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
17Copyright @copyright{} 1995-2014 Free Software Foundation,
18Inc.
19
20Permission is granted to copy, distribute and/or modify this document
21under the terms of the GNU Free Documentation License, Version 1.3 or
22any later version published by the Free Software Foundation; with no
23Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24Texts.  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
160GNAT, The GNU Ada Development Environment@*
161GCC version @value{version-GCC}@*
162
163@noindent
164AdaCore@*
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
232This guide describes the use of @value{EDITION},
233a compiler and software development toolset for the full Ada
234programming language, implemented on OpenVMS for HP's Alpha and
235Integrity server (I64) platforms.
236@end ifset
237@ifclear vms
238This guide describes the use of @value{EDITION},
239a compiler and software development
240toolset for the full Ada programming language.
241@end ifclear
242It documents the features of the compiler and tools, and explains
243how to use them to build Ada applications.
244
245@value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
246invoked in Ada 83 compatibility mode.
247By default, @value{EDITION} assumes Ada 2012, but you can override with a
248compiler switch (@pxref{Compiling Different Versions of Ada})
249to explicitly specify the language version.
250Throughout this manual, references to ``Ada'' without a year suffix
251apply to all Ada 95/2005/2012 versions of the language.
252
253@ifclear FSFEDITION
254For 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
270This guide contains the following chapters:
271@itemize @bullet
272
273@item
274@ref{Getting Started with GNAT}, describes how to get started compiling
275and running Ada programs with the GNAT Ada programming environment.
276@item
277@ref{The GNAT Compilation Model}, describes the compilation model used
278by GNAT.
279
280@item
281@ref{Compiling with gcc}, describes how to compile
282Ada programs with @command{gcc}, the Ada compiler.
283
284@item
285@ref{Binding with gnatbind}, describes how to
286perform binding of Ada programs with @code{gnatbind}, the GNAT binding
287utility.
288
289@item
290@ref{Linking with gnatlink},
291describes @command{gnatlink}, a
292program that provides for linking using the GNAT run-time library to
293construct a program. @command{gnatlink} can also incorporate foreign language
294object units into the executable.
295
296@item
297@ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
298utility that automatically determines the set of sources
299needed by an Ada compilation unit, and executes the necessary compilations
300binding and link.
301
302@item
303@ref{Improving Performance}, shows various techniques for making your
304Ada program run faster or take less space and describes the effect of
305the compiler's optimization switch.
306It also describes
307@ifclear FSFEDITION
308the @command{gnatelim} tool and
309@end ifclear
310unused 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
315contains Ada source code, and split it into one or more new files, one
316for each compilation unit.
317
318@item
319@ref{Configuration Pragmas}, describes the configuration pragmas
320handled by GNAT.
321
322@item
323@ref{Handling Arbitrary File Naming Conventions with gnatname},
324shows how to override the default GNAT file naming conventions,
325either for an individual unit or globally.
326
327@item
328@ref{GNAT Project Manager}, describes how to use project files
329to 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
334way to navigate through sources.
335
336@ifclear FSFEDITION
337@item
338@ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
339version of an Ada source file with control over casing, indentation,
340comment 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
347source 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
354metrics for an Ada source file, such as the number of types and subprograms,
355and assorted complexity measures.
356@end ifclear
357
358@item
359@ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
360file name krunching utility, used to handle shortened
361file names on operating systems with a limit on the length of names.
362
363@item
364@ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
365preprocessor utility that allows a single source file to be used to
366generate multiple or parameterized source files by means of macro
367substitution.
368
369@item
370@ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
371utility that displays information about compiled units, including dependences
372on the corresponding sources files, and consistency of compilations.
373
374@item
375@ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
376to 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
381Libraries with GNAT. It also describes how to recompile the GNAT run-time
382library.
383
384@item
385@ref{Using the GNU make Utility}, describes some techniques for using
386the GNAT toolset in Makefiles.
387@end ifclear
388
389@item
390@ref{Memory Management Issues}, describes some useful predefined storage pools
391and in particular the GNAT Debug Pool facility, which helps detect incorrect
392memory references.
393@ifclear vms
394@ifclear FSFEDITION
395It also describes @command{gnatmem}, a utility that monitors dynamic
396allocation 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
402stack checking and analysis.
403
404@ifclear FSFEDITION
405@item
406@ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
407a utility that checks Ada code against a set of rules.
408
409@item
410@ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
411a 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},
417a 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
422facilities used in GNAT to declare dimensioned objects, and to verify that
423uses 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
428generate automatically Ada bindings from C and C++ headers.
429
430@item
431@ref{Other Utility Programs}, discusses several other GNAT utilities,
432including @code{gnathtml}.
433
434@ifclear vms
435@item
436@ref{Code Coverage and Profiling}, describes how to perform a structural
437coverage 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
442Ada programs.
443
444@ifset vms
445@item
446@ref{Compatibility with HP Ada}, details the compatibility of GNAT with
447HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
448developed by Digital Equipment Corporation and currently supported by HP.}
449for OpenVMS Alpha. This product was formerly known as DEC Ada,
450@cindex DEC Ada
451and for
452historical compatibility reasons, the relevant libraries still use the
453DEC prefix.
454@end ifset
455
456@item
457@ref{Platform-Specific Information for the Run-Time Libraries},
458describes the various run-time
459libraries supported by GNAT on various platforms and explains how to
460choose a particular library.
461
462@item
463@ref{Example of Binder Output File}, shows the source code for the binder
464output file for a sample program.
465
466@item
467@ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
468you deal with elaboration order issues.
469
470@item
471@ref{Overflow Check Handling in GNAT}, describes how GNAT helps
472you deal with arithmetic overflow issues.
473
474@item
475@ref{Conditional Compilation}, describes how to model conditional compilation,
476both 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
480in an Ada program.
481
482@item
483@ref{Compatibility and Porting Guide}, contains sections on compatibility
484of GNAT with other Ada development environments (including Ada 83 systems),
485to assist in porting code from those environments.
486
487@ifset unw
488@item
489@ref{Microsoft Windows Topics}, presents information relevant to the
490Microsoft Windows platform.
491
492@item
493@ref{Mac OS Topics}, presents information relevant to Apple's OS X
494platform.
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
506This guide assumes a basic familiarity with the Ada 95 language, as
507described in the International Standard ANSI/ISO/IEC-8652:1995, January
5081995.
509It does not require knowledge of the new features introduced by Ada 2005,
510(officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
511and Amendment 1).
512Both reference manuals are included in the GNAT documentation
513package.
514
515@node Related Information
516@unnumberedsec Related Information
517
518@noindent
519For further information about related tools, refer to the following
520documents:
521
522@itemize @bullet
523@item
524@xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
525Reference Manual}, which contains all reference material for the GNAT
526implementation of Ada.
527
528@ifset unw
529@item
530@cite{Using the GNAT Programming Studio}, which describes the GPS
531Integrated Development Environment.
532
533@item
534@cite{GNAT Programming Studio Tutorial}, which introduces the
535main GPS features through examples.
536@end ifset
537
538@item
539@cite{Ada 95 Reference Manual}, which contains reference
540material for the Ada 95 programming language.
541
542@item
543@cite{Ada 2005 Reference Manual}, which contains reference
544material for the Ada 2005 programming language.
545
546@item
547@xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
548@ifset vms
549in the GNU:[DOCS] directory,
550@end ifset
551for all details on the use of the GNU source-level debugger.
552
553@item
554@xref{Top,, The extensible self-documenting text editor, emacs,
555GNU Emacs Manual},
556@ifset vms
557located in the GNU:[DOCS] directory if the EMACS kit is installed,
558@end ifset
559for full information on the extensible editor and programming
560environment Emacs.
561
562@end itemize
563
564@c **************
565@node Conventions
566@unnumberedsec Conventions
567@cindex Conventions
568@cindex Typographical conventions
569
570@noindent
571Following are examples of the typographical and graphic conventions used
572in this guide:
573
574@itemize @bullet
575@item
576@code{Functions}, @command{utility program names}, @code{standard names},
577and @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
587variables}.
588
589@item
590@emph{Emphasis}.
591
592@item
593@r{[}optional information or parameters@r{]}
594
595@item
596Examples are described by text
597@smallexample
598and then shown this way.
599@end smallexample
600@end itemize
601
602@noindent
603Commands that are entered by the user are preceded in this manual by the
604characters @w{``@code{$ }''} (dollar sign followed by space). If your system
605uses this sequence as a prompt, then the commands will appear exactly as
606you see them in the manual. If your system uses some other prompt, then
607the command will appear with the @code{$} replaced by whatever prompt
608character you are using.
609
610@ifset unw
611Full file names are shown with the ``@code{/}'' character
612as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
613If you are using GNAT on a Windows platform, please note that
614the ``@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
622This chapter describes some simple ways of using GNAT to build
623executable Ada programs.
624@ifset unw
625@ref{Running GNAT}, through @ref{Using the gnatmake Utility},
626show how to use the command line environment.
627@ref{Introduction to GPS}, provides a brief
628introduction to the GNAT Programming Studio, a visually-oriented
629Integrated Development Environment for GNAT.
630GPS offers a graphical ``look and feel'', support for development in
631other programming languages, comprehensive browsing features, and
632many other capabilities.
633For 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
654Three steps are needed to create an executable file from an Ada source
655file:
656
657@enumerate
658@item
659The source file(s) must be compiled.
660@item
661The file(s) must be bound using the GNAT binder.
662@item
663All appropriate object files must be linked to produce an executable.
664@end enumerate
665
666@noindent
667All three steps are most commonly handled by using the @command{gnatmake}
668utility program that, given the name of the main program, automatically
669performs 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
675Any text editor may be used to prepare an Ada program.
676(If @code{Emacs} is
677used, the optional Ada mode may be helpful in laying out the program.)
678The
679program text is a normal text file. We will assume in our initial
680example that you have used your editor to prepare the following
681standard format text file:
682
683@smallexample @c ada
684@cartouche
685with Ada.Text_IO; use Ada.Text_IO;
686procedure Hello is
687begin
688   Put_Line ("Hello WORLD!");
689end Hello;
690@end cartouche
691@end smallexample
692
693@noindent
694This file should be named @file{hello.adb}.
695With the normal default file naming conventions, GNAT requires
696that each file
697contain a single compilation unit whose file name is the
698unit name,
699with periods replaced by hyphens; the
700extension is @file{ads} for a
701spec and @file{adb} for a body.
702You can override this default file naming convention by use of the
703special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
704Alternatively, if you want to rename your files according to this default
705convention, which is probably more convenient if you will be using GNAT
706for all your compilations, then the @code{gnatchop} utility
707can be used to generate correctly-named source files
708(@pxref{Renaming Files with gnatchop}).
709
710You can compile the program using the following command (@code{$} is used
711as 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
719capable of compiling programs in several languages, including Ada and
720C. It assumes that you have given it an Ada program if the file extension is
721either @file{.ads} or @file{.adb}, and it will then call
722the GNAT compiler to compile the specified file.
723
724@ifclear vms
725The @option{-c} switch is required. It tells @command{gcc} to only do a
726compilation. (For C programs, @command{gcc} can also do linking, but this
727capability is not used directly for Ada programs, so the @option{-c}
728switch must always be present.)
729@end ifclear
730
731This compile command generates a file
732@file{hello.o}, which is the object
733file corresponding to your Ada program. It also generates
734an ``Ada Library Information'' file @file{hello.ali},
735which contains additional information used to check
736that an Ada program is consistent.
737To build an executable file,
738use @code{gnatbind} to bind the program
739and @command{gnatlink} to link it. The
740argument to both @code{gnatbind} and @command{gnatlink} is the name of the
741@file{ALI} file, but the default extension of @file{.ali} can
742be omitted. This means that in the most common case, the argument
743is simply the name of the main program:
744
745@smallexample
746$ gnatbind hello
747$ gnatlink hello
748@end smallexample
749
750@noindent
751A simpler method of carrying out these steps is to use
752@command{gnatmake},
753a master program that invokes all the required
754compilation, binding and linking tools in the correct order. In particular,
755@command{gnatmake} automatically recompiles any sources that have been
756modified since they were last compiled, or sources that depend
757on 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
765The result is an executable program called @file{hello}, which can be
766run by entering:
767
768@smallexample
769$ ^hello^RUN HELLO^
770@end smallexample
771
772@noindent
773assuming that the current directory is on the search path
774for executable programs.
775
776@noindent
777and, if all has gone well, you will see
778
779@smallexample
780Hello WORLD!
781@end smallexample
782
783@noindent
784appear 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
791Consider a slightly more complicated example that has three files: a
792main program, and the spec and body of a package:
793
794@smallexample @c ada
795@cartouche
796@group
797package Greetings is
798   procedure Hello;
799   procedure Goodbye;
800end Greetings;
801
802with Ada.Text_IO; use Ada.Text_IO;
803package 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;
813end Greetings;
814@end group
815
816@group
817with Greetings;
818procedure Gmain is
819begin
820   Greetings.Hello;
821   Greetings.Goodbye;
822end Gmain;
823@end group
824@end cartouche
825@end smallexample
826
827@noindent
828Following the one-unit-per-file rule, place this program in the
829following three separate files:
830
831@table @file
832@item greetings.ads
833spec of package @code{Greetings}
834
835@item greetings.adb
836body of package @code{Greetings}
837
838@item gmain.adb
839body of main program
840@end table
841
842@noindent
843To build an executable version of
844this program, we could use four separate steps to compile, bind, and link
845the 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
855Note that there is no required order of compilation when using GNAT.
856In particular it is perfectly fine to compile the main program first.
857Also, it is not necessary to compile package specs in the case where
858there is an accompanying body; you only need to compile the body. If you want
859to submit these files to the compiler for semantic checking and not code
860generation, then use the
861@option{-gnatc} switch:
862
863@smallexample
864$ gcc -c greetings.ads -gnatc
865@end smallexample
866
867@noindent
868Although the compilation can be done in separate steps as in the
869above example, in practice it is almost always more convenient
870to use the @command{gnatmake} tool. All you need to know in this case
871is the name of the main program's source file. The effect of the above four
872commands can be achieved with a single one:
873
874@smallexample
875$ gnatmake gmain.adb
876@end smallexample
877
878@noindent
879In the next section we discuss the advantages of using @command{gnatmake} in
880more detail.
881
882@c *****************************
883@node Using the gnatmake Utility
884@section Using the @command{gnatmake} Utility
885
886@noindent
887If 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
889build a consistent system, you compile not only these units, but also any
890units that depend on the units you have modified.
891For example, in the preceding case,
892if you edit @file{gmain.adb}, you only need to recompile that file. But if
893you edit @file{greetings.ads}, you must recompile both
894@file{greetings.adb} and @file{gmain.adb}, because both files contain
895units that depend on @file{greetings.ads}.
896
897@code{gnatbind} will warn you if you forget one of these compilation
898steps, so that it is impossible to generate an inconsistent program as a
899result of forgetting to do a compilation. Nevertheless it is tedious and
900error-prone to keep track of dependencies among units.
901One approach to handle the dependency-bookkeeping is to use a
902makefile. However, makefiles present maintenance problems of their own:
903if the dependencies change as you change the program, you must make
904sure that the makefile is kept up-to-date manually, which is also an
905error-prone process.
906
907The @command{gnatmake} utility takes care of these details automatically.
908Invoke 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
916The argument is the name of the file containing the main program;
917you may omit the extension. @command{gnatmake}
918examines the environment, automatically recompiles any files that need
919recompiling, and binds and links the resulting set of object files,
920generating the executable file, @file{^gmain^GMAIN.EXE^}.
921In a large program, it
922can be extremely helpful to use @command{gnatmake}, because working out by hand
923what needs to be recompiled can be difficult.
924
925Note that @command{gnatmake}
926takes into account all the Ada rules that
927establish dependencies among units. These include dependencies that result
928from inlining subprogram bodies, and from
929generic instantiation. Unlike some other
930Ada make tools, @command{gnatmake} does not rely on the dependencies that were
931found by the compiler on a previous compilation, which may possibly
932be wrong when sources change. @command{gnatmake} determines the exact set of
933dependencies 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
941Emacs is an extensible self-documenting text editor that is available in a
942separate VMSINSTAL kit.
943
944Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
945click on the Emacs Help menu and run the Emacs Tutorial.
946In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
947written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
948
949Documentation on Emacs and other tools is available in Emacs under the
950pull-down menu button: @code{Help - Info}. After selecting @code{Info},
951use the middle mouse button to select a topic (e.g.@: Emacs).
952
953In 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
955get to the Emacs manual.
956Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
957prompt.
958
959The tutorial is highly recommended in order to learn the intricacies of Emacs,
960which is sufficiently extensible to provide for a complete programming
961environment 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
970Although the command line interface (@command{gnatmake}, etc.) alone
971is sufficient, a graphical Interactive Development
972Environment can make it easier for you to compose, navigate, and debug
973programs.  This section describes the main features of GPS
974(``GNAT Programming Studio''), the GNAT graphical IDE.
975You will see how to use GPS to build and debug an executable, and
976you will also learn some of the basics of the GNAT ``project'' facility.
977
978GPS enables you to do much more than is presented here;
979e.g., you can produce a call graph, interface to a third-party
980Version Control System, and inspect the generated assembly language
981for a program.
982Indeed, GPS also supports languages other than Ada.
983Such additional information, and an explanation of all of the GPS menu
984items. may be found in the on-line help, which includes
985a user's guide and a tutorial (these are also accessible from the GNAT
986startup 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
996GPS invokes the GNAT compilation tools using information
997contained in a @emph{project} (also known as a @emph{project file}):
998a collection of properties such
999as source directories, identities of main subprograms, tool switches, etc.,
1000and their associated values.
1001See @ref{GNAT Project Manager} for details.
1002In order to run GPS, you will need to either create a new project
1003or else open an existing one.
1004
1005This section will explain how you can use GPS to create a project,
1006to associate Ada source files with a project, and to build and run
1007programs.
1008
1009@enumerate
1010@item @emph{Creating a project}
1011
1012Invoke GPS, either from the command line or the platform's IDE.
1013After it starts, GPS will display a ``Welcome'' screen with three
1014radio 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
1028Select @code{Create new project with wizard} and press @code{OK}.
1029A new window will appear.  In the text box labeled with
1030@code{Enter the name of the project to create}, type @file{sample}
1031as the project name.
1032In the next box, browse to choose the directory in which you
1033would like to create the project file.
1034After selecting an appropriate directory, press @code{Forward}.
1035
1036A window will appear with the title
1037@code{Version Control System Configuration}.
1038Simply press @code{Forward}.
1039
1040A window will appear with the title
1041@code{Please select the source directories for this project}.
1042The directory that you specified for the project file will be selected
1043by default as the one to use for sources; simply press @code{Forward}.
1044
1045A window will appear with the title
1046@code{Please select the build directory for this project}.
1047The directory that you specified for the project file will be selected
1048by default for object files and executables;
1049simply press @code{Forward}.
1050
1051A window will appear with the title
1052@code{Please select the main units for this project}.
1053You will supply this information later, after creating the source file.
1054Simply press @code{Forward} for now.
1055
1056A window will appear with the title
1057@code{Please select the switches to build the project}.
1058Press @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
1063After you create the new project, a GPS window will appear, which is
1064partitioned into two main sections:
1065
1066@itemize @bullet
1067@item
1068A @emph{Workspace area}, initially greyed out, which you will use for
1069creating and editing source files
1070
1071@item
1072Directly 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
1078Select @code{File} on the menu bar, and then the @code{New} command.
1079The Workspace area will become white, and you can now
1080enter the source program explicitly.
1081Type the following text
1082
1083@smallexample @c ada
1084@group
1085with Ada.Text_IO; use Ada.Text_IO;
1086procedure Hello is
1087begin
1088  Put_Line("Hello from GPS!");
1089end Hello;
1090@end group
1091@end smallexample
1092
1093@noindent
1094Select @code{File}, then @code{Save As}, and enter the source file name
1095@file{hello.adb}.
1096The file will be saved in the same directory you specified as the
1097location of the default project file.
1098
1099@item @emph{Updating the project file}
1100
1101You need to add the new source file to the project.
1102To do this, select
1103the @code{Project} menu and then @code{Edit project properties}.
1104Click the @code{Main files} tab on the left, and then the
1105@code{Add} button.
1106Choose @file{hello.adb} from the list, and press @code{Open}.
1107The project settings window will reflect this action.
1108Click @code{OK}.
1109
1110@item @emph{Building and running the program}
1111
1112In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1113and select @file{hello.adb}.
1114The Messages window will display the resulting invocations of @command{gcc},
1115@command{gnatbind}, and @command{gnatlink}
1116(reflecting the default switch settings from the
1117project file that you created) and then a ``successful compilation/build''
1118message.
1119
1120To run the program, choose the @code{Build} menu, then @code{Run}, and
1121select @command{hello}.
1122An @emph{Arguments Selection} window will appear.
1123There are no command line arguments, so just click @code{OK}.
1124
1125The 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
1127update is displayed (@code{Run: hello}).
1128Close the GPS window (or select @code{File}, then @code{Exit}) to
1129terminate this GPS session.
1130@end enumerate
1131
1132@node Simple Debugging with GPS
1133@subsection Simple Debugging with GPS
1134@noindent
1135This section illustrates basic debugging techniques (setting breakpoints,
1136examining/modifying variables, single stepping).
1137
1138@enumerate
1139@item @emph{Opening a project}
1140
1141Start GPS and select @code{Open existing project}; browse to
1142specify the project file @file{sample.prj} that you had created in the
1143earlier example.
1144
1145@item @emph{Creating a source file}
1146
1147Select @code{File}, then @code{New}, and type in the following program:
1148
1149@smallexample @c ada
1150@group
1151with Ada.Text_IO; use Ada.Text_IO;
1152procedure Example is
1153   Line : String (1..80);
1154   N    : Natural;
1155begin
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;
1163end Example;
1164@end group
1165@end smallexample
1166
1167@noindent
1168Select @code{File}, then @code{Save as}, and enter the file name
1169@file{example.adb}.
1170
1171@item @emph{Updating the project file}
1172
1173Add @code{Example} as a new main unit for the project:
1174@enumerate a
1175@item
1176Select @code{Project}, then @code{Edit Project Properties}.
1177
1178@item
1179Select the @code{Main files} tab, click @code{Add}, then
1180select the file @file{example.adb} from the list, and
1181click @code{Open}.
1182You will see the file name appear in the list of main units
1183
1184@item
1185Click @code{OK}
1186@end enumerate
1187
1188@item @emph{Building/running the executable}
1189
1190To build the executable
1191select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1192
1193Run the program to see its effect (in the Messages area).
1194Each line that you enter is displayed; an empty line will
1195cause the loop to exit and the program to terminate.
1196
1197@item @emph{Debugging the program}
1198
1199Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1200which are required for debugging, are on by default when you create
1201a new project.
1202Thus unless you intentionally remove these settings, you will be able
1203to debug any program that you develop using GPS.
1204
1205@enumerate a
1206@item @emph{Initializing}
1207
1208Select @code{Debug}, then @code{Initialize}, then @file{example}
1209
1210@item @emph{Setting a breakpoint}
1211
1212After performing the initialization step, you will observe a small
1213icon to the right of each line number.
1214This serves as a toggle for breakpoints; clicking the icon will
1215set a breakpoint at the corresponding line (the icon will change to
1216a red circle with an ``x''), and clicking it again
1217will remove the breakpoint / reset the icon.
1218
1219For purposes of this example, set a breakpoint at line 10 (the
1220statement @code{Put_Line@ (Line@ (1..N));}
1221
1222@item @emph{Starting program execution}
1223
1224Select @code{Debug}, then @code{Run}.  When the
1225@code{Program Arguments} window appears, click @code{OK}.
1226A console window will appear; enter some line of text,
1227e.g.@: @code{abcde}, at the prompt.
1228The program will pause execution when it gets to the
1229breakpoint, and the corresponding line is highlighted.
1230
1231@item @emph{Examining a variable}
1232
1233Move the mouse over one of the occurrences of the variable @code{N}.
1234You will see the value (5) displayed, in ``tool tip'' fashion.
1235Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1236You will see information about @code{N} appear in the @code{Debugger Data}
1237pane, showing the value as 5.
1238
1239@item @emph{Assigning a new value to a variable}
1240
1241Right click on the @code{N} in the @code{Debugger Data} pane, and
1242select @code{Set value of N}.
1243When the input window appears, enter the value @code{4} and click
1244@code{OK}.
1245This value does not automatically appear in the @code{Debugger Data}
1246pane; to see it, right click again on the @code{N} in the
1247@code{Debugger Data} pane and select @code{Update value}.
1248The new value, 4, will appear in red.
1249
1250@item @emph{Single stepping}
1251
1252Select @code{Debug}, then @code{Next}.
1253This will cause the next statement to be executed, in this case the
1254call of @code{Put_Line} with the string slice.
1255Notice in the console window that the displayed string is simply
1256@code{abcd} and not @code{abcde} which you had entered.
1257This is because the upper bound of the slice is now 4 rather than 5.
1258
1259@item @emph{Removing a breakpoint}
1260
1261Toggle the breakpoint icon at line 10.
1262
1263@item @emph{Resuming execution from a breakpoint}
1264
1265Select @code{Debug}, then @code{Continue}.
1266The program will reach the next iteration of the loop, and
1267wait for input after displaying the prompt.
1268This time, just hit the @kbd{Enter} key.
1269The value of @code{N} will be 0, and the program will terminate.
1270The 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
1302This chapter describes the compilation model used by GNAT. Although
1303similar to that used by other languages, such as C and C++, this model
1304is substantially different from the traditional Ada compilation models,
1305which are based on a library. The model is initially described without
1306reference to the library-based model. If you have not previously used an
1307Ada compiler, you need only read the first part of this chapter. The
1308last section describes and discusses the differences between the GNAT
1309model and the traditional Ada compiler models. If you have used other
1310Ada compilers, this section will help you to understand those
1311differences, and the advantages of the GNAT model.
1312
1313@node Source Representation
1314@section Source Representation
1315@cindex Latin-1
1316
1317@noindent
1318Ada source programs are represented in standard text files, using
1319Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
13207-bit ASCII set, plus additional characters used for
1321representing foreign languages (@pxref{Foreign Language Representation}
1322for support of non-USA character sets). The format effector characters
1323are represented using their standard ASCII encodings, as follows:
1324
1325@table @code
1326@item VT
1327@findex VT
1328Vertical tab, @code{16#0B#}
1329
1330@item HT
1331@findex HT
1332Horizontal tab, @code{16#09#}
1333
1334@item CR
1335@findex CR
1336Carriage return, @code{16#0D#}
1337
1338@item LF
1339@findex LF
1340Line feed, @code{16#0A#}
1341
1342@item FF
1343@findex FF
1344Form feed, @code{16#0C#}
1345@end table
1346
1347@noindent
1348Source files are in standard text file format. In addition, GNAT will
1349recognize a wide variety of stream formats, in which the end of
1350physical lines is marked by any of the following sequences:
1351@code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1352in accommodating files that are imported from other operating systems.
1353
1354@cindex End of source file
1355@cindex Source file, end
1356@findex SUB
1357The end of a source file is normally represented by the physical end of
1358file. However, the control character @code{16#1A#} (@code{SUB}) is also
1359recognized as signalling the end of the source file. Again, this is
1360provided for compatibility with other operating systems where this
1361code is used to represent the end of file.
1362
1363Each file contains a single Ada compilation unit, including any pragmas
1364associated with the unit. For example, this means you must place a
1365package declaration (a package @dfn{spec}) and the corresponding body in
1366separate files. An Ada @dfn{compilation} (which is a sequence of
1367compilation units) is represented using a sequence of files. Similarly,
1368you 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
1374GNAT supports the standard character sets defined in Ada as well as
1375several other non-standard character sets for use in localized versions
1376of 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
1388The basic character set is Latin-1. This character set is defined by ISO
1389standard 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
1391half is used to represent additional characters. These include extended letters
1392used by European languages, such as French accents, the vowels with umlauts
1393used in German, and the extra letter A-ring used in Swedish.
1394
1395@findex Ada.Characters.Latin_1
1396For a complete list of Latin-1 codes and their encodings, see the source
1397file of library unit @code{Ada.Characters.Latin_1} in file
1398@file{a-chlat1.ads}.
1399You may use any of these extended characters freely in character or
1400string literals. In addition, the extended characters that represent
1401letters can be used in identifiers.
1402
1403@node Other 8-Bit Codes
1404@subsection Other 8-Bit Codes
1405
1406@noindent
1407GNAT 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
1413Latin-2 letters allowed in identifiers, with uppercase and lowercase
1414equivalence.
1415
1416@item ISO 8859-3 (Latin-3)
1417@cindex Latin-3
1418@cindex ISO 8859-3
1419Latin-3 letters allowed in identifiers, with uppercase and lowercase
1420equivalence.
1421
1422@item ISO 8859-4 (Latin-4)
1423@cindex Latin-4
1424@cindex ISO 8859-4
1425Latin-4 letters allowed in identifiers, with uppercase and lowercase
1426equivalence.
1427
1428@item ISO 8859-5 (Cyrillic)
1429@cindex ISO 8859-5
1430@cindex Cyrillic
1431ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1432lowercase equivalence.
1433
1434@item ISO 8859-15 (Latin-9)
1435@cindex ISO 8859-15
1436@cindex Latin-9
1437ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1438lowercase equivalence
1439
1440@item IBM PC (code page 437)
1441@cindex code page 437
1442This code page is the normal default for PCs in the U.S. It corresponds
1443to the original IBM PC character set. This set has some, but not all, of
1444the extended Latin-1 letters, but these letters do not have the same
1445encoding as Latin-1. In this mode, these letters are allowed in
1446identifiers with uppercase and lowercase equivalence.
1447
1448@item IBM PC (code page 850)
1449@cindex code page 850
1450This code page is a modification of 437 extended to include all the
1451Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1452mode, all these letters are allowed in identifiers with uppercase and
1453lowercase equivalence.
1454
1455@item Full Upper 8-bit
1456Any character in the range 80-FF allowed in identifiers, and all are
1457considered distinct. In other words, there are no uppercase and lowercase
1458equivalences in this range. This is useful in conjunction with
1459certain encoding schemes used for some foreign character sets (e.g.,
1460the typical method of representing Chinese characters on the PC).
1461
1462@item No Upper-Half
1463No upper-half characters in the range 80-FF are allowed in identifiers.
1464This gives Ada 83 compatibility for identifier names.
1465@end table
1466
1467@noindent
1468For precise data on the encodings permitted, and the uppercase and lowercase
1469equivalences that are recognized, see the file @file{csets.adb} in
1470the GNAT compiler sources. You will need to obtain a full source release
1471of GNAT to obtain this file.
1472
1473@node Wide Character Encodings
1474@subsection Wide Character Encodings
1475
1476@noindent
1477GNAT allows wide character codes to appear in character and string
1478literals, and also optionally in identifiers, by means of the following
1479possible encoding schemes:
1480
1481@table @asis
1482
1483@item Hex Coding
1484In this encoding, a wide character is represented by the following five
1485character sequence:
1486
1487@smallexample
1488ESC a b c d
1489@end smallexample
1490
1491@noindent
1492Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1493characters (using uppercase letters) of the wide character code. For
1494example, ESC A345 is used to represent the wide character with code
1495@code{16#A345#}.
1496This scheme is compatible with use of the full Wide_Character set.
1497
1498@item Upper-Half Coding
1499@cindex Upper-Half Coding
1500The 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
1503character, but is not required to be in the upper half. This method can
1504be also used for shift-JIS or EUC, where the internal coding matches the
1505external coding.
1506
1507@item Shift JIS Coding
1508@cindex Shift JIS Coding
1509A 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
1512described above. The internal character code is the corresponding JIS
1513character according to the standard algorithm for Shift-JIS
1514conversion. Only characters defined in the JIS code set table can be
1515used with this encoding method.
1516
1517@item EUC Coding
1518@cindex EUC Coding
1519A 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
1522character code is the corresponding JIS character according to the EUC
1523encoding algorithm. Only characters defined in the JIS code set table
1524can be used with this encoding method.
1525
1526@item UTF-8 Coding
1527A wide character is represented using
1528UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
152910646-1/Am.2. Depending on the character value, the representation
1530is a one, two, or three byte sequence:
1531@smallexample
1532@iftex
1533@leftskip=.7cm
1534@end iftex
153516#0000#-16#007f#: 2#0@var{xxxxxxx}#
153616#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
153716#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1538
1539@end smallexample
1540
1541@noindent
1542where the @var{xxx} bits correspond to the left-padded bits of the
154316-bit character value. Note that all lower half ASCII characters
1544are represented as ASCII bytes and all upper half characters and
1545other wide characters are represented as sequences of upper-half
1546(The full UTF-8 scheme allows for encoding 31-bit characters as
15476-byte sequences, but in this implementation, all UTF-8 sequences
1548of four or more bytes length will be treated as illegal).
1549@item Brackets Coding
1550In this encoding, a wide character is represented by the following eight
1551character sequence:
1552
1553@smallexample
1554[ " a b c d " ]
1555@end smallexample
1556
1557@noindent
1558Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1559characters (using uppercase letters) of the wide character code. For
1560example, [``A345''] is used to represent the wide character with code
1561@code{16#A345#}. It is also possible (though not required) to use the
1562Brackets coding for upper half characters. For example, the code
1563@code{16#A3#} can be represented as @code{[``A3'']}.
1564
1565This scheme is compatible with use of the full Wide_Character set,
1566and is also the method used for wide character encoding in the standard
1567ACVC (Ada Compiler Validation Capability) test suite distributions.
1568
1569@end table
1570
1571@noindent
1572Note: Some of these coding schemes do not permit the full use of the
1573Ada character set. For example, neither Shift JIS, nor EUC allow the
1574use of the upper half of the Latin-1 set.
1575
1576@node File Naming Rules
1577@section File Naming Rules
1578
1579@noindent
1580The default file name is determined by the name of the unit that the
1581file contains. The name is formed by taking the full expanded name of
1582the unit and replacing the separating dots with hyphens and using
1583^lowercase^uppercase^ for all letters.
1584
1585An exception arises if the file name generated by the above rules starts
1586with 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
1593and the second character is a
1594minus. In this case, the character ^tilde^dollar sign^ is used in place
1595of the minus. The reason for this special rule is to avoid clashes with
1596the standard names for child units of the packages System, Ada,
1597Interfaces, 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
1604respectively.
1605
1606The file extension is @file{.ads} for a spec and
1607@file{.adb} for a body. The following list shows some
1608examples of these rules.
1609
1610@table @file
1611@item main.ads
1612Main (spec)
1613@item main.adb
1614Main (body)
1615@item arith_functions.ads
1616Arith_Functions (package spec)
1617@item arith_functions.adb
1618Arith_Functions (package body)
1619@item func-spec.ads
1620Func.Spec (child package spec)
1621@item func-spec.adb
1622Func.Spec (child package body)
1623@item main-sub.adb
1624Sub (subunit of Main)
1625@item ^a~bad.adb^A$BAD.ADB^
1626A.Bad (child package body)
1627@end table
1628
1629@noindent
1630Following these rules can result in excessively long
1631file names if corresponding
1632unit names are long (for example, if child units or subunits are
1633heavily nested). An option is available to shorten such long file names
1634(called file name ``krunching''). This may be particularly useful when
1635programs being developed with GNAT are to be used on operating systems
1636with limited file name lengths. @xref{Using gnatkr}.
1637
1638Of course, no file shortening algorithm can guarantee uniqueness over
1639all possible unit names; if file name krunching is used, it is your
1640responsibility to ensure no name clashes occur. Alternatively you
1641can specify the exact file names that you want used, as described
1642in the next section. Finally, if your Ada programs are migrating from a
1643compiler with a different naming convention, you can use the gnatchop
1644utility to produce source files that follow the GNAT naming conventions.
1645(For details @pxref{Renaming Files with gnatchop}.)
1646
1647Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1648systems, case is not significant. So for example on @code{Windows XP}
1649if 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
1651operating systems, so for example, if you want to use other than
1652canonically cased file names on a Unix system, you need to follow
1653the 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
1660In the previous section, we have described the default rules used by
1661GNAT to determine the file name in which a given unit resides. It is
1662often convenient to follow these default rules, and if you follow them,
1663the compiler knows without being explicitly told where to find all
1664the files it needs.
1665
1666However, in some cases, particularly when a program is imported from
1667another Ada compiler environment, it may be more convenient for the
1668programmer to specify which file names contain which units. GNAT allows
1669arbitrary file names to be used by means of the Source_File_Name pragma.
1670The form of this pragma is as shown in the following examples:
1671@cindex Source_File_Name pragma
1672
1673@smallexample @c ada
1674@cartouche
1675pragma Source_File_Name (My_Utilities.Stacks,
1676  Spec_File_Name => "myutilst_a.ada");
1677pragma Source_File_name (My_Utilities.Stacks,
1678  Body_File_Name => "myutilst.ada");
1679@end cartouche
1680@end smallexample
1681
1682@noindent
1683As shown in this example, the first argument for the pragma is the unit
1684name (in this example a child unit). The second argument has the form
1685of a named association. The identifier
1686indicates whether the file name is for a spec or a body;
1687the file name itself is given by a string literal.
1688
1689The source file name pragma is a configuration pragma, which means that
1690normally it will be placed in the @file{gnat.adc}
1691file used to hold configuration
1692pragmas that apply to a complete compilation environment.
1693For more details on how the @file{gnat.adc} file is created and used
1694see @ref{Handling of Configuration Pragmas}.
1695@cindex @file{gnat.adc}
1696
1697@ifclear vms
1698GNAT allows completely arbitrary file names to be specified using the
1699source file name pragma. However, if the file name specified has an
1700extension other than @file{.ads} or @file{.adb} it is necessary to use
1701a special syntax when compiling the file. The name in this case must be
1702preceded by the special sequence @option{-x} followed by a space and the name
1703of 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
1712non-standard file name for the main program is simply used as the
1713argument to gnatmake). Note that if the extension is also non-standard,
1714then it must be included in the @command{gnatmake} command, it may not
1715be 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
1722In the previous section, we described the use of the @code{Source_File_Name}
1723pragma to allow arbitrary names to be assigned to individual source files.
1724However, this approach requires one pragma for each file, and especially in
1725large systems can result in very long @file{gnat.adc} files, and also create
1726a maintenance problem.
1727
1728GNAT also provides a facility for specifying systematic file naming schemes
1729other than the standard default naming scheme previously described. An
1730alternative 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
1735pragma Source_File_Name (
1736   Spec_File_Name  => FILE_NAME_PATTERN
1737 @r{[},Casing          => CASING_SPEC@r{]}
1738 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1739
1740pragma Source_File_Name (
1741   Body_File_Name  => FILE_NAME_PATTERN
1742 @r{[},Casing          => CASING_SPEC@r{]}
1743 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1744
1745pragma Source_File_Name (
1746   Subunit_File_Name  => FILE_NAME_PATTERN
1747 @r{[},Casing             => CASING_SPEC@r{]}
1748 @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
1749
1750FILE_NAME_PATTERN ::= STRING_LITERAL
1751CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1752@end smallexample
1753
1754@noindent
1755The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1756It contains a single asterisk character, and the unit name is substituted
1757systematically for this asterisk. The optional parameter
1758@code{Casing} indicates
1759whether the unit name is to be all upper-case letters, all lower-case letters,
1760or mixed-case. If no
1761@code{Casing} parameter is used, then the default is all
1762^lower-case^upper-case^.
1763
1764The optional @code{Dot_Replacement} string is used to replace any periods
1765that occur in subunit or child unit names. If no @code{Dot_Replacement}
1766argument is used then separating dots appear unchanged in the resulting
1767file name.
1768Although the above syntax indicates that the
1769@code{Casing} argument must appear
1770before the @code{Dot_Replacement} argument, but it
1771is also permissible to write these arguments in the opposite order.
1772
1773As indicated, it is possible to specify different naming schemes for
1774bodies, specs, and subunits. Quite often the rule for subunits is the
1775same as the rule for bodies, in which case, there is no need to give
1776a separate @code{Subunit_File_Name} rule, and in this case the
1777@code{Body_File_name} rule is used for subunits as well.
1778
1779The separate rule for subunits can also be used to implement the rather
1780unusual case of a compilation environment (e.g.@: a single directory) which
1781contains a subunit and a child unit with the same unit name. Although
1782both units cannot appear in the same partition, the Ada Reference Manual
1783allows (but does not require) the possibility of the two units coexisting
1784in the same environment.
1785
1786The file name translation works in the following steps:
1787
1788@itemize @bullet
1789
1790@item
1791If there is a specific @code{Source_File_Name} pragma for the given unit,
1792then this is always used, and any general pattern rules are ignored.
1793
1794@item
1795If there is a pattern type @code{Source_File_Name} pragma that applies to
1796the unit, then the resulting file name will be used if the file exists. If
1797more than one pattern matches, the latest one will be tried first, and the
1798first attempt resulting in a reference to a file that exists will be used.
1799
1800@item
1801If no pattern type @code{Source_File_Name} pragma that applies to the unit
1802for which the corresponding file exists, then the standard GNAT default
1803naming rules are used.
1804
1805@end itemize
1806
1807@noindent
1808As an example of the use of this mechanism, consider a commonly used scheme
1809in which file names are all lower case, with separating periods copied
1810unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1811bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1812two pragmas appear:
1813
1814@smallexample @c ada
1815pragma Source_File_Name
1816  (Spec_File_Name => "*.1.ada");
1817pragma Source_File_Name
1818  (Body_File_Name => "*.2.ada");
1819@end smallexample
1820
1821@noindent
1822The default GNAT scheme is actually implemented by providing the following
1823default pragmas internally:
1824
1825@smallexample @c ada
1826pragma Source_File_Name
1827  (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1828pragma Source_File_Name
1829  (Body_File_Name => "*.adb", Dot_Replacement => "-");
1830@end smallexample
1831
1832@noindent
1833Our final example implements a scheme typically used with one of the
1834Ada 83 compilers, where the separator character for subunits was ``__''
1835(two underscores), specs were identified by adding @file{_.ADA}, bodies
1836by adding @file{.ADA}, and subunits by
1837adding @file{.SEP}. All file names were
1838upper case. Child units were not present of course since this was an
1839Ada 83 compiler, but it seems reasonable to extend this scheme to use
1840the same double underscore separator for child units.
1841
1842@smallexample @c ada
1843pragma Source_File_Name
1844  (Spec_File_Name => "*_.ADA",
1845   Dot_Replacement => "__",
1846   Casing = Uppercase);
1847pragma Source_File_Name
1848  (Body_File_Name => "*.ADA",
1849   Dot_Replacement => "__",
1850   Casing = Uppercase);
1851pragma 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
1861An Ada program consists of a set of source files, and the first step in
1862compiling the program is to generate the corresponding object files.
1863These are generated by compiling a subset of these source files.
1864The files you need to compile are the following:
1865
1866@itemize @bullet
1867@item
1868If a package spec has no body, compile the package spec to produce the
1869object file for the package.
1870
1871@item
1872If a package has both a spec and a body, compile the body to produce the
1873object file for the package. The source file for the package spec need
1874not be compiled in this case because there is only one object file, which
1875contains the code for both the spec and body of the package.
1876
1877@item
1878For a subprogram, compile the subprogram body to produce the object file
1879for the subprogram. The spec, if one is present, is as usual in a
1880separate file, and need not be compiled.
1881
1882@item
1883@cindex Subunits
1884In the case of subunits, only compile the parent unit. A single object
1885file is generated for the entire subunit tree, which includes all the
1886subunits.
1887
1888@item
1889Compile child units independently of their parent units
1890(though, of course, the spec of all the ancestor unit must be present in order
1891to compile a child unit).
1892
1893@item
1894@cindex Generics
1895Compile generic units in the same manner as any other units. The object
1896files in this case are small dummy files that contain at most the
1897flag used for elaboration checking. This is because GNAT always handles generic
1898instantiation by means of macro expansion. However, it is still necessary to
1899compile generic units, for dependency checking and elaboration purposes.
1900@end itemize
1901
1902@noindent
1903The preceding rules describe the set of files that must be compiled to
1904generate the object files for a program. Each object file has the same
1905name as the corresponding source file, except that the extension is
1906@file{.o} as usual.
1907
1908You may wish to compile other files for the purpose of checking their
1909syntactic and semantic correctness. For example, in the case where a
1910package has a separate spec and body, you would not normally compile the
1911spec. However, it is convenient in practice to compile the spec to make
1912sure it is error-free before compiling clients of this spec, because such
1913compilations will fail if there is an error in the spec.
1914
1915GNAT provides an option for compiling such files purely for the
1916purposes of checking correctness; such compilations are not required as
1917part of the process of building a program. To compile a file in this
1918checking mode, use the @option{-gnatc} switch.
1919
1920@node Source Dependencies
1921@section Source Dependencies
1922
1923@noindent
1924A given object file clearly depends on the source file which is compiled
1925to 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
1927file if changes to the source file require the object file to be
1928recompiled.
1929In addition to this basic dependency, a given object may depend on
1930additional source files as follows:
1931
1932@itemize @bullet
1933@item
1934If a file being compiled @code{with}'s a unit @var{X}, the object file
1935depends on the file containing the spec of unit @var{X}. This includes
1936files that are @code{with}'ed implicitly either because they are parents
1937of @code{with}'ed child units or they are run-time units required by the
1938language constructs used in a particular unit.
1939
1940@item
1941If a file being compiled instantiates a library level generic unit, the
1942object file depends on both the spec and body files for this generic
1943unit.
1944
1945@item
1946If a file being compiled instantiates a generic unit defined within a
1947package, the object file depends on the body file for the package as
1948well as the spec file.
1949
1950@item
1951@findex Inline
1952@cindex @option{-gnatn} switch
1953If a file being compiled contains a call to a subprogram for which
1954pragma @code{Inline} applies and inlining is activated with the
1955@option{-gnatn} switch, the object file depends on the file containing the
1956body of this subprogram as well as on the file containing the spec. Note
1957that for inlining to actually occur as a result of the use of this switch,
1958it is necessary to compile in optimizing mode.
1959
1960@cindex @option{-gnatN} switch
1961The use of @option{-gnatN} activates  inlining optimization
1962that is performed by the front end of the compiler. This inlining does
1963not require that the code generation be optimized. Like @option{-gnatn},
1964the use of this switch generates additional dependencies.
1965
1966When using a gcc-based back end (in practice this means using any version
1967of 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.
1969Historically front end inlining was more extensive than the gcc back end
1970inlining, but that is no longer the case.
1971
1972@item
1973If an object file @file{O} depends on the proper body of a subunit through
1974inlining or instantiation, it depends on the parent unit of the subunit.
1975This means that any modification of the parent unit or one of its subunits
1976affects the compilation of @file{O}.
1977
1978@item
1979The object file for a parent unit depends on all its subunit body files.
1980
1981@item
1982The previous two rules meant that for purposes of computing dependencies and
1983recompilation, a body and all its subunits are treated as an indivisible whole.
1984
1985@noindent
1986These rules are applied transitively: if unit @code{A} @code{with}'s
1987unit @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
1991The set of dependent files described by these rules includes all the
1992files on which the unit is semantically dependent, as dictated by the
1993Ada language standard. However, it is a superset of what the
1994standard describes, because it includes generic, inline, and subunit
1995dependencies.
1996
1997An object file must be recreated by recompiling the corresponding source
1998file if any of the source files on which it depends are modified. For
1999example, if the @code{make} utility is used to control compilation,
2000the rule for an Ada object file must mention all the source files on
2001which the object file depends, according to the above definition.
2002The determination of the necessary
2003recompilations 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
2012Each compilation actually generates two output files. The first of these
2013is the normal object file that has a @file{.o} extension. The second is a
2014text file containing full dependency information. It has the same
2015name as the source file, but an @file{.ali} extension.
2016This file is known as the Ada Library Information (@file{ALI}) file.
2017The following information is contained in the @file{ALI} file.
2018
2019@itemize @bullet
2020@item
2021Version information (indicates which version of GNAT was used to compile
2022the unit(s) in question)
2023
2024@item
2025Main program information (including priority and time slice settings,
2026as well as the wide character encoding used during compilation).
2027
2028@item
2029List of arguments used in the @command{gcc} command for the compilation
2030
2031@item
2032Attributes of the unit, including configuration pragmas used, an indication
2033of whether the compilation was successful, exception model used etc.
2034
2035@item
2036A list of relevant restrictions applying to the unit (used for consistency)
2037checking.
2038
2039@item
2040Categorization information (e.g.@: use of pragma @code{Pure}).
2041
2042@item
2043Information on all @code{with}'ed units, including presence of
2044@code{Elaborate} or @code{Elaborate_All} pragmas.
2045
2046@item
2047Information from any @code{Linker_Options} pragmas used in the unit
2048
2049@item
2050Information on the use of @code{Body_Version} or @code{Version}
2051attributes in the unit.
2052
2053@item
2054Dependency information. This is a list of files, together with
2055time stamp and checksum information. These are files on which
2056the unit depends in the sense that recompilation is required
2057if any of these units are modified.
2058
2059@item
2060Cross-reference data. Contains information on all entities referenced
2061in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2062provide cross-reference information.
2063
2064@end itemize
2065
2066@noindent
2067For a full detailed description of the format of the @file{ALI} file,
2068see 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
2075When using languages such as C and C++, once the source files have been
2076compiled the only remaining step in building an executable program
2077is linking the object modules together. This means that it is possible to
2078link an inconsistent version of a program, in which two units have
2079included different versions of the same header.
2080
2081The rules of Ada do not permit such an inconsistent program to be built.
2082For example, if two clients have different versions of the same package,
2083it is illegal to build a program containing these two clients.
2084These rules are enforced by the GNAT binder, which also determines an
2085elaboration order consistent with the Ada rules.
2086
2087The GNAT binder is run after all the object files for a program have
2088been created. It is given the name of the main program unit, and from
2089this it determines the set of units required by the program, by reading the
2090corresponding ALI files. It generates error messages if the program is
2091inconsistent or if no valid order of elaboration exists.
2092
2093If no errors are detected, the binder produces a main program, in Ada by
2094default, that contains calls to the elaboration procedures of those
2095compilation unit that require them, followed by
2096a call to the main program. This Ada program is compiled to generate the
2097object file for the main program. The name of
2098the 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
2100main program unit.
2101
2102Finally, the linker is used to build the resulting executable program,
2103using the object from the main program from the bind step as well as the
2104object 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
2111This section describes how to develop a mixed-language program,
2112specifically 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
2122Interfacing Ada with a foreign language such as C involves using
2123compiler directives to import and/or export entity definitions in each
2124language---using @code{extern} statements in C, for instance, and the
2125@code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2126A full treatment of these topics is provided in Appendix B, section 1
2127of the Ada Reference Manual.
2128
2129There are two ways to build a program using GNAT that contains some Ada
2130sources and some foreign language sources, depending on whether or not
2131the main subprogram is written in Ada.  Here is a source example with
2132the main subprogram in Ada:
2133
2134@smallexample
2135/* file1.c */
2136#include <stdio.h>
2137
2138void 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 */
2147extern int num_from_Ada;
2148
2149int get_num (void)
2150@{
2151  return num_from_Ada;
2152@}
2153@end smallexample
2154
2155@smallexample @c ada
2156--  my_main.adb
2157procedure 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
2173begin
2174   Print_Num (Get_Num);
2175end My_Main;
2176@end smallexample
2177
2178@enumerate
2179@item
2180To build this example, first compile the foreign language files to
2181generate 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
2188Then, compile the Ada units to produce a set of object files and ALI
2189files:
2190@smallexample
2191gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2192@end smallexample
2193
2194@item
2195Run the Ada binder on the Ada main program:
2196@smallexample
2197gnatbind my_main.ali
2198@end smallexample
2199
2200@item
2201Link the Ada main program, the Ada objects and the other language
2202objects:
2203@smallexample
2204gnatlink my_main.ali file1.o file2.o
2205@end smallexample
2206@end enumerate
2207
2208The last three steps can be grouped in a single command:
2209@smallexample
2210gnatmake my_main.adb -largs file1.o file2.o
2211@end smallexample
2212
2213@cindex Binder output file
2214@noindent
2215If the main program is in a language other than Ada, then you may have
2216more than one entry point into the Ada subsystem. You must use a special
2217binder option to generate callable routines that initialize and
2218finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2219Calls to the initialization and finalization routines must be inserted
2220in the main program, or some other appropriate point in the code. The
2221call to initialize the Ada units must occur before the first Ada
2222subprogram is called, and the call to finalize the Ada units must occur
2223after the last Ada subprogram returns. The binder will place the
2224initialization and finalization subprograms into the
2225@file{b~@var{xxx}.adb} file where they can be accessed by your C
2226sources.  To illustrate, we have the following example:
2227
2228@smallexample
2229/* main.c */
2230extern void adainit (void);
2231extern void adafinal (void);
2232extern int add (int, int);
2233extern int sub (int, int);
2234
2235int 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
2252package Unit1 is
2253   function Add (A, B : Integer) return Integer;
2254   pragma Export (C, Add, "add");
2255end Unit1;
2256
2257--  unit1.adb
2258package body Unit1 is
2259   function Add (A, B : Integer) return Integer is
2260   begin
2261      return A + B;
2262   end Add;
2263end Unit1;
2264
2265--  unit2.ads
2266package Unit2 is
2267   function Sub (A, B : Integer) return Integer;
2268   pragma Export (C, Sub, "sub");
2269end Unit2;
2270
2271--  unit2.adb
2272package body Unit2 is
2273   function Sub (A, B : Integer) return Integer is
2274   begin
2275      return A - B;
2276   end Sub;
2277end Unit2;
2278@end smallexample
2279
2280@enumerate
2281@item
2282The build procedure for this application is similar to the last
2283example's.  First, compile the foreign language files to generate object
2284files:
2285@smallexample
2286^gcc -c main.c^gcc -c main.c^
2287@end smallexample
2288
2289@item
2290Next, compile the Ada units to produce a set of object files and ALI
2291files:
2292@smallexample
2293gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2294gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2295@end smallexample
2296
2297@item
2298Run 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
2301gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2302@end smallexample
2303
2304@item
2305Link the Ada main program, the Ada objects and the foreign language
2306objects. You need only list the last ALI file here:
2307@smallexample
2308gnatlink unit2.ali main.o -o exec_file
2309@end smallexample
2310
2311This procedure yields a binary executable called @file{exec_file}.
2312@end enumerate
2313
2314@noindent
2315Depending on the circumstances (for example when your non-Ada main object
2316does not provide symbol @code{main}), you may also need to instruct the
2317GNAT 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
2324GNAT follows standard calling sequence conventions and will thus interface
2325to any other language that also follows these conventions. The following
2326Convention 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
2333This indicates that the standard Ada calling sequence will be
2334used and all Ada data items may be passed without any limitations in the
2335case where GNAT is used to generate both the caller and callee. It is also
2336possible to mix GNAT generated code and code generated by another Ada
2337compiler. In this case, the data types should be restricted to simple
2338cases, including primitive types. Whether complex data types can be passed
2339depends on the situation. Probably it is safe to pass simple arrays, such
2340as arrays of integers or floats. Records may or may not work, depending
2341on whether both compilers lay them out identically. Complex structures
2342involving variant records, access parameters, tasks, or protected types,
2343are unlikely to be able to be passed.
2344
2345Note that in the case of GNAT running
2346on a platform that supports HP Ada 83, a higher degree of compatibility
2347can be guaranteed, and in particular records are laid out in an identical
2348manner in the two compilers. Note also that if output from two different
2349compilers is mixed, the program is responsible for dealing with elaboration
2350issues. Probably the safest approach is to write the main program in the
2351version of Ada other than GNAT, so that it takes care of its own elaboration
2352requirements, and then call the GNAT-generated adainit procedure to ensure
2353elaboration of the GNAT components. Consult the documentation of the other
2354Ada compiler for further details on elaboration.
2355
2356However, it is not possible to mix the tasking run time of GNAT and
2357HP Ada 83, All the tasking operations must either be entirely within
2358GNAT compiled sections of the program, or entirely within HP Ada 83
2359compiled sections of the program.
2360
2361@cindex Interfacing to Assembly
2362@cindex Convention Assembler
2363@item Assembler
2364Specifies assembler as the convention. In practice this has the
2365same effect as convention Ada (but is not equivalent in the sense of being
2366considered the same convention).
2367
2368@cindex Convention Asm
2369@findex Asm
2370@item Asm
2371Equivalent to Assembler.
2372
2373@cindex Interfacing to COBOL
2374@cindex Convention COBOL
2375@findex COBOL
2376@item COBOL
2377Data will be passed according to the conventions described
2378in section B.4 of the Ada Reference Manual.
2379
2380@findex C
2381@cindex Interfacing to C
2382@cindex Convention C
2383@item C
2384Data will be passed according to the conventions described
2385in section B.3 of the Ada Reference Manual.
2386
2387A 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
2394In C, @code{varargs} allows a function to take a variable number of
2395arguments. There is no direct equivalent in this to Ada. One
2396approach that can be used is to create a C wrapper for each
2397different profile and then interface to this C wrapper. For
2398example, to print an @code{int} value using @code{printf},
2399create a C function @code{printfi} that takes two arguments, a
2400pointer to a string and an int, and calls @code{printf}.
2401Then in the Ada program, use pragma @code{Import} to
2402interface to @code{printfi}.
2403
2404@item
2405It may work on some platforms to directly interface to
2406a @code{varargs} function by providing a specific Ada profile
2407for a particular call. However, this does not work on
2408all platforms, since there is no guarantee that the
2409calling sequence for a two argument normal C function
2410is the same as for calling a @code{varargs} C function with
2411the same two arguments.
2412@end itemize
2413
2414@cindex Convention Default
2415@findex Default
2416@item Default
2417Equivalent to C.
2418
2419@cindex Convention External
2420@findex External
2421@item External
2422Equivalent 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)
2429This stands for C++. For most purposes this is identical to C.
2430See the separate description of the specialized GNAT pragmas relating to
2431C++ interfacing for further details.
2432@end ifclear
2433
2434@findex Fortran
2435@cindex Interfacing to Fortran
2436@cindex Convention Fortran
2437@item Fortran
2438Data will be passed according to the conventions described
2439in section B.5 of the Ada Reference Manual.
2440
2441@item Intrinsic
2442This applies to an intrinsic operation, as defined in the Ada
2443Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2444this means that the body of the subprogram is provided by the compiler itself,
2445usually by means of an efficient code sequence, and that the user does not
2446supply an explicit body for it. In an application program, the pragma may
2447be applied to the following sets of names:
2448
2449@itemize @bullet
2450@item
2451Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2452Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2453two formal parameters. The
2454first one must be a signed integer type or a modular type with a binary
2455modulus, and the second parameter must be of type Natural.
2456The return type must be the same as the type of the first argument. The size
2457of this type can only be 8, 16, 32, or 64.
2458
2459@item
2460Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2461The corresponding operator declaration must have parameters and result type
2462that have the same root numeric type (for example, all three are long_float
2463types). This simplifies the definition of operations that use type checking
2464to perform dimensional checks:
2465
2466@smallexample @c ada
2467type Distance is new Long_Float;
2468type Time     is new Long_Float;
2469type Velocity is new Long_Float;
2470function "/" (D : Distance; T : Time)
2471  return Velocity;
2472pragma Import (Intrinsic, "/");
2473@end smallexample
2474
2475@noindent
2476This common idiom is often programmed with a generic definition and an
2477explicit body. The pragma makes it simpler to introduce such declarations.
2478It incurs no overhead in compilation time or code size, because it is
2479implemented as a single machine instruction.
2480
2481@item
2482General subprogram entities, to bind an Ada subprogram declaration to
2483a compiler builtin by name with back-ends where such interfaces are
2484available. A typical example is the set of ``__builtin'' functions
2485exposed 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
2492Most of the GCC builtins are accessible this way, and as for other
2493import conventions (e.g. C), it is the user's responsibility to ensure
2494that the Ada subprogram profile matches the underlying builtin
2495expectations.
2496@end itemize
2497
2498@noindent
2499
2500@ifset unw
2501@findex Stdcall
2502@cindex Convention Stdcall
2503@item Stdcall
2504This is relevant only to Windows XP/2000/NT implementations of GNAT,
2505and specifies that the @code{Stdcall} calling sequence will be used,
2506as defined by the NT API. Nevertheless, to ease building
2507cross-platform bindings this convention will be handled as a @code{C} calling
2508convention on non-Windows platforms.
2509
2510@findex DLL
2511@cindex Convention DLL
2512@item DLL
2513This is equivalent to @code{Stdcall}.
2514
2515@findex Win32
2516@cindex Convention Win32
2517@item Win32
2518This is equivalent to @code{Stdcall}.
2519@end ifset
2520
2521@findex Stubbed
2522@cindex Convention Stubbed
2523@item Stubbed
2524This is a special convention that indicates that the compiler
2525should provide a stub body that raises @code{Program_Error}.
2526@end table
2527
2528@noindent
2529GNAT additionally provides a useful pragma @code{Convention_Identifier}
2530that can be used to parameterize conventions and allow additional synonyms
2531to be specified. For example if you have legacy code in which the convention
2532identifier Fortran77 was used for Fortran, you can use the configuration
2533pragma:
2534
2535@smallexample @c ada
2536pragma Convention_Identifier (Fortran77, Fortran);
2537@end smallexample
2538
2539@noindent
2540And from now on the identifier Fortran77 may be used as a convention
2541identifier (for example in an @code{Import} pragma) with the same
2542meaning as Fortran.
2543
2544@ifclear vms
2545@node Building Mixed Ada & C++ Programs
2546@section Building Mixed Ada and C++ Programs
2547
2548@noindent
2549A programmer inexperienced with mixed-language development may find that
2550building an application containing both Ada and C++ code can be a
2551challenge.  This section gives a few
2552hints that should make this task easier. The first section addresses
2553the differences between interfacing with C and interfacing with C++.
2554The second section
2555looks into the delicate problem of linking the complete application from
2556its Ada and C++ parts. The last section gives some hints on how the GNAT
2557run-time library can be adapted in order to allow inter-language dispatching
2558with 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
2572GNAT supports interfacing with the G++ compiler (or any C++ compiler
2573generating code that is compatible with the G++ Application Binary
2574Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2575
2576@noindent
2577Interfacing can be done at 3 levels: simple data, subprograms, and
2578classes. In the first two cases, GNAT offers a specific @code{Convention
2579C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2580Usually, C++ mangles the names of subprograms. To generate proper mangled
2581names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2582This problem can also be addressed manually in two ways:
2583
2584@itemize @bullet
2585@item
2586by modifying the C++ code in order to force a C convention using
2587the @code{extern "C"} syntax.
2588
2589@item
2590by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2591Link_Name argument of the pragma import.
2592@end itemize
2593
2594@noindent
2595Interfacing at the class level can be achieved by using the GNAT specific
2596pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2597gnat_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
2603Usually the linker of the C++ development system must be used to link
2604mixed applications because most C++ systems will resolve elaboration
2605issues (such as calling constructors on global class instances)
2606transparently during the link phase. GNAT has been adapted to ease the
2607use of a foreign linker for the last phase. Three cases can be
2608considered:
2609@enumerate
2610
2611@item
2612Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2613The C++ linker can simply be called by using the C++ specific driver
2614called @code{g++}.
2615
2616Note that if the C++ code uses inline functions, you will need to
2617compile your C++ code with the @code{-fkeep-inline-functions} switch in
2618order to provide an existing function implementation that the Ada code can
2619link 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
2628Using GNAT and G++ from two different GCC installations: If both
2629compilers are on the @env{PATH}, the previous method may be used. It is
2630important 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
2633at the same time and may make one of the two compilers operate
2634improperly if set during invocation of the wrong compiler.  It is also
2635very important that the linker uses the proper @file{libgcc.a} GCC
2636library -- that is, the one from the C++ compiler installation. The
2637implicit link command as suggested in the @command{gnatmake} command
2638from the former example can be replaced by an explicit link command with
2639the 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
2644If there is a problem due to interfering environment variables, it can
2645be worked around by using an intermediate script. The following example
2646shows the proper script to use when GNAT has not been installed at its
2647default location and g++ has been installed at its default location:
2648
2649@smallexample
2650$ cat ./my_script
2651#!/bin/sh
2652unset BINUTILS_ROOT
2653unset GCC_ROOT
2654c++ $*
2655$ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2656@end smallexample
2657
2658@item
2659Using a non-GNU C++ compiler: The commands previously described can be
2660used to insure that the C++ linker is used. Nonetheless, you need to add
2661a few more parameters to the link command line, depending on the exception
2662mechanism used.
2663
2664If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2665to the libgcc libraries are required:
2666
2667@smallexample
2668$ cat ./my_script
2669#!/bin/sh
2670CC $* `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
2674Where CC is the name of the non-GNU C++ compiler.
2675
2676If the @code{zero cost} exception mechanism is used, and the platform
2677supports automatic registration of exception tables (e.g.@: Solaris),
2678paths to more objects are required:
2679
2680@smallexample
2681$ cat ./my_script
2682#!/bin/sh
2683CC `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
2689If the @code{zero cost} exception mechanism is used, and the platform
2690doesn't support automatic registration of exception tables (e.g.@: HP-UX
2691or AIX), the simple approach described above will not work and
2692a pre-linking phase using GNAT will be necessary.
2693
2694@end enumerate
2695
2696Another alternative is to use the @command{gprbuild} multi-language builder
2697which has a large knowledge base and knows how to link Ada and C++ code
2698together automatically in most cases.
2699
2700@node A Simple Example
2701@subsection  A Simple Example
2702@noindent
2703The following example, provided as part of the GNAT examples, shows how
2704to achieve procedural interfacing between Ada and C++ in both
2705directions. The C++ class A has two methods. The first method is exported
2706to Ada by the means of an extern C wrapper function. The second method
2707calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2708a limited record with a layout comparable to the C++ class. The Ada
2709subprogram, in turn, calls the C++ method. So, starting from the C++
2710main program, the process passes back and forth between the two
2711languages.
2712
2713@noindent
2714Here 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
2725Here are the corresponding sources:
2726@smallexample
2727
2728//cpp_main.C
2729
2730#include "ex7.h"
2731
2732extern "C" @{
2733  void adainit (void);
2734  void adafinal (void);
2735  void method1 (A *t);
2736@}
2737
2738void method1 (A *t)
2739@{
2740  t->method1 ();
2741@}
2742
2743int main ()
2744@{
2745  A obj;
2746  adainit ();
2747  obj.method2 (3030);
2748  adafinal ();
2749@}
2750
2751//ex7.h
2752
2753class Origin @{
2754 public:
2755  int o_value;
2756@};
2757class 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
2770extern "C" @{ void ada_method2 (A *t, int v);@}
2771
2772void A::method1 (void)
2773@{
2774  a_value = 2020;
2775  printf ("in A::method1, a_value = %d \n",a_value);
2776
2777@}
2778
2779void A::method2 (int v)
2780@{
2781   ada_method2 (this, v);
2782   printf ("in A::method2, a_value = %d \n",a_value);
2783
2784@}
2785
2786A::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
2795package 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
2803end Simple_Cpp_Interface;
2804
2805with System;
2806package 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
2821end Simple_Cpp_Interface;
2822@end smallexample
2823
2824@node Interfacing with C++ constructors
2825@subsection Interfacing with C++ constructors
2826@noindent
2827
2828In order to interface with C++ constructors GNAT provides the
2829@code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2830gnat_rm, GNAT Reference Manual}, for additional information).
2831In this section we present some common uses of C++ constructors
2832in mixed-languages programs in GNAT.
2833
2834Let us assume that we need to interface with the following
2835C++ 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
2849For this purpose we can write the following package spec (further
2850information 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
2855with Interfaces.C; use Interfaces.C;
2856package 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");
2874end Pkg_Root;
2875@end smallexample
2876
2877On the Ada side the constructor is represented by a function (whose
2878name is arbitrary) that returns the classwide type corresponding to
2879the imported C++ class. Although the constructor is described as a
2880function, it is typically a procedure with an extra implicit argument
2881(the object being initialized) at the implementation level. GNAT
2882issues the appropriate call, whatever it is, to get the object
2883properly initialized.
2884
2885Constructors can only appear in the following contexts:
2886
2887@itemize @bullet
2888@item
2889On the right side of an initialization of an object of type @var{T}.
2890@item
2891On the right side of an initialization of a record component of type @var{T}.
2892@item
2893In an Ada 2005 limited aggregate.
2894@item
2895In an Ada 2005 nested limited aggregate.
2896@item
2897In an Ada 2005 limited aggregate that initializes an object built in
2898place by an extended return statement.
2899@end itemize
2900
2901@noindent
2902In a declaration of an object whose type is a class imported from C++,
2903either the default C++ constructor is implicitly called by GNAT, or
2904else the required C++ constructor must be explicitly called in the
2905expression 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
2914The first two declarations are equivalent: in both cases the default C++
2915constructor is invoked (in the former case the call to the constructor is
2916implicit, and in the latter case the call is explicit in the object
2917declaration). @code{Obj3} is initialized by the C++ non-default constructor
2918that takes an integer argument, and @code{Obj4} is initialized by the
2919non-default C++ constructor that takes two integers.
2920
2921Let 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
2929In this case the components DT inherited from the C++ side must be
2930initialized by a C++ constructor, and the additional Ada components
2931of type DT are initialized by GNAT. The initialization of such an
2932object is done either by default, or by means of a function returning
2933an 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
2941The declaration of @code{Obj5} invokes the default constructors: the
2942C++ default constructor of the parent type takes care of the initialization
2943of the components inherited from Root, and GNAT takes care of the default
2944initialization of the additional Ada components of type DT (that is,
2945@code{C_Value} is initialized to value 2009). The order of invocation of
2946the constructors is consistent with the order of elaboration required by
2947Ada and C++. That is, the constructor of the parent type is always called
2948before the constructor of the derived type.
2949
2950Let us now consider a record that has components whose type is imported
2951from 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
2965The initialization of an object of type @code{Rec2} will call the
2966non-default C++ constructors specified for the imported components.
2967For example:
2968
2969@smallexample @c ada
2970  Obj8 : Rec2 (40);
2971@end smallexample
2972
2973Using Ada 2005 we can use limited aggregates to initialize an object
2974invoking C++ constructors that differ from those specified in the type
2975declarations. For example:
2976
2977@smallexample @c ada
2978  Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2979                          others => <>),
2980                  others => <>);
2981@end smallexample
2982
2983The above declaration uses an Ada 2005 limited aggregate to
2984initialize @code{Obj9}, and the C++ constructor that has two integer
2985arguments is invoked to initialize the @code{Data1} component instead
2986of the constructor specified in the declaration of type @code{Rec1}. In
2987Ada 2005 the box in the aggregate indicates that unspecified components
2988are initialized using the expression (if any) available in the component
2989declaration. That is, in this case discriminant @code{D} is initialized
2990to value @code{20}, @code{Value} is initialized to value 1000, and the
2991non-default C++ constructor that handles two integers takes care of
2992initializing component @code{Data2} with values @code{20,30}.
2993
2994In Ada 2005 we can use the extended return statement to build the Ada
2995equivalent 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
3010In this example the extended return statement construct is used to
3011build in place the returned object whose components are initialized
3012by means of a limited aggregate. Any further action associated with
3013the 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
3018In this section we demonstrate the GNAT features for interfacing with
3019C++ by means of an example making use of Ada 2005 abstract interface
3020types. This example consists of a classification of animals; classes
3021have been used to model our main classification of animals, and
3022interfaces provide support for the management of secondary
3023classifications. We first demonstrate a case in which the types and
3024constructors are defined on the C++ side and imported from the Ada
3025side, and latter the reverse case.
3026
3027The root of our derivation will be the @code{Animal} class, with a
3028single private attribute (the @code{Age} of the animal) and two public
3029primitives 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
3041Abstract interface types are defined in C++ by means of classes with pure
3042virtual functions and no data members. In our example we will use two
3043interfaces that provide support for the common management of @code{Carnivore}
3044and @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
3058Using these declarations, we can now say that a @code{Dog} is an animal that is
3059both 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
3074In the following examples we will assume that the previous declarations are
3075located in a file named @code{animals.h}. The following package demonstrates
3076how to import these C++ declarations from the Ada side:
3077
3078@smallexample @c ada
3079with Interfaces.C.Strings; use Interfaces.C.Strings;
3080package 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");
3118end Animals;
3119@end smallexample
3120
3121Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3122interfacing with these C++ classes is easy. The only requirement is that all
3123the primitives and components must be declared exactly in the same order in
3124the two languages.
3125
3126Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3127means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3128the arguments to the called primitives will be the same as for C++. For the
3129imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3130to indicate that they have been defined on the C++ side; this is required
3131because the dispatch table associated with these tagged types will be built
3132in the C++ side and therefore will not contain the predefined Ada primitives
3133which Ada would otherwise expect.
3134
3135As the reader can see there is no need to indicate the C++ mangled names
3136associated with each subprogram because it is assumed that all the calls to
3137these primitives will be dispatching calls. The only exception is the
3138constructor, which must be registered with the compiler by means of
3139@code{pragma CPP_Constructor} and needs to provide its associated C++
3140mangled name because the Ada compiler generates direct calls to it.
3141
3142With the above packages we can now declare objects of type Dog on the Ada side
3143and dispatch calls to the corresponding subprograms on the C++ side. We can
3144also extend the tagged type Dog with further fields and primitives, and
3145override some of its C++ primitives on the Ada side. For example, here we have
3146a type derivation defined on the Ada side that inherits all the dispatching
3147primitives 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
3157It is important to note that, because of the ABI compatibility, the programmer
3158does not need to add any further information to indicate either the object
3159layout or the dispatch table entry associated with each dispatching operation.
3160
3161Now let us define all the types and constructors on the Ada side and export
3162them to C++, using the same hierarchy of our previous example:
3163
3164@smallexample @c ada
3165with Interfaces.C.Strings;
3166use Interfaces.C.Strings;
3167package 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);
3204end Animals;
3205@end smallexample
3206
3207Compared 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
3209be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3210nothing else to be done; as explained above, the only requirement is that all
3211the primitives and components are declared in exactly the same order.
3212
3213For completeness, let us see a brief C++ main program that uses the
3214declarations available in @code{animals.h} (presented in our first example) to
3215import and use the declarations from the Ada side, properly initializing and
3216finalizing 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
3223void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3224void Check_Domestic (Domestic *obj)   @{@dots{}@}
3225void Check_Animal (Animal *obj)       @{@dots{}@}
3226void Check_Dog (Dog *obj)             @{@dots{}@}
3227
3228@b{extern} "C" @{
3229  void adainit (void);
3230  void adafinal (void);
3231  Dog* new_dog ();
3232@}
3233
3234void 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
3243int 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
3254The GNAT model of compilation is close to the C and C++ models. You can
3255think of Ada specs as corresponding to header files in C. As in C, you
3256don't need to compile specs; they are compiled when they are used. The
3257Ada @code{with} is similar in effect to the @code{#include} of a C
3258header.
3259
3260One notable difference is that, in Ada, you may compile specs separately
3261to check them for semantic and syntactic accuracy. This is not always
3262possible with C headers because they are fragments of programs that have
3263less specific syntactic or semantic rules.
3264
3265The other major difference is the requirement for running the binder,
3266which performs two important functions. First, it checks for
3267consistency. In C or C++, the only defense against assembling
3268inconsistent programs lies outside the compiler, in a makefile, for
3269example. The binder satisfies the Ada requirement that it be impossible
3270to construct an inconsistent program when the compiler is used in normal
3271mode.
3272
3273@cindex Elaboration order control
3274The other important function of the binder is to deal with elaboration
3275issues. There are also elaboration issues in C++ that are handled
3276automatically. This automatic handling has the advantage of being
3277simpler to use, but the C++ programmer has no control over elaboration.
3278Where @code{gnatbind} might complain there was no valid order of
3279elaboration, a C++ compiler would simply construct a program that
3280malfunctioned 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
3287This section is intended for Ada programmers who have
3288used an Ada compiler implementing the traditional Ada library
3289model, as described in the Ada Reference Manual.
3290
3291@cindex GNAT library
3292In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3293source files themselves acts as the library. Compiling Ada programs does
3294not generate any centralized information, but rather an object file and
3295a ALI file, which are of interest only to the binder and linker.
3296In a traditional system, the compiler reads information not only from
3297the source file being compiled, but also from the centralized library.
3298This means that the effect of a compilation depends on what has been
3299previously compiled. In particular:
3300
3301@itemize @bullet
3302@item
3303When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3304to the version of the unit most recently compiled into the library.
3305
3306@item
3307Inlining is effective only if the necessary body has already been
3308compiled into the library.
3309
3310@item
3311Compiling a unit may obsolete other units in the library.
3312@end itemize
3313
3314@noindent
3315In GNAT, compiling one unit never affects the compilation of any other
3316units because the compiler reads only source files. Only changes to source
3317files can affect the results of a compilation. In particular:
3318
3319@itemize @bullet
3320@item
3321When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3322to the source version of the unit that is currently accessible to the
3323compiler.
3324
3325@item
3326@cindex Inlining
3327Inlining requires the appropriate source files for the package or
3328subprogram bodies to be available to the compiler. Inlining is always
3329effective, independent of the order in which units are complied.
3330
3331@item
3332Compiling a unit never affects any other compilations. The editing of
3333sources may cause previous compilations to be out of date if they
3334depended on the source file being modified.
3335@end itemize
3336
3337@noindent
3338The most important result of these differences is that order of compilation
3339is never significant in GNAT. There is no situation in which one is
3340required to do one compilation before another. What shows up as order of
3341compilation requirements in the traditional Ada library becomes, in
3342GNAT, simple source dependencies; in other words, there is only a set
3343of rules saying what source files must be present when a file is
3344compiled.
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
3352GNAT creates temporary files in the directory designated by the environment
3353variable @env{TMPDIR}.
3354(See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3355for detailed information on how environment variables are resolved.
3356For most users the easiest way to make use of this feature is to simply
3357define @env{TMPDIR} as a job level logical name).
3358For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3359for compiler temporary files, then you can include something like the
3360following command in your @file{LOGIN.COM} file:
3361
3362@smallexample
3363$ define/job TMPDIR "/disk$scratchram/000000/temp/"
3364@end smallexample
3365
3366@noindent
3367If @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
3369designated by @env{TEMP}.
3370If none of these environment variables are defined then GNAT uses the
3371directory designated by the logical name @code{SYS$SCRATCH:}
3372(by default the user's home directory). If all else fails
3373GNAT 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
3381This chapter discusses how to compile Ada programs using the @command{gcc}
3382command. It also describes the set of switches
3383that 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
3396The first step in creating an executable program is to compile the units
3397of the program using the @command{gcc} command. You must compile the
3398following files:
3399
3400@itemize @bullet
3401@item
3402the body file (@file{.adb}) for a library level subprogram or generic
3403subprogram
3404
3405@item
3406the spec file (@file{.ads}) for a library level package or generic
3407package that has no body
3408
3409@item
3410the body file (@file{.adb}) for a library level package
3411or generic package that has a body
3412
3413@end itemize
3414
3415@noindent
3416You need @emph{not} compile the following files
3417
3418@itemize @bullet
3419
3420@item
3421the spec of a library unit which has a body
3422
3423@item
3424subunits
3425@end itemize
3426
3427@noindent
3428because they are compiled as part of compiling related units. GNAT
3429package specs
3430when the corresponding body is compiled, and subunits when the parent is
3431compiled.
3432
3433@cindex cannot generate code
3434If you attempt to compile any of these files, you will get one of the
3435following error messages (where @var{fff} is the name of the file you
3436compiled):
3437
3438@smallexample
3439cannot generate code for file @var{fff} (package spec)
3440to check package spec, use -gnatc
3441
3442cannot generate code for file @var{fff} (missing subunits)
3443to check parent unit, use -gnatc
3444
3445cannot generate code for file @var{fff} (subprogram spec)
3446to check subprogram spec, use -gnatc
3447
3448cannot generate code for file @var{fff} (subunit)
3449to check subunit, use -gnatc
3450@end smallexample
3451
3452@noindent
3453As indicated by the above error messages, if you want to submit
3454one of these files to the compiler to check for correct semantics
3455without generating code, then use the @option{-gnatc} switch.
3456
3457The 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
3466where @var{file name} is the name of the Ada file (usually
3467having an extension
3468@file{.ads} for a spec or @file{.adb} for a body).
3469@ifclear vms
3470You specify the
3471@option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3472@end ifclear
3473The result of a successful compilation is an object file, which has the
3474same name as the source file but an extension of @file{.o} and an Ada
3475Library Information (ALI) file, which also has the same name as the
3476source file, but with @file{.ali} as the extension. GNAT creates these
3477two output files in the current directory, but you may specify a source
3478file in any directory using an absolute or relative path specification
3479containing the directory information.
3480
3481@findex gnat1
3482@command{gcc} is actually a driver program that looks at the extensions of
3483the file arguments and loads the appropriate compiler. For example, the
3484GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3485These programs are in directories known to the driver program (in some
3486configurations via environment variables you set), but need not be in
3487your path. The @command{gcc} driver also calls the assembler and any other
3488utilities needed to complete the generation of the required object
3489files.
3490
3491It is possible to supply several file names on the same @command{gcc}
3492command. This causes @command{gcc} to call the appropriate compiler for
3493each file. For example, the following command lists two separate
3494files to be compiled:
3495
3496@smallexample
3497$ gcc -c x.adb y.adb
3498@end smallexample
3499
3500@noindent
3501calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3502@file{y.adb}.
3503The compiler generates two object files @file{x.o} and @file{y.o}
3504and the two ALI files @file{x.ali} and @file{y.ali}.
3505Any switches apply to all the files ^listed,^listed.^
3506
3507@node Switches for gcc
3508@section Switches for @command{gcc}
3509
3510@noindent
3511The @command{gcc} command accepts switches that control the
3512compilation process. These switches are fully described in this section.
3513First we briefly list all the switches, in alphabetical order, then we
3514describe the switches in more detail in functionally grouped sections.
3515
3516More switches exist for GCC than those documented here, especially
3517for specific targets. However, their use is not recommended as
3518they may change code generation in ways that are incompatible with
3519the Ada run-time library, or can cause inconsistencies between
3520compilation 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}
3551Compile your program to run on @var{target}, which is the name of a
3552system 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})
3557Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3558from @var{dir} instead of the default location. Only use this switch
3559when multiple versions of the GNAT compiler are available.
3560@xref{Directory Options,, Options for Directory Search, gcc, Using the
3561GNU Compiler Collection (GCC)}, for further details. You would normally
3562use the @option{-b} or @option{-V} switch instead.
3563
3564@item -c
3565@cindex @option{-c} (@command{gcc})
3566Compile. Always use this switch when compiling Ada programs.
3567
3568Note: for some other languages when using @command{gcc}, notably in
3569the case of C and C++, it is possible to use
3570use @command{gcc} without a @option{-c} switch to
3571compile and link in one step. In the case of GNAT, you
3572cannot use this approach, because the binder must be run
3573and @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})
3578Makes the compiler output callgraph information for the program, on a
3579per-file basis. The information is generated in the VCG format.  It can
3580be decorated with additional, per-node and/or per-edge information, if a
3581list 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}
3583marker is specified, the callgraph is decorated with information about
3584dynamically allocated objects.
3585
3586@item -fdump-scos
3587@cindex @option{-fdump-scos} (@command{gcc})
3588Generates SCO (Source Coverage Obligation) information in the ALI file.
3589This information is used by advanced coverage tools. See unit @file{SCOs}
3590in 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})
3595Generates cross reference information in GLI files for C and C++ sources.
3596The GLI files have the same syntax as the ALI files for Ada, and can be used
3597for source navigation in IDEs and on the command line using e.g. gnatxref
3598and the @option{--ext=gli} switch.
3599
3600@item -flto@r{[}=n@r{]}
3601@cindex @option{-flto} (@command{gcc})
3602Enables Link Time Optimization. This switch must be used in conjunction
3603with the traditional @option{-Ox} switches and instructs the compiler to
3604defer most optimizations until the link stage. The advantage of this
3605approach is that the compiler can do a whole-program analysis and choose
3606the best interprocedural optimization strategy based on a complete view
3607of the program, instead of a fragmentary view with the usual approach.
3608This can also speed up the compilation of huge programs and reduce the
3609size of the final executable, compared with a per-unit compilation with
3610full inlining across modules enabled with the @option{-gnatn2} switch.
3611The drawback of this approach is that it may require much more memory.
3612The switch, as well as the accompanying @option{-Ox} switches, must be
3613specified both for the compilation and the link phases.
3614If the @var{n} parameter is specified, the optimization and final code
3615generation at link time are executed using @var{n} parallel jobs by
3616means of an installed @command{make} program.
3617
3618@item -fno-inline
3619@cindex @option{-fno-inline} (@command{gcc})
3620Suppresses all inlining, even if other optimization or inlining
3621switches are set.  This includes suppression of inlining that
3622results from the use of the pragma @code{Inline_Always}.
3623Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3624are ignored, and @option{-gnatn} and @option{-gnatN} have no
3625effects if this switch is present.  Note that inlining can also
3626be 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})
3630Suppresses automatic inlining of subprograms, which is enabled
3631if @option{-O3} is used.
3632
3633@item -fno-inline-small-functions
3634@cindex @option{-fno-inline-small-functions} (@command{gcc})
3635Suppresses automatic inlining of small subprograms, which is enabled
3636if @option{-O2} is used.
3637
3638@item -fno-inline-functions-called-once
3639@cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3640Suppresses inlining of subprograms local to the unit and called once
3641from within it, which is enabled if @option{-O1} is used.
3642
3643@item -fno-ivopts
3644@cindex @option{-fno-ivopts} (@command{gcc})
3645Suppresses high-level loop induction variable optimizations, which are
3646enabled if @option{-O1} is used. These optimizations are generally
3647profitable but, for some specific cases of loops with numerous uses
3648of the iteration variable that follow a common pattern, they may end
3649up destroying the regularity that could be exploited at a lower level
3650and thus producing inferior code.
3651
3652@item -fno-strict-aliasing
3653@cindex @option{-fno-strict-aliasing} (@command{gcc})
3654Causes the compiler to avoid assumptions regarding non-aliasing
3655of 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})
3660Activates stack checking.
3661See @ref{Stack Overflow Checking} for details.
3662
3663@item -fstack-usage
3664@cindex @option{-fstack-usage} (@command{gcc})
3665Makes the compiler output stack usage information for the program, on a
3666per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3667
3668@item ^-g^/DEBUG^
3669@cindex @option{^-g^/DEBUG^} (@command{gcc})
3670Generate debugging information. This information is stored in the object
3671file and copied from there to the final executable file by the linker,
3672where 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})
3677Enforce Ada 83 restrictions.
3678
3679@item -gnat95
3680@cindex @option{-gnat95} (@command{gcc})
3681Enforce Ada 95 restrictions.
3682
3683@item -gnat05
3684@cindex @option{-gnat05} (@command{gcc})
3685Allow full Ada 2005 features.
3686
3687@item -gnat2005
3688@cindex @option{-gnat2005} (@command{gcc})
3689Allow 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})
3696Allow full Ada 2012 features (same as @option{-gnat12})
3697
3698@item -gnata
3699@cindex @option{-gnata} (@command{gcc})
3700Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3701activated. Note that these pragmas can also be controlled using the
3702configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3703It also activates pragmas @code{Check}, @code{Precondition}, and
3704@code{Postcondition}. Note that these pragmas can also be controlled
3705using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3706also activates all assertions defined in the RM as aspects: preconditions,
3707postconditions, type invariants and (sub)type predicates. In all Ada modes,
3708corresponding pragmas for type invariants and (sub)type predicates are
3709also activated.
3710
3711@item -gnatA
3712@cindex @option{-gnatA} (@command{gcc})
3713Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3714it will be ignored.
3715
3716@item -gnatb
3717@cindex @option{-gnatb} (@command{gcc})
3718Generate brief messages to @file{stderr} even if verbose mode set.
3719
3720@item -gnatB
3721@cindex @option{-gnatB} (@command{gcc})
3722Assume no invalid (bad) values except for 'Valid attribute use
3723(@pxref{Validity Checking}).
3724
3725@item -gnatc
3726@cindex @option{-gnatc} (@command{gcc})
3727Check syntax and semantics only (no code generation attempted). When the
3728compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3729only given to the compiler (after @option{-cargs} or in package Compiler of
3730the project file, @command{gnatmake} will fail because it will not find the
3731object file after compilation. If @command{gnatmake} is called with
3732@option{-gnatc} as a builder switch (before @option{-cargs} or in package
3733Builder of the project file) then @command{gnatmake} will not fail because
3734it will not look for the object files after compilation, and it will not try
3735to build and link. This switch may not be given if a previous @code{-gnatR}
3736switch has been given, since @code{-gnatR} requires that the code generator
3737be called to complete determination of representation information.
3738
3739@item -gnatC
3740@cindex @option{-gnatC} (@command{gcc})
3741Generate CodePeer intermediate format (no code generation attempted).
3742This switch will generate an intermediate representation suitable for
3743use by CodePeer (@file{.scil} files). This switch is not compatible with
3744code generation (it will, among other things, disable some switches such
3745as -gnatn, and enable others such as -gnata).
3746
3747@item -gnatd
3748@cindex @option{-gnatd} (@command{gcc})
3749Specify debug options for the compiler. The string of characters after
3750the @option{-gnatd} specify the specific debug options. The possible
3751characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3752compiler source file @file{debug.adb} for details of the implemented
3753debug options. Certain debug options are relevant to applications
3754programmers, and these are documented at appropriate points in this
3755users 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
3764Create expanded source files for source level debugging. This switch
3765also 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})
3771Check that there is no aliasing between two parameters of the same subprogram.
3772
3773@item -gnatec=@var{path}
3774@cindex @option{-gnatec} (@command{gcc})
3775Specify 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})
3783Generate CodePeer messages in a compiler-like format. This switch is only
3784effective if @option{-gnatcC} is also specified and requires an installation
3785of CodePeer.
3786
3787@item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3788@cindex @option{-gnated} (@command{gcc})
3789Disable atomic synchronization
3790
3791@item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3792@cindex @option{-gnateD} (@command{gcc})
3793Defines a symbol, associated with @var{value}, for preprocessing.
3794(@pxref{Integrated Preprocessing}).
3795
3796@item -gnateE
3797@cindex @option{-gnateE} (@command{gcc})
3798Generate extra information in exception messages. In particular, display
3799extra column information and the value and range associated with index and
3800range check failures, and extra column information for access checks.
3801In cases where the compiler is able to determine at compile time that
3802a check will fail, it gives a warning, and the extra information is not
3803produced at run time.
3804
3805@item -gnatef
3806@cindex @option{-gnatef} (@command{gcc})
3807Display full source path name in brief error messages.
3808
3809@item -gnateF
3810@cindex @option{-gnateF} (@command{gcc})
3811Check for overflow on all floating-point operations, including those
3812for 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})
3817Save result of preprocessing in a text file.
3818
3819@item -gnatei@var{nnn}
3820@cindex @option{-gnatei} (@command{gcc})
3821Set 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
3823the rare case when a single unit legitimately exceeds this limit.
3824
3825@item -gnateI@var{nnn}
3826@cindex @option{-gnateI} (@command{gcc})
3827Indicates that the source is a multi-unit source and that the index of the
3828unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3829to be a valid index in the multi-unit source.
3830
3831@item -gnatel
3832@cindex @option{-gnatel} (@command{gcc})
3833This switch can be used with the static elaboration model to issue info
3834messages showing
3835where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3836are generated. This is useful in diagnosing elaboration circularities
3837caused by these implicit pragmas when using the static elaboration
3838model. See See the section in this guide on elaboration checking for
3839further details. These messages are not generated by default, and are
3840intended only for temporary use when debugging circularity problems.
3841
3842@item -gnateL
3843@cindex @option{-gnatel} (@command{gcc})
3844This switch turns off the info messages about implicit elaboration pragmas.
3845
3846@item -gnatem=@var{path}
3847@cindex @option{-gnatem} (@command{gcc})
3848Specify 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})
3856Specify 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})
3864Turn categorization dependency errors into warnings.
3865Ada requires that units that WITH one another have compatible categories, for
3866example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3867these errors become warnings (which can be ignored, or suppressed in the usual
3868manner). This can be useful in some specialized circumstances such as the
3869temporary use of special test software.
3870
3871@item -gnateS
3872@cindex @option{-gnateS} (@command{gcc})
3873Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3874
3875@item -gnatet=@var{path}
3876@cindex @option{-gnatet=file} (@command{gcc})
3877Generate target dependent information. The format of the output file is
3878described in the section about switch @option{-gnateT}.
3879
3880@item -gnateT=@var{path}
3881@cindex @option{-gnateT} (@command{gcc})
3882Read target dependent information, such as endianness or sizes and alignments
3883of base type. If this switch is passed, the default target dependent
3884information of the compiler is replaced by the one read from the input file.
3885This is used by tools other than the compiler, e.g. to do
3886semantic analysis of programs that will run on some other target than
3887the machine on which the tool is run.
3888
3889The following target dependent values should be defined,
3890where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3891positive integer value, and fields marked with a question mark are
3892boolean fields, where a value of 0 is False, and a value of 1 is True:
3893
3894@smallexample
3895Bits_BE                    : Nat; -- Bits stored big-endian?
3896Bits_Per_Unit              : Pos; -- Bits in a storage unit
3897Bits_Per_Word              : Pos; -- Bits in a word
3898Bytes_BE                   : Nat; -- Bytes stored big-endian?
3899Char_Size                  : Pos; -- Standard.Character'Size
3900Double_Float_Alignment     : Nat; -- Alignment of double float
3901Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
3902Double_Size                : Pos; -- Standard.Long_Float'Size
3903Float_Size                 : Pos; -- Standard.Float'Size
3904Float_Words_BE             : Nat; -- Float words stored big-endian?
3905Int_Size                   : Pos; -- Standard.Integer'Size
3906Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
3907Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
3908Long_Size                  : Pos; -- Standard.Long_Integer'Size
3909Maximum_Alignment          : Pos; -- Maximum permitted alignment
3910Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
3911Pointer_Size               : Pos; -- System.Address'Size
3912Short_Enums                : Nat; -- Short foreign convention enums?
3913Short_Size                 : Pos; -- Standard.Short_Integer'Size
3914Strict_Alignment           : Nat; -- Strict alignment?
3915System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3916Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
3917Words_BE                   : Nat; -- Words stored big-endian?
3918@end smallexample
3919
3920The format of the input file is as follows. First come the values of
3921the variables defined above, with one line per value:
3922
3923@smallexample
3924name  value
3925@end smallexample
3926
3927where @code{name} is the name of the parameter, spelled out in full,
3928and cased as in the above list, and @code{value} is an unsigned decimal
3929integer. Two or more blanks separates the name from the value.
3930
3931All the variables must be present, in alphabetical order (i.e. the
3932same order as the list above).
3933
3934Then there is a blank line to separate the two parts of the file. Then
3935come the lines showing the floating-point types to be registered, with
3936one line per registered mode:
3937
3938@smallexample
3939name  digs float_rep size alignment
3940@end smallexample
3941
3942where @code{name} is the string name of the type (which can have
3943single spaces embedded in the name (e.g. long double), @code{digs} is
3944the number of digits for the floating-point type, @code{float_rep} is
3945the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3946AAMP), @code{size} is the size in bits, @code{alignment} is the
3947alignment in bits. The name is followed by at least two blanks, fields
3948are separated by at least one blank, and a LF character immediately
3949follows the alignment field.
3950
3951Here is an example of a target parameterization file:
3952
3953@smallexample
3954Bits_BE                       0
3955Bits_Per_Unit                 8
3956Bits_Per_Word                64
3957Bytes_BE                      0
3958Char_Size                     8
3959Double_Float_Alignment        0
3960Double_Scalar_Alignment       0
3961Double_Size                  64
3962Float_Size                   32
3963Float_Words_BE                0
3964Int_Size                     64
3965Long_Double_Size            128
3966Long_Long_Size               64
3967Long_Size                    64
3968Maximum_Alignment            16
3969Max_Unaligned_Field          64
3970Pointer_Size                 64
3971Short_Size                   16
3972Strict_Alignment              0
3973System_Allocator_Alignment   16
3974Wchar_T_Size                 32
3975Words_BE                      0
3976
3977float         15  I  64  64
3978double        15  I  64  64
3979long double   18  I  80 128
3980TF            33  I 128 128
3981@end smallexample
3982
3983@item -gnateu
3984@cindex @option{-gnateu} (@command{gcc})
3985Ignore unrecognized validity, warning, and style switches that
3986appear after this switch is given. This may be useful when
3987compiling sources developed on a later version of the compiler
3988with an earlier version. Of course the earlier version must
3989support this switch.
3990
3991@item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3992@cindex @option{-gnateV} (@command{gcc})
3993Check validity of subprogram parameters.
3994
3995@item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3996@cindex @option{-gnateY} (@command{gcc})
3997Ignore all STYLE_CHECKS pragmas. Full legality checks
3998are still carried out, but the pragmas have no effect
3999on what style checks are active. This allows all style
4000checking options to be controlled from the command line.
4001
4002@item -gnatE
4003@cindex @option{-gnatE} (@command{gcc})
4004Full dynamic elaboration checks.
4005
4006@item -gnatf
4007@cindex @option{-gnatf} (@command{gcc})
4008Full errors. Multiple errors per line, all undefined references, do not
4009attempt to suppress cascaded errors.
4010
4011@item -gnatF
4012@cindex @option{-gnatF} (@command{gcc})
4013Externals names are folded to all uppercase.
4014
4015@item ^-gnatg^/GNAT_INTERNAL^
4016@cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4017Internal GNAT implementation mode. This should not be used for
4018applications programs, it is intended only for use by the compiler
4019and its run-time library. For documentation, see the GNAT sources.
4020Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4021@option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4022@option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4023so that all standard warnings and all standard style options are turned on.
4024All 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
4033List generated expanded code in source form.
4034
4035@item ^-gnath^/HELP^
4036@cindex @option{^-gnath^/HELP^} (@command{gcc})
4037Output 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})
4041Identifier character set
4042@ifclear vms
4043(@var{c}=1/2/3/4/8/9/p/f/n/w).
4044@end ifclear
4045For details of the possible selections for @var{c},
4046see @ref{Character Set Control}.
4047
4048@item ^-gnatI^/IGNORE_REP_CLAUSES^
4049@cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4050Ignore representation clauses. When this switch is used,
4051representation clauses are treated as comments. This is useful
4052when initially porting code where you want to ignore rep clause
4053problems, and also for compiling foreign code (particularly
4054for use with ASIS). The representation clauses that are ignored
4055are: enumeration_representation_clause, record_representation_clause,
4056and attribute_definition_clause for the following attributes:
4057Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4058Object_Size, Size, Small, Stream_Size, and Value_Size.
4059Note that this option should be used only for compiling -- the
4060code is likely to malfunction at run time.
4061
4062@item -gnatjnn
4063@cindex @option{-gnatjnn} (@command{gcc})
4064Reformat error messages to fit on nn character lines
4065
4066@item -gnatk=@var{n}
4067@cindex @option{-gnatk} (@command{gcc})
4068Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4069
4070@item -gnatl
4071@cindex @option{-gnatl} (@command{gcc})
4072Output full source listing with embedded error messages.
4073
4074@item -gnatL
4075@cindex @option{-gnatL} (@command{gcc})
4076Used in conjunction with -gnatG or -gnatD to intersperse original
4077source lines (as comment lines with line numbers) in the expanded
4078source output.
4079
4080@item -gnatm=@var{n}
4081@cindex @option{-gnatm} (@command{gcc})
4082Limit number of detected error or warning messages to @var{n}
4083where @var{n} is in the range 1..999999. The default setting if
4084no switch is given is 9999. If the number of warnings reaches this
4085limit, then a message is output and further warnings are suppressed,
4086but the compilation is continued. If the number of error messages
4087reaches this limit, then a message is output and the compilation
4088is abandoned. The equal sign here is optional. A value of zero
4089means that no limit applies.
4090
4091@item -gnatn[12]
4092@cindex @option{-gnatn} (@command{gcc})
4093Activate inlining for subprograms for which pragma @code{Inline} is
4094specified. This inlining is performed by the GCC back-end. An optional
4095digit sets the inlining level: 1 for moderate inlining across modules
4096or 2 for full inlining across modules. If no inlining level is specified,
4097the compiler will pick it based on the optimization level.
4098
4099@item -gnatN
4100@cindex @option{-gnatN} (@command{gcc})
4101Activate front end inlining for subprograms for which
4102pragma @code{Inline} is specified. This inlining is performed
4103by the front end and will be visible in the
4104@option{-gnatG} output.
4105
4106When using a gcc-based back end (in practice this means using any version
4107of 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.
4109Historically front end inlining was more extensive than the gcc back end
4110inlining, but that is no longer the case.
4111
4112@item -gnato??
4113@cindex @option{-gnato??} (@command{gcc})
4114Set default mode for handling generation of code to avoid intermediate
4115arithmetic overflow. Here `@code{??}' is two digits, a
4116single digit, or nothing. Each digit is one of the digits `@code{1}'
4117through `@code{3}':
4118
4119@itemize @bullet
4120@item   @code{1}:
4121all intermediate overflows checked against base type (@code{STRICT})
4122@item   @code{2}:
4123minimize intermediate overflows (@code{MINIMIZED})
4124@item   @code{3}:
4125eliminate intermediate overflows (@code{ELIMINATED})
4126@end itemize
4127
4128If only one digit appears then it applies to all
4129cases; if two digits are given, then the first applies outside
4130assertions, and the second within assertions.
4131
4132If no digits follow the @option{-gnato}, then it is equivalent to
4133@option{^-gnato11^/OVERFLOW_CHECKS=11^},
4134causing all intermediate overflows to be handled in strict mode.
4135
4136This switch also causes arithmetic overflow checking to be performed
4137(as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4138
4139The default if no option @option{-gnato} is given is that overflow handling
4140is in @code{STRICT} mode (computations done using the base type), and that
4141overflow checking is suppressed.
4142
4143Note that division by zero is a separate check that is not
4144controlled by this switch (division by zero checking is on by default).
4145
4146See also @ref{Specifying the Desired Mode}.
4147
4148@item -gnatp
4149@cindex @option{-gnatp} (@command{gcc})
4150Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4151has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4152
4153@item -gnat-p
4154@cindex @option{-gnat-p} (@command{gcc})
4155Cancel effect of previous @option{-gnatp} switch.
4156
4157@item -gnatP
4158@cindex @option{-gnatP} (@command{gcc})
4159Enable polling. This is required on some systems (notably Windows NT) to
4160obtain asynchronous abort and asynchronous transfer of control capability.
4161@xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4162details.
4163
4164@item -gnatq
4165@cindex @option{-gnatq} (@command{gcc})
4166Don't quit. Try semantics, even if parse errors.
4167
4168@item -gnatQ
4169@cindex @option{-gnatQ} (@command{gcc})
4170Don't quit. Generate @file{ALI} and tree files even if illegalities.
4171
4172@item -gnatr
4173@cindex @option{-gnatr} (@command{gcc})
4174Treat 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})
4178Output representation information for declared types and objects.
4179Note that this switch is not allowed if a previous @code{-gnatD} switch has
4180been given, since these two switches are not compatible. It is also not allowed
4181if a previous @code{-gnatc} switch has been given, since we must be generating
4182code to be able to determine representation information.
4183
4184@item ^-gnatRm[s]^/REPRESENTATION_INFO^
4185Output convention and parameter passing mechanisms for all subprograms.
4186This form is also incompatible with the use of @code{-gnatc}.
4187
4188@item -gnats
4189@cindex @option{-gnats} (@command{gcc})
4190Syntax check only.
4191
4192@item -gnatS
4193@cindex @option{-gnatS} (@command{gcc})
4194Print package Standard.
4195
4196@item -gnatt
4197@cindex @option{-gnatt} (@command{gcc})
4198Generate tree output file.
4199
4200@item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4201@cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4202All compiler tables start at @var{nnn} times usual starting size.
4203
4204@item -gnatu
4205@cindex @option{-gnatu} (@command{gcc})
4206List units for this compilation.
4207
4208@item -gnatU
4209@cindex @option{-gnatU} (@command{gcc})
4210Tag all error messages with the unique string ``error:''
4211
4212@item -gnatv
4213@cindex @option{-gnatv} (@command{gcc})
4214Verbose mode. Full error output with source lines to @file{stdout}.
4215
4216@item -gnatV
4217@cindex @option{-gnatV} (@command{gcc})
4218Control 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})
4222Warning mode where
4223^@var{xxx} is a string of option letters that^the list of options^ denotes
4224the exact warnings that
4225are 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})
4229Wide 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})
4239Suppress generation of cross-reference information.
4240
4241@item -gnatX
4242@cindex @option{-gnatX} (@command{gcc})
4243Enable GNAT implementation extensions and latest Ada version.
4244
4245@item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4246@cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4247Enable built-in style checks (@pxref{Style Checking}).
4248
4249@item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4250@cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4251Distribution 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
4257to be generated and compiled).
4258@end ifset
4259
4260@item ^-I^/SEARCH=^@var{dir}
4261@cindex @option{^-I^/SEARCH^} (@command{gcc})
4262@cindex RTL
4263Direct GNAT to search the @var{dir} directory for source files needed by
4264the 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
4270Except for the source file named in the command line, do not look for source
4271files 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)
4278This standard gcc switch causes the compiler to use larger offsets in its
4279jump table representation for @code{case} statements.
4280This 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
4283in order to compile large and/or nested @code{case} statements.
4284
4285@item -o @var{file}
4286@cindex @option{-o} (@command{gcc})
4287This switch is used in @command{gcc} to redirect the generated object file
4288and its associated ALI file. Beware of this switch with GNAT, because it may
4289cause the object file and ALI file to have different names which in turn
4290may confuse the binder and the linker.
4291@end ifclear
4292
4293@item -nostdinc
4294@cindex @option{-nostdinc} (@command{gcc})
4295Inhibit the search of the default location for the GNAT Run Time
4296Library (RTL) source files.
4297
4298@item -nostdlib
4299@cindex @option{-nostdlib} (@command{gcc})
4300Inhibit the search of the default location for the GNAT Run Time
4301Library (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
4312No optimization, the default setting if no @option{-O} appears
4313
4314@item n = 1
4315Normal optimization, the default if you specify @option{-O} without
4316an operand. A good compromise between code quality and compilation
4317time.
4318
4319@item n = 2
4320Extensive optimization, may improve execution time, possibly at the cost of
4321substantially increased compilation time.
4322
4323@item n = 3
4324Same as @option{-O2}, and also includes inline expansion for small subprograms
4325in the same unit.
4326
4327@item n = s
4328Optimize space usage
4329@end table
4330
4331@noindent
4332See also @ref{Optimization Levels}.
4333@end ifclear
4334
4335@ifset vms
4336@item  /NOOPTIMIZE
4337@cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4338Equivalent to @option{/OPTIMIZE=NONE}.
4339This is the default behavior in the absence of an @option{/OPTIMIZE}
4340qualifier.
4341
4342@item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4343@cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4344Selects the level of optimization for your program. The supported
4345keywords are as follows:
4346@table @code
4347@item   ALL
4348Perform most optimizations, including those that
4349are expensive.
4350This is the default if the @option{/OPTIMIZE} qualifier is supplied
4351without keyword options.
4352
4353@item   NONE
4354Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4355
4356@item SOME
4357Perform some optimizations, but omit ones that are costly.
4358
4359@item   DEVELOPMENT
4360Same as @code{SOME}.
4361
4362@item INLINING
4363Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4364automatic inlining of small subprograms within a unit
4365
4366@item   UNROLL_LOOPS
4367Try to unroll loops. This keyword may be specified together with
4368any keyword above other than @code{NONE}. Loop unrolling
4369usually, but not always, improves the performance of programs.
4370
4371@item SPACE
4372Optimize space usage
4373@end table
4374
4375@noindent
4376See also @ref{Optimization Levels}.
4377@end ifset
4378
4379@ifclear vms
4380@item -pass-exit-codes
4381@cindex @option{-pass-exit-codes} (@command{gcc})
4382Catch exit codes from the compiler and use the most meaningful as
4383exit status.
4384@end ifclear
4385
4386@item --RTS=@var{rts-path}
4387@cindex @option{--RTS} (@command{gcc})
4388Specifies the default location of the runtime library. Same meaning as the
4389equivalent @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^
4394cause the assembler source file to be
4395generated, using @file{^.s^.S^} as the extension,
4396instead of the object file.
4397This 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}^
4402to cause the generated assembly code file to be annotated with variable
4403names, making it significantly easier to follow.
4404
4405@item ^-v^/VERBOSE^
4406@cindex @option{^-v^/VERBOSE^} (@command{gcc})
4407Show commands generated by the @command{gcc} driver. Normally used only for
4408debugging purposes or if you need to be sure what version of the
4409compiler you are executing.
4410
4411@ifclear vms
4412@item -V @var{ver}
4413@cindex @option{-V} (@command{gcc})
4414Execute @var{ver} version of the compiler. This is the @command{gcc}
4415version, not the GNAT version.
4416@end ifclear
4417
4418@item ^-w^/NO_BACK_END_WARNINGS^
4419@cindex @option{-w} (@command{gcc})
4420Turn off warnings generated by the back end of the compiler. Use of
4421this switch also causes the default for front end warnings to be set
4422to suppress (as though @option{-gnatws} had appeared at the start of
4423the options).
4424
4425@end table
4426
4427@ifclear vms
4428@c Combining qualifiers does not work on VMS
4429You may combine a sequence of GNAT switches into a single switch. For
4430example, the combined switch
4431
4432@cindex Combining GNAT switches
4433@smallexample
4434-gnatofi3
4435@end smallexample
4436
4437@noindent
4438is equivalent to specifying the following sequence of switches:
4439
4440@smallexample
4441-gnato -gnatf -gnati3
4442@end smallexample
4443@end ifclear
4444
4445@noindent
4446The following restrictions apply to the combination of switches
4447in this manner:
4448
4449@itemize @bullet
4450@item
4451The switch @option{-gnatc} if combined with other switches must come
4452first in the string.
4453
4454@item
4455The switch @option{-gnats} if combined with other switches must come
4456first in the string.
4457
4458@item
4459The switches
4460^^@option{/DISTRIBUTION_STUBS=},^
4461@option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4462switches, and only one of them may appear in the command line.
4463
4464@item
4465The switch @option{-gnat-p} may not be combined with any other switch.
4466
4467@ifclear vms
4468@item
4469Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4470switch), then all further characters in the switch are interpreted
4471as style modifiers (see description of @option{-gnaty}).
4472
4473@item
4474Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4475switch), then all further characters in the switch are interpreted
4476as debug flags (see description of @option{-gnatd}).
4477
4478@item
4479Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4480switch), then all further characters in the switch are interpreted
4481as warning mode modifiers (see description of @option{-gnatw}).
4482
4483@item
4484Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4485switch), then all further characters in the switch are interpreted
4486as validity checking options (@pxref{Validity Checking}).
4487
4488@item
4489Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4490a 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
4499The standard default format for error messages is called ``brief format''.
4500Brief format messages are written to @file{stderr} (the standard error
4501file) and have the following form:
4502
4503@smallexample
4504e.adb:3:04: Incorrect spelling of keyword "function"
4505e.adb:4:20: ";" should be "is"
4506@end smallexample
4507
4508@noindent
4509The first integer after the file name is the line number in the file,
4510and the second integer is the column number within the line.
4511@ifclear vms
4512@code{GPS} can parse the error messages
4513and point to the referenced character.
4514@end ifclear
4515The following switches provide control over the error message
4516format:
4517
4518@table @option
4519@c !sort!
4520@item -gnatv
4521@cindex @option{-gnatv} (@command{gcc})
4522@findex stdout
4523@ifclear vms
4524The v stands for verbose.
4525@end ifclear
4526The effect of this setting is to write long-format error
4527messages to @file{stdout} (the standard output file.
4528The same program compiled with the
4529@option{-gnatv} switch would generate:
4530
4531@smallexample
4532@cartouche
45333. funcion X (Q : Integer)
4534   |
4535>>> Incorrect spelling of keyword "function"
45364. return Integer;
4537                 |
4538>>> ";" should be "is"
4539@end cartouche
4540@end smallexample
4541
4542@noindent
4543The vertical bar indicates the location of the error, and the @samp{>>>}
4544prefix can be used to search for error messages. When this switch is
4545used the only source lines output are those with errors.
4546
4547@item -gnatl
4548@cindex @option{-gnatl} (@command{gcc})
4549@ifclear vms
4550The @code{l} stands for list.
4551@end ifclear
4552This switch causes a full listing of
4553the file to be generated. In the case where a body is
4554compiled, the corresponding spec is also listed, along
4555with any subunits. Typical output from compiling a package
4556body @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
4572Compiling: p.ads
4573
4574     1. package p is
4575     2.    pragma Elaborate_Body
4576                                |
4577        >>> missing ";"
4578
4579     3. end p;
4580
4581Compiling: 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
4599When you specify the @option{-gnatv} or @option{-gnatl} switches and
4600standard output is redirected, a brief summary is written to
4601@file{stderr} (standard error) giving the number of error messages and
4602warning messages generated.
4603
4604@item ^-gnatl^/OUTPUT_FILE^=file
4605@cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4606This has the same effect as @option{-gnatl} except that the output is
4607written 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
4609of the file to be written. If @file{fname} is an extension, it is
4610appended to the name of the file being compiled. For example, if
4611file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4612then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4613
4614@item -gnatU
4615@cindex @option{-gnatU} (@command{gcc})
4616This switch forces all error messages to be preceded by the unique
4617string ``error:''. This means that error messages take a few more
4618characters in space, but allows easy searching for and identification
4619of error messages.
4620
4621@item -gnatb
4622@cindex @option{-gnatb} (@command{gcc})
4623@ifclear vms
4624The @code{b} stands for brief.
4625@end ifclear
4626This switch causes GNAT to generate the
4627brief format error messages to @file{stderr} (the standard error
4628file) as well as the verbose
4629format 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
4635The @code{m} stands for maximum.
4636@end ifclear
4637@var{n} is a decimal integer in the
4638range of 1 to 999999 and limits the number of error or warning
4639messages to be generated. For example, using
4640@option{-gnatm2} might yield
4641
4642@smallexample
4643e.adb:3:04: Incorrect spelling of keyword "function"
4644e.adb:5:35: missing ".."
4645fatal error: maximum number of errors detected
4646compilation abandoned
4647@end smallexample
4648
4649@noindent
4650The default setting if
4651no switch is given is 9999. If the number of warnings reaches this
4652limit, then a message is output and further warnings are suppressed,
4653but the compilation is continued. If the number of error messages
4654reaches this limit, then a message is output and the compilation
4655is abandoned. A value of zero means that no limit applies.
4656
4657@noindent
4658Note 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
4665The @code{f} stands for full.
4666@end ifclear
4667Normally, the compiler suppresses error messages that are likely to be
4668redundant. This switch causes all error
4669messages to be generated. In particular, in the case of
4670references to undefined variables. If a given variable is referenced
4671several times, the normal format of messages is
4672@smallexample
4673e.adb:7:07: "V" is undefined (more references follow)
4674@end smallexample
4675
4676@noindent
4677where the parenthetical comment warns that there are additional
4678references to the variable @code{V}. Compiling the same program with the
4679@option{-gnatf} switch yields
4680
4681@smallexample
4682e.adb:7:07: "V" is undefined
4683e.adb:8:07: "V" is undefined
4684e.adb:8:12: "V" is undefined
4685e.adb:8:16: "V" is undefined
4686e.adb:9:07: "V" is undefined
4687e.adb:9:12: "V" is undefined
4688@end smallexample
4689
4690@noindent
4691The @option{-gnatf} switch also generates additional information for
4692some error messages.  Some examples are:
4693
4694@itemize @bullet
4695@item
4696Details on possibly non-portable unchecked conversion
4697@item
4698List possible interpretations for ambiguous calls
4699@item
4700Additional details on incorrect parameters
4701@end itemize
4702
4703@item -gnatjnn
4704@cindex @option{-gnatjnn} (@command{gcc})
4705In normal operation mode (or if @option{-gnatj0} is used), then error messages
4706with continuation lines are treated as though the continuation lines were
4707separate messages (and so a warning with two continuation lines counts as
4708three warnings, and is listed as three separate messages).
4709
4710If the @option{-gnatjnn} switch is used with a positive value for nn, then
4711messages are output in a different manner. A message and all its continuation
4712lines are treated as a unit, and count as only one warning or message in the
4713statistics totals. Furthermore, the message is reformatted so that no line
4714is longer than nn characters.
4715
4716@item -gnatq
4717@cindex @option{-gnatq} (@command{gcc})
4718@ifclear vms
4719The @code{q} stands for quit (really ``don't quit'').
4720@end ifclear
4721In normal operation mode, the compiler first parses the program and
4722determines if there are any syntax errors. If there are, appropriate
4723error messages are generated and compilation is immediately terminated.
4724This switch tells
4725GNAT to continue with semantic analysis even if syntax errors have been
4726found. This may enable the detection of more errors in a single run. On
4727the other hand, the semantic analyzer is more likely to encounter some
4728internal fatal error when given a syntactically invalid tree.
4729
4730@item -gnatQ
4731@cindex @option{-gnatQ} (@command{gcc})
4732In normal operation mode, the @file{ALI} file is not generated if any
4733illegalities are detected in the program. The use of @option{-gnatQ} forces
4734generation of the @file{ALI} file. This file is marked as being in
4735error, so it cannot be used for binding purposes, but it does contain
4736reasonably complete cross-reference information, and thus may be useful
4737for use by tools (e.g., semantic browsing tools or integrated development
4738environments) that are driven from the @file{ALI} file. This switch
4739implies @option{-gnatq}, since the semantic phase must be run to get a
4740meaningful ALI file.
4741
4742In addition, if @option{-gnatt} is also specified, then the tree file is
4743generated even if there are illegalities. It may be useful in this case
4744to also specify @option{-gnatq} to ensure that full semantic processing
4745occurs. The resulting tree file can be processed by ASIS, for the purpose
4746of providing partial information about illegal units, but if the error
4747causes the tree to be badly malformed, then ASIS may crash during the
4748analysis.
4749
4750When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4751being in error, @command{gnatmake} will attempt to recompile the source when it
4752finds such an @file{ALI} file, including with switch @option{-gnatc}.
4753
4754Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4755since 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
4763In addition to error messages, which correspond to illegalities as defined
4764in the Ada Reference Manual, the compiler detects two kinds of warning
4765situations.
4766
4767First, the compiler considers some constructs suspicious and generates a
4768warning message to alert you to a possible error. Second, if the
4769compiler detects a situation that is sure to raise an exception at
4770run time, it generates a warning message. The following shows an example
4771of warning messages:
4772@smallexample
4773e.adb:4:24: warning: creation of object may raise Storage_Error
4774e.adb:10:17: warning: static value out of range
4775e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4776@end smallexample
4777
4778@noindent
4779GNAT considers a large number of situations as appropriate
4780for the generation of warning messages. As always, warnings are not
4781definite indications of errors. For example, if you do an out-of-range
4782assignment with the deliberate intention of raising a
4783@code{Constraint_Error} exception, then the warning that may be
4784issued does not indicate an error. Some of the situations for which GNAT
4785issues warnings (at least some of the time) are given in the following
4786list. This list is not complete, and new warnings are often added to
4787subsequent versions of GNAT. The list is intended to give a general idea
4788of the kinds of warnings that are generated.
4789
4790@itemize @bullet
4791@item
4792Possible infinitely recursive calls
4793
4794@item
4795Out-of-range values being assigned
4796
4797@item
4798Possible order of elaboration problems
4799
4800@item
4801Assertions (pragma Assert) that are sure to fail
4802
4803@item
4804Unreachable code
4805
4806@item
4807Address clauses with possibly unaligned values, or where an attempt is
4808made to overlay a smaller variable with a larger one.
4809
4810@item
4811Fixed-point type declarations with a null range
4812
4813@item
4814Direct_IO or Sequential_IO instantiated with a type that has access values
4815
4816@item
4817Variables that are never assigned a value
4818
4819@item
4820Variables that are referenced before being initialized
4821
4822@item
4823Task entries with no corresponding @code{accept} statement
4824
4825@item
4826Duplicate accepts for the same task entry in a @code{select}
4827
4828@item
4829Objects that take too much storage
4830
4831@item
4832Unchecked conversion between types of differing sizes
4833
4834@item
4835Missing @code{return} statement along some execution path in a function
4836
4837@item
4838Incorrect (unrecognized) pragmas
4839
4840@item
4841Incorrect external names
4842
4843@item
4844Allocation from empty storage pool
4845
4846@item
4847Potentially blocking operation in protected type
4848
4849@item
4850Suspicious parenthesization of expressions
4851
4852@item
4853Mismatching bounds in an aggregate
4854
4855@item
4856Attempt to return local value by reference
4857
4858@item
4859Premature instantiation of a generic body
4860
4861@item
4862Attempt to pack aliased components
4863
4864@item
4865Out of bounds array subscripts
4866
4867@item
4868Wrong length on string assignment
4869
4870@item
4871Violations of style rules if style checking is enabled
4872
4873@item
4874Unused @code{with} clauses
4875
4876@item
4877@code{Bit_Order} usage that does not have any effect
4878
4879@item
4880@code{Standard.Duration} used to resolve universal fixed expression
4881
4882@item
4883Dereference of possibly null value
4884
4885@item
4886Declaration that is likely to cause storage error
4887
4888@item
4889Internal GNAT unit @code{with}'ed by application unit
4890
4891@item
4892Values known to be out of range at compile time
4893
4894@item
4895Unreferenced or unmodified variables. Note that a special
4896exemption applies to variables which contain any of the substrings
4897@code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4898are considered likely to be intentionally used in a situation where
4899otherwise a warning would be given, so warnings of this kind are
4900always suppressed for such variables.
4901
4902@item
4903Address overlays that could clobber memory
4904
4905@item
4906Unexpected initialization when address clause present
4907
4908@item
4909Bad alignment for address clause
4910
4911@item
4912Useless type conversions
4913
4914@item
4915Redundant assignment statements and other redundant constructs
4916
4917@item
4918Useless exception handlers
4919
4920@item
4921Accidental hiding of name by child unit
4922
4923@item
4924Access before elaboration detected at compile time
4925
4926@item
4927A range in a @code{for} loop that is known to be null or might be null
4928
4929@end itemize
4930
4931@noindent
4932The following section lists compiler switches that are available
4933to control the handling of warning messages. It is also possible
4934to exercise much finer control over what warnings are issued and
4935suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4936gnat_rm, GNAT Reference manual}.
4937
4938@table @option
4939@c !sort!
4940@item -gnatwa
4941@emph{Activate most optional warnings.}
4942@cindex @option{-gnatwa} (@command{gcc})
4943This switch activates most optional warning messages.  See the remaining list
4944in this section for details on optional warning messages that can be
4945individually controlled.  The warnings that are not turned on by this
4946switch are:
4947@option{-gnatwd} (implicit dereferencing),
4948@option{-gnatwh} (hiding),
4949@option{-gnatw.d} (tag warnings with -gnatw switch)
4950@option{-gnatw.h} (holes (gaps) in record layouts)
4951@option{-gnatw.i} (overlapping actuals),
4952@option{-gnatw.k} (redefinition of names in standard),
4953@option{-gnatwl} (elaboration warnings),
4954@option{-gnatw.l} (inherited aspects),
4955@option{-gnatw.o} (warn on values set by out parameters ignored),
4956@option{-gnatwt} (tracking of deleted conditional code)
4957and @option{-gnatw.u} (unordered enumeration),
4958All other optional warnings are turned on.
4959
4960@item -gnatwA
4961@emph{Suppress all optional errors.}
4962@cindex @option{-gnatwA} (@command{gcc})
4963This switch suppresses all optional warning messages, see remaining list
4964in this section for details on optional warning messages that can be
4965individually controlled. Note that unlike switch @option{-gnatws}, the
4966use of switch @option{-gnatwA} does not suppress warnings that are
4967normally given unconditionally and cannot be individually controlled
4968(for example, the warning about a missing exit path in a function).
4969Also, again unlike switch @option{-gnatws}, warnings suppressed by
4970the use of switch @option{-gnatwA} can be individually turned back
4971on. For example the use of switch @option{-gnatwA} followed by
4972switch @option{-gnatwd} will suppress all optional warnings except
4973the warnings for implicit dereferencing.
4974
4975@item -gnatw.a
4976@emph{Activate warnings on failing assertions.}
4977@cindex @option{-gnatw.a} (@command{gcc})
4978@cindex Assert failures
4979This switch activates warnings for assertions where the compiler can tell at
4980compile time that the assertion will fail. Note that this warning is given
4981even if assertions are disabled. The default is that such warnings are
4982generated.
4983
4984@item -gnatw.A
4985@emph{Suppress warnings on failing assertions.}
4986@cindex @option{-gnatw.A} (@command{gcc})
4987@cindex Assert failures
4988This switch suppresses warnings for assertions where the compiler can tell at
4989compile time that the assertion will fail.
4990
4991@item -gnatwb
4992@emph{Activate warnings on bad fixed values.}
4993@cindex @option{-gnatwb} (@command{gcc})
4994@cindex Bad fixed values
4995@cindex Fixed-point Small value
4996@cindex Small value
4997This switch activates warnings for static fixed-point expressions whose
4998value is not an exact multiple of Small. Such values are implementation
4999dependent, since an implementation is free to choose either of the multiples
5000that surround the value. GNAT always chooses the closer one, but this is not
5001required behavior, and it is better to specify a value that is an exact
5002multiple, ensuring predictable execution. The default is that such warnings
5003are not generated.
5004
5005@item -gnatwB
5006@emph{Suppress warnings on bad fixed values.}
5007@cindex @option{-gnatwB} (@command{gcc})
5008This switch suppresses warnings for static fixed-point expressions whose
5009value is not an exact multiple of Small.
5010
5011@item -gnatw.b
5012@emph{Activate warnings on biased representation.}
5013@cindex @option{-gnatw.b} (@command{gcc})
5014@cindex Biased representation
5015This switch activates warnings when a size clause, value size clause, component
5016clause, or component size clause forces the use of biased representation for an
5017integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5018to represent 10/11). The default is that such warnings are generated.
5019
5020@item -gnatw.B
5021@emph{Suppress warnings on biased representation.}
5022@cindex @option{-gnatwB} (@command{gcc})
5023This switch suppresses warnings for representation clauses that force the use
5024of biased representation.
5025
5026@item -gnatwc
5027@emph{Activate warnings on conditionals.}
5028@cindex @option{-gnatwc} (@command{gcc})
5029@cindex Conditionals, constant
5030This switch activates warnings for conditional expressions used in
5031tests that are known to be True or False at compile time. The default
5032is that such warnings are not generated.
5033Note that this warning does
5034not get issued for the use of boolean variables or constants whose
5035values are known at compile time, since this is a standard technique
5036for conditional compilation in Ada, and this would generate too many
5037false positive warnings.
5038
5039This warning option also activates a special test for comparisons using
5040the operators ``>='' and`` <=''.
5041If the compiler can tell that only the equality condition is possible,
5042then it will warn that the ``>'' or ``<'' part of the test
5043is useless and that the operator could be replaced by ``=''.
5044An example would be comparing a @code{Natural} variable <= 0.
5045
5046This warning option also generates warnings if
5047one or both tests is optimized away in a membership test for integer
5048values if the result can be determined at compile time. Range tests on
5049enumeration types are not included, since it is common for such tests
5050to include an end point.
5051
5052This warning can also be turned on using @option{-gnatwa}.
5053
5054@item -gnatwC
5055@emph{Suppress warnings on conditionals.}
5056@cindex @option{-gnatwC} (@command{gcc})
5057This switch suppresses warnings for conditional expressions used in
5058tests that are known to be True or False at compile time.
5059
5060@item -gnatw.c
5061@emph{Activate warnings on missing component clauses.}
5062@cindex @option{-gnatw.c} (@command{gcc})
5063@cindex Component clause, missing
5064This switch activates warnings for record components where a record
5065representation clause is present and has component clauses for the
5066majority, but not all, of the components. A warning is given for each
5067component for which no component clause is present.
5068
5069This warning can also be turned on using @option{-gnatwa}.
5070
5071@item -gnatw.C
5072@emph{Suppress warnings on missing component clauses.}
5073@cindex @option{-gnatwC} (@command{gcc})
5074This switch suppresses warnings for record components that are
5075missing a component clause in the situation described above.
5076
5077@item -gnatwd
5078@emph{Activate warnings on implicit dereferencing.}
5079@cindex @option{-gnatwd} (@command{gcc})
5080If this switch is set, then the use of a prefix of an access type
5081in an indexed component, slice, or selected component without an
5082explicit @code{.all} will generate a warning. With this warning
5083enabled, access checks occur only at points where an explicit
5084@code{.all} appears in the source code (assuming no warnings are
5085generated as a result of this switch). The default is that such
5086warnings are not generated.
5087Note that @option{-gnatwa} does not affect the setting of
5088this warning option.
5089
5090@item -gnatwD
5091@emph{Suppress warnings on implicit dereferencing.}
5092@cindex @option{-gnatwD} (@command{gcc})
5093@cindex Implicit dereferencing
5094@cindex Dereferencing, implicit
5095This switch suppresses warnings for implicit dereferences in
5096indexed components, slices, and selected components.
5097
5098@item -gnatw.d
5099@emph{Activate tagging of warning messages.}
5100@cindex @option{-gnatw.d} (@command{gcc})
5101If this switch is set, then warning messages are tagged, either with
5102the string ``@option{-gnatw?}'' showing which switch controls the warning,
5103or with ``[enabled by default]'' if the warning is not under control of a
5104specific @option{-gnatw?} switch. This mode is off by default, and is not
5105affected by the use of @code{-gnatwa}.
5106
5107@item -gnatw.D
5108@emph{Deactivate tagging of warning messages.}
5109@cindex @option{-gnatw.d} (@command{gcc})
5110If this switch is set, then warning messages return to the default
5111mode in which warnings are not tagged as described above for
5112@code{-gnatw.d}.
5113
5114@item -gnatwe
5115@emph{Treat warnings and style checks as errors.}
5116@cindex @option{-gnatwe} (@command{gcc})
5117@cindex Warnings, treat as error
5118This switch causes warning messages and style check messages to be
5119treated as errors.
5120The warning string still appears, but the warning messages are counted
5121as errors, and prevent the generation of an object file. Note that this
5122is the only -gnatw switch that affects the handling of style check messages.
5123
5124@item -gnatw.e
5125@emph{Activate every optional warning}
5126@cindex @option{-gnatw.e} (@command{gcc})
5127@cindex Warnings, activate every optional warning
5128This switch activates all optional warnings, including those which
5129are not activated by @code{-gnatwa}. The use of this switch is not
5130recommended for normal use. If you turn this switch on, it is almost
5131certain that you will get large numbers of useless warnings. The
5132warnings that are excluded from @code{-gnatwa} are typically highly
5133specialized warnings that are suitable for use only in code that has
5134been specifically designed according to specialized coding rules.
5135
5136@item -gnatwf
5137@emph{Activate warnings on unreferenced formals.}
5138@cindex @option{-gnatwf} (@command{gcc})
5139@cindex Formals, unreferenced
5140This switch causes a warning to be generated if a formal parameter
5141is not referenced in the body of the subprogram. This warning can
5142also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5143default is that these warnings are not generated.
5144
5145@item -gnatwF
5146@emph{Suppress warnings on unreferenced formals.}
5147@cindex @option{-gnatwF} (@command{gcc})
5148This switch suppresses warnings for unreferenced formal
5149parameters. Note that the
5150combination @option{-gnatwu} followed by @option{-gnatwF} has the
5151effect of warning on unreferenced entities other than subprogram
5152formals.
5153
5154@item -gnatwg
5155@emph{Activate warnings on unrecognized pragmas.}
5156@cindex @option{-gnatwg} (@command{gcc})
5157@cindex Pragmas, unrecognized
5158This switch causes a warning to be generated if an unrecognized
5159pragma is encountered. Apart from issuing this warning, the
5160pragma is ignored and has no effect. This warning can
5161also be turned on using @option{-gnatwa}. The default
5162is that such warnings are issued (satisfying the Ada Reference
5163Manual requirement that such warnings appear).
5164
5165@item -gnatwG
5166@emph{Suppress warnings on unrecognized pragmas.}
5167@cindex @option{-gnatwG} (@command{gcc})
5168This switch suppresses warnings for unrecognized pragmas.
5169
5170@item -gnatwh
5171@emph{Activate warnings on hiding.}
5172@cindex @option{-gnatwh} (@command{gcc})
5173@cindex Hiding of Declarations
5174This switch activates warnings on hiding declarations.
5175A declaration is considered hiding
5176if it is for a non-overloadable entity, and it declares an entity with the
5177same name as some other entity that is directly or use-visible. The default
5178is that such warnings are not generated.
5179Note that @option{-gnatwa} does not affect the setting of this warning option.
5180
5181@item -gnatwH
5182@emph{Suppress warnings on hiding.}
5183@cindex @option{-gnatwH} (@command{gcc})
5184This switch suppresses warnings on hiding declarations.
5185
5186@item -gnatw.h
5187@emph{Activate warnings on holes/gaps in records.}
5188@cindex @option{-gnatw.h} (@command{gcc})
5189@cindex Record Representation (gaps)
5190This switch activates warnings on component clauses in record
5191representation clauses that leave holes (gaps) in the record layout.
5192If this warning option is active, then record representation clauses
5193should specify a contiguous layout, adding unused fill fields if needed.
5194Note that @option{-gnatwa} does not affect the setting of this warning option.
5195
5196@item -gnatw.H
5197@emph{Suppress warnings on holes/gaps in records.}
5198@cindex @option{-gnatw.H} (@command{gcc})
5199This switch suppresses warnings on component clauses in record
5200representation clauses that leave holes (haps) in the record layout.
5201
5202@item -gnatwi
5203@emph{Activate warnings on implementation units.}
5204@cindex @option{-gnatwi} (@command{gcc})
5205This switch activates warnings for a @code{with} of an internal GNAT
5206implementation unit, defined as any unit from the @code{Ada},
5207@code{Interfaces}, @code{GNAT},
5208^^@code{DEC},^ or @code{System}
5209hierarchies that is not
5210documented in either the Ada Reference Manual or the GNAT
5211Programmer's Reference Manual. Such units are intended only
5212for internal implementation purposes and should not be @code{with}'ed
5213by user programs. The default is that such warnings are generated
5214This warning can also be turned on using @option{-gnatwa}.
5215
5216@item -gnatwI
5217@emph{Disable warnings on implementation units.}
5218@cindex @option{-gnatwI} (@command{gcc})
5219This switch disables warnings for a @code{with} of an internal GNAT
5220implementation unit.
5221
5222@item -gnatw.i
5223@emph{Activate warnings on overlapping actuals.}
5224@cindex @option{-gnatw.i} (@command{gcc})
5225This switch enables a warning on statically detectable overlapping actuals in
5226a subprogram call, when one of the actuals is an in-out parameter, and the
5227types of the actuals are not by-copy types. The warning is off by default,
5228and is not included under -gnatwa.
5229
5230@item -gnatw.I
5231@emph{Disable warnings on overlapping actuals.}
5232@cindex @option{-gnatw.I} (@command{gcc})
5233This switch disables warnings on overlapping actuals in a call..
5234
5235@item -gnatwj
5236@emph{Activate warnings on obsolescent features (Annex J).}
5237@cindex @option{-gnatwj} (@command{gcc})
5238@cindex Features, obsolescent
5239@cindex Obsolescent features
5240If this warning option is activated, then warnings are generated for
5241calls to subprograms marked with @code{pragma Obsolescent} and
5242for use of features in Annex J of the Ada Reference Manual. In the
5243case of Annex J, not all features are flagged. In particular use
5244of the renamed packages (like @code{Text_IO}) and use of package
5245@code{ASCII} are not flagged, since these are very common and
5246would generate many annoying positive warnings. The default is that
5247such warnings are not generated. This warning is also turned on by
5248the use of @option{-gnatwa}.
5249
5250In addition to the above cases, warnings are also generated for
5251GNAT features that have been provided in past versions but which
5252have been superseded (typically by features in the new Ada standard).
5253For example, @code{pragma Ravenscar} will be flagged since its
5254function is replaced by @code{pragma Profile(Ravenscar)}, and
5255@code{pragma Interface_Name} will be flagged since its function
5256is replaced by @code{pragma Import}.
5257
5258Note that this warning option functions differently from the
5259restriction @code{No_Obsolescent_Features} in two respects.
5260First, the restriction applies only to annex J features.
5261Second, the restriction does flag uses of package @code{ASCII}.
5262
5263@item -gnatwJ
5264@emph{Suppress warnings on obsolescent features (Annex J).}
5265@cindex @option{-gnatwJ} (@command{gcc})
5266This switch disables warnings on use of obsolescent features.
5267
5268@item -gnatwk
5269@emph{Activate warnings on variables that could be constants.}
5270@cindex @option{-gnatwk} (@command{gcc})
5271This switch activates warnings for variables that are initialized but
5272never modified, and then could be declared constants. The default is that
5273such warnings are not given.
5274This warning can also be turned on using @option{-gnatwa}.
5275
5276@item -gnatwK
5277@emph{Suppress warnings on variables that could be constants.}
5278@cindex @option{-gnatwK} (@command{gcc})
5279This switch disables warnings on variables that could be declared constants.
5280
5281@item -gnatw.k
5282@emph{Activate warnings on redefinition of names in standard.}
5283@cindex @option{-gnatw.k} (@command{gcc})
5284This switch activates warnings for declarations that declare a name that
5285is defined in package Standard. Such declarations can be confusing,
5286especially since the names in package Standard continue to be directly
5287visible, meaning that use visibiliy on such redeclared names does not
5288work as expected. Names of discriminants and components in records are
5289not included in this check.
5290This warning is not part of the warnings activated by @option{-gnatwa}.
5291It must be explicitly activated.
5292
5293@item -gnatw.K
5294@emph{Suppress warnings on variables that could be constants.}
5295@cindex @option{-gnatwK} (@command{gcc})
5296This switch activates warnings for declarations that declare a name that
5297is defined in package Standard.
5298
5299@item -gnatwl
5300@emph{Activate warnings for elaboration pragmas.}
5301@cindex @option{-gnatwl} (@command{gcc})
5302@cindex Elaboration, warnings
5303This switch activates warnings on missing
5304for possible elaboration problems, including suspicious use
5305of @code{Elaborate} pragmas, when using the static elaboration model, and
5306possible situations that may raise @code{Program_Error} when using the
5307dynamic elaboration model.
5308See the section in this guide on elaboration checking for further details.
5309The default is that such warnings
5310are not generated.
5311This warning is not automatically turned on by the use of @option{-gnatwa}.
5312
5313@item -gnatwL
5314@emph{Suppress warnings for elaboration pragmas.}
5315@cindex @option{-gnatwL} (@command{gcc})
5316This switch suppresses warnings for possible elaboration problems.
5317
5318@item -gnatw.l
5319@emph{List inherited aspects.}
5320@cindex @option{-gnatw.l} (@command{gcc})
5321This switch causes the compiler to list inherited invariants,
5322preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5323Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5324These messages are not automatically turned on by the use of @option{-gnatwa}.
5325
5326@item -gnatw.L
5327@emph{Suppress listing of inherited aspects.}
5328@cindex @option{-gnatw.L} (@command{gcc})
5329This switch suppresses listing of inherited aspects.
5330
5331@item -gnatwm
5332@emph{Activate warnings on modified but unreferenced variables.}
5333@cindex @option{-gnatwm} (@command{gcc})
5334This switch activates warnings for variables that are assigned (using
5335an initialization value or with one or more assignment statements) but
5336whose value is never read. The warning is suppressed for volatile
5337variables and also for variables that are renamings of other variables
5338or for which an address clause is given.
5339This warning can also be turned on using @option{-gnatwa}.
5340The default is that these warnings are not given.
5341
5342@item -gnatwM
5343@emph{Disable warnings on modified but unreferenced variables.}
5344@cindex @option{-gnatwM} (@command{gcc})
5345This switch disables warnings for variables that are assigned or
5346initialized, but never read.
5347
5348@item -gnatw.m
5349@emph{Activate warnings on suspicious modulus values.}
5350@cindex @option{-gnatw.m} (@command{gcc})
5351This switch activates warnings for modulus values that seem suspicious.
5352The cases caught are where the size is the same as the modulus (e.g.
5353a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5354with no size clause. The guess in both cases is that 2**x was intended
5355rather than x. In addition expressions of the form 2*x for small x
5356generate a warning (the almost certainly accurate guess being that
53572**x was intended). The default is that these warnings are given.
5358
5359@item -gnatw.M
5360@emph{Disable warnings on suspicious modulus values.}
5361@cindex @option{-gnatw.M} (@command{gcc})
5362This switch disables warnings for suspicious modulus values.
5363
5364@item -gnatwn
5365@emph{Set normal warnings mode.}
5366@cindex @option{-gnatwn} (@command{gcc})
5367This switch sets normal warning mode, in which enabled warnings are
5368issued and treated as warnings rather than errors. This is the default
5369mode. the switch @option{-gnatwn} can be used to cancel the effect of
5370an explicit @option{-gnatws} or
5371@option{-gnatwe}. It also cancels the effect of the
5372implicit @option{-gnatwe} that is activated by the
5373use of @option{-gnatg}.
5374
5375@item -gnatw.n
5376@emph{Activate warnings on atomic synchronization.}
5377@cindex @option{-gnatw.n} (@command{gcc})
5378@cindex Atomic Synchronization, warnings
5379This switch actives warnings when an access to an atomic variable
5380requires the generation of atomic synchronization code. These
5381warnings are off by default and this warning is not included
5382in @code{-gnatwa}.
5383
5384@item -gnatw.N
5385@emph{Suppress warnings on atomic synchronization.}
5386@cindex @option{-gnatw.n} (@command{gcc})
5387@cindex Atomic Synchronization, warnings
5388This switch suppresses warnings when an access to an atomic variable
5389requires the generation of atomic synchronization code.
5390
5391@item -gnatwo
5392@emph{Activate warnings on address clause overlays.}
5393@cindex @option{-gnatwo} (@command{gcc})
5394@cindex Address Clauses, warnings
5395This switch activates warnings for possibly unintended initialization
5396effects of defining address clauses that cause one variable to overlap
5397another. The default is that such warnings are generated.
5398This warning can also be turned on using @option{-gnatwa}.
5399
5400@item -gnatwO
5401@emph{Suppress warnings on address clause overlays.}
5402@cindex @option{-gnatwO} (@command{gcc})
5403This switch suppresses warnings on possibly unintended initialization
5404effects of defining address clauses that cause one variable to overlap
5405another.
5406
5407@item -gnatw.o
5408@emph{Activate warnings on modified but unreferenced out parameters.}
5409@cindex @option{-gnatw.o} (@command{gcc})
5410This switch activates warnings for variables that are modified by using
5411them as actuals for a call to a procedure with an out mode formal, where
5412the resulting assigned value is never read. It is applicable in the case
5413where there is more than one out mode formal. If there is only one out
5414mode formal, the warning is issued by default (controlled by -gnatwu).
5415The warning is suppressed for volatile
5416variables and also for variables that are renamings of other variables
5417or for which an address clause is given.
5418The default is that these warnings are not given. Note that this warning
5419is not included in -gnatwa, it must be activated explicitly.
5420
5421@item -gnatw.O
5422@emph{Disable warnings on modified but unreferenced out parameters.}
5423@cindex @option{-gnatw.O} (@command{gcc})
5424This switch suppresses warnings for variables that are modified by using
5425them as actuals for a call to a procedure with an out mode formal, where
5426the resulting assigned value is never read.
5427
5428@item -gnatwp
5429@emph{Activate warnings on ineffective pragma Inlines.}
5430@cindex @option{-gnatwp} (@command{gcc})
5431@cindex Inlining, warnings
5432This switch activates warnings for failure of front end inlining
5433(activated by @option{-gnatN}) to inline a particular call. There are
5434many reasons for not being able to inline a call, including most
5435commonly that the call is too complex to inline. The default is
5436that such warnings are not given.
5437This warning can also be turned on using @option{-gnatwa}.
5438Warnings on ineffective inlining by the gcc back-end can be activated
5439separately, using the gcc switch -Winline.
5440
5441@item -gnatwP
5442@emph{Suppress warnings on ineffective pragma Inlines.}
5443@cindex @option{-gnatwP} (@command{gcc})
5444This switch suppresses warnings on ineffective pragma Inlines. If the
5445inlining mechanism cannot inline a call, it will simply ignore the
5446request silently.
5447
5448@item -gnatw.p
5449@emph{Activate warnings on parameter ordering.}
5450@cindex @option{-gnatw.p} (@command{gcc})
5451@cindex Parameter order, warnings
5452This switch activates warnings for cases of suspicious parameter
5453ordering when the list of arguments are all simple identifiers that
5454match the names of the formals, but are in a different order. The
5455warning is suppressed if any use of named parameter notation is used,
5456so this is the appropriate way to suppress a false positive (and
5457serves to emphasize that the "misordering" is deliberate). The
5458default is
5459that such warnings are not given.
5460This warning can also be turned on using @option{-gnatwa}.
5461
5462@item -gnatw.P
5463@emph{Suppress warnings on parameter ordering.}
5464@cindex @option{-gnatw.P} (@command{gcc})
5465This switch suppresses warnings on cases of suspicious parameter
5466ordering.
5467
5468@item -gnatwq
5469@emph{Activate warnings on questionable missing parentheses.}
5470@cindex @option{-gnatwq} (@command{gcc})
5471@cindex Parentheses, warnings
5472This switch activates warnings for cases where parentheses are not used and
5473the result is potential ambiguity from a readers point of view. For example
5474(not a > b) when a and b are modular means ((not a) > b) and very likely the
5475programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5476quite likely ((-x) mod 5) was intended. In such situations it seems best to
5477follow the rule of always parenthesizing to make the association clear, and
5478this warning switch warns if such parentheses are not present. The default
5479is that these warnings are given.
5480This warning can also be turned on using @option{-gnatwa}.
5481
5482@item -gnatwQ
5483@emph{Suppress warnings on questionable missing parentheses.}
5484@cindex @option{-gnatwQ} (@command{gcc})
5485This switch suppresses warnings for cases where the association is not
5486clear and the use of parentheses is preferred.
5487
5488@item -gnatwr
5489@emph{Activate warnings on redundant constructs.}
5490@cindex @option{-gnatwr} (@command{gcc})
5491This switch activates warnings for redundant constructs. The following
5492is the current list of constructs regarded as redundant:
5493
5494@itemize @bullet
5495@item
5496Assignment of an item to itself.
5497@item
5498Type conversion that converts an expression to its own type.
5499@item
5500Use of the attribute @code{Base} where @code{typ'Base} is the same
5501as @code{typ}.
5502@item
5503Use of pragma @code{Pack} when all components are placed by a record
5504representation clause.
5505@item
5506Exception handler containing only a reraise statement (raise with no
5507operand) which has no effect.
5508@item
5509Use of the operator abs on an operand that is known at compile time
5510to be non-negative
5511@item
5512Comparison of boolean expressions to an explicit True value.
5513@end itemize
5514
5515This warning can also be turned on using @option{-gnatwa}.
5516The default is that warnings for redundant constructs are not given.
5517
5518@item -gnatwR
5519@emph{Suppress warnings on redundant constructs.}
5520@cindex @option{-gnatwR} (@command{gcc})
5521This switch suppresses warnings for redundant constructs.
5522
5523@item -gnatw.r
5524@emph{Activate warnings for object renaming function.}
5525@cindex @option{-gnatw.r} (@command{gcc})
5526This switch activates warnings for an object renaming that renames a
5527function call, which is equivalent to a constant declaration (as
5528opposed to renaming the function itself).  The default is that these
5529warnings are given.  This warning can also be turned on using
5530@option{-gnatwa}.
5531
5532@item -gnatw.R
5533@emph{Suppress warnings for object renaming function.}
5534@cindex @option{-gnatwT} (@command{gcc})
5535This switch suppresses warnings for object renaming function.
5536
5537@item -gnatws
5538@emph{Suppress all warnings.}
5539@cindex @option{-gnatws} (@command{gcc})
5540This switch completely suppresses the
5541output of all warning messages from the GNAT front end, including
5542both warnings that can be controlled by switches described in this
5543section, and those that are normally given unconditionally. The
5544effect of this suppress action can only be cancelled by a subsequent
5545use of the switch @option{-gnatwn}.
5546
5547Note that switch @option{-gnatws} does not suppress
5548warnings from the @command{gcc} back end.
5549To suppress these back end warnings as well, use the switch @option{-w}
5550in addition to @option{-gnatws}. Also this switch has no effect on the
5551handling of style check messages.
5552
5553@item -gnatw.s
5554@emph{Activate warnings on overridden size clauses.}
5555@cindex @option{-gnatw.s} (@command{gcc})
5556@cindex Record Representation (component sizes)
5557This switch activates warnings on component clauses in record
5558representation clauses where the length given overrides that
5559specified by an explicit size clause for the component type. A
5560warning is similarly given in the array case if a specified
5561component size overrides an explicit size clause for the array
5562component type.
5563Note that @option{-gnatwa} does not affect the setting of this warning option.
5564
5565@item -gnatw.S
5566@emph{Suppress warnings on overridden size clauses.}
5567@cindex @option{-gnatw.S} (@command{gcc})
5568This switch suppresses warnings on component clauses in record
5569representation clauses that override size clauses, and similar
5570warnings when an array component size overrides a size clause.
5571
5572@item -gnatwt
5573@emph{Activate warnings for tracking of deleted conditional code.}
5574@cindex @option{-gnatwt} (@command{gcc})
5575@cindex Deactivated code, warnings
5576@cindex Deleted code, warnings
5577This switch activates warnings for tracking of code in conditionals (IF and
5578CASE statements) that is detected to be dead code which cannot be executed, and
5579which is removed by the front end. This warning is off by default, and is not
5580turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5581useful for detecting deactivated code in certified applications.
5582
5583@item -gnatwT
5584@emph{Suppress warnings for tracking of deleted conditional code.}
5585@cindex @option{-gnatwT} (@command{gcc})
5586This switch suppresses warnings for tracking of deleted conditional code.
5587
5588@item -gnatw.t
5589@emph{Activate warnings on suspicious contracts.}
5590@cindex @option{-gnatw.t} (@command{gcc})
5591This switch activates warnings on suspicious postconditions (whether a
5592pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5593and suspicious contract cases (pragma @code{Contract_Cases}). A
5594function postcondition or contract case is suspicious when no postcondition
5595or contract case for this function mentions the result of the function.
5596A procedure postcondition or contract case is suspicious when it only
5597refers to the pre-state of the procedure, because in that case it should
5598rather be expressed as a precondition. The default is that such warnings
5599are not generated. This warning can also be turned on using @option{-gnatwa}.
5600
5601@item -gnatw.T
5602@emph{Suppress warnings on suspicious contracts.}
5603@cindex @option{-gnatw.T} (@command{gcc})
5604This switch suppresses warnings on suspicious postconditions.
5605
5606@item -gnatwu
5607@emph{Activate warnings on unused entities.}
5608@cindex @option{-gnatwu} (@command{gcc})
5609This switch activates warnings to be generated for entities that
5610are declared but not referenced, and for units that are @code{with}'ed
5611and not
5612referenced. In the case of packages, a warning is also generated if
5613no entities in the package are referenced. This means that if a with'ed
5614package is referenced but the only references are in @code{use}
5615clauses or @code{renames}
5616declarations, a warning is still generated. A warning is also generated
5617for a generic package that is @code{with}'ed but never instantiated.
5618In the case where a package or subprogram body is compiled, and there
5619is a @code{with} on the corresponding spec
5620that is only referenced in the body,
5621a warning is also generated, noting that the
5622@code{with} can be moved to the body. The default is that
5623such warnings are not generated.
5624This switch also activates warnings on unreferenced formals
5625(it includes the effect of @option{-gnatwf}).
5626This warning can also be turned on using @option{-gnatwa}.
5627
5628@item -gnatwU
5629@emph{Suppress warnings on unused entities.}
5630@cindex @option{-gnatwU} (@command{gcc})
5631This switch suppresses warnings for unused entities and packages.
5632It also turns off warnings on unreferenced formals (and thus includes
5633the effect of @option{-gnatwF}).
5634
5635@item -gnatw.u
5636@emph{Activate warnings on unordered enumeration types.}
5637@cindex @option{-gnatw.u} (@command{gcc})
5638This switch causes enumeration types to be considered as conceptually
5639unordered, unless an explicit pragma @code{Ordered} is given for the type.
5640The effect is to generate warnings in clients that use explicit comparisons
5641or subranges, since these constructs both treat objects of the type as
5642ordered. (A @emph{client} is defined as a unit that is other than the unit in
5643which the type is declared, or its body or subunits.) Please refer to
5644the description of pragma @code{Ordered} in the
5645@cite{@value{EDITION} Reference Manual} for further details.
5646The default is that such warnings are not generated.
5647This warning is not automatically turned on by the use of @option{-gnatwa}.
5648
5649@item -gnatw.U
5650@emph{Deactivate warnings on unordered enumeration types.}
5651@cindex @option{-gnatw.U} (@command{gcc})
5652This switch causes all enumeration types to be considered as ordered, so
5653that no warnings are given for comparisons or subranges for any type.
5654
5655@item -gnatwv
5656@emph{Activate warnings on unassigned variables.}
5657@cindex @option{-gnatwv} (@command{gcc})
5658@cindex Unassigned variable warnings
5659This switch activates warnings for access to variables which
5660may not be properly initialized. The default is that
5661such warnings are generated.
5662This warning can also be turned on using @option{-gnatwa}.
5663
5664@item -gnatwV
5665@emph{Suppress warnings on unassigned variables.}
5666@cindex @option{-gnatwV} (@command{gcc})
5667This switch suppresses warnings for access to variables which
5668may not be properly initialized.
5669For variables of a composite type, the warning can also be suppressed in
5670Ada 2005 by using a default initialization with a box. For example, if
5671Table is an array of records whose components are only partially uninitialized,
5672then the following code:
5673
5674@smallexample @c ada
5675   Tab : Table := (others => <>);
5676@end smallexample
5677
5678will suppress warnings on subsequent statements that access components
5679of variable Tab.
5680
5681@item -gnatw.v
5682@emph{Activate info messages for non-default bit order.}
5683@cindex @option{-gnatw.v} (@command{gcc})
5684@cindex bit order warnings
5685This switch activates messages (labeled "info", they are not warnings,
5686just informational messages) about the effects of non-default bit-order
5687on records to which a component clause is applied. The effect of specifying
5688non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5689these messages, which are given by default, are useful in understanding the
5690exact consequences of using this feature. These messages
5691can also be turned on using @option{-gnatwa}
5692
5693@item -gnatw.V
5694@emph{Suppress info messages for non-default bit order.}
5695@cindex @option{-gnatw.V} (@command{gcc})
5696This switch suppresses information messages for the effects of specifying
5697non-default bit order on record components with component clauses.
5698
5699@item -gnatww
5700@emph{Activate warnings on wrong low bound assumption.}
5701@cindex @option{-gnatww} (@command{gcc})
5702@cindex String indexing warnings
5703This switch activates warnings for indexing an unconstrained string parameter
5704with a literal or S'Length. This is a case where the code is assuming that the
5705low bound is one, which is in general not true (for example when a slice is
5706passed). The default is that such warnings are generated.
5707This warning can also be turned on using @option{-gnatwa}.
5708
5709@item -gnatwW
5710@emph{Suppress warnings on wrong low bound assumption.}
5711@cindex @option{-gnatwW} (@command{gcc})
5712This switch suppresses warnings for indexing an unconstrained string parameter
5713with a literal or S'Length. Note that this warning can also be suppressed
5714in a particular case by adding an
5715assertion that the lower bound is 1,
5716as shown in the following example.
5717
5718@smallexample @c ada
5719   procedure K (S : String) is
5720      pragma Assert (S'First = 1);
5721      @dots{}
5722@end smallexample
5723
5724@item -gnatw.w
5725@emph{Activate warnings on Warnings Off pragmas}
5726@cindex @option{-gnatw.w} (@command{gcc})
5727@cindex Warnings Off control
5728This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5729where either the pragma is entirely useless (because it suppresses no
5730warnings), or it could be replaced by @code{pragma Unreferenced} or
5731@code{pragma Unmodified}. The default is that these warnings are not given.
5732Note that this warning is not included in -gnatwa, it must be
5733activated explicitly. Also activates warnings for the case of
5734Warnings (Off, String), where either there is no matching
5735Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5736
5737@item -gnatw.W
5738@emph{Suppress warnings on unnecessary Warnings Off pragmas}
5739@cindex @option{-gnatw.W} (@command{gcc})
5740This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5741
5742@item -gnatwx
5743@emph{Activate warnings on Export/Import pragmas.}
5744@cindex @option{-gnatwx} (@command{gcc})
5745@cindex Export/Import pragma warnings
5746This switch activates warnings on Export/Import pragmas when
5747the compiler detects a possible conflict between the Ada and
5748foreign language calling sequences. For example, the use of
5749default parameters in a convention C procedure is dubious
5750because the C compiler cannot supply the proper default, so
5751a warning is issued. The default is that such warnings are
5752generated.
5753This warning can also be turned on using @option{-gnatwa}.
5754
5755@item -gnatwX
5756@emph{Suppress warnings on Export/Import pragmas.}
5757@cindex @option{-gnatwX} (@command{gcc})
5758This switch suppresses warnings on Export/Import pragmas.
5759The sense of this is that you are telling the compiler that
5760you know what you are doing in writing the pragma, and it
5761should not complain at you.
5762
5763@item -gnatw.x
5764@emph{Activate warnings for No_Exception_Propagation mode.}
5765@cindex @option{-gnatwm} (@command{gcc})
5766This switch activates warnings for exception usage when pragma Restrictions
5767(No_Exception_Propagation) is in effect. Warnings are given for implicit or
5768explicit exception raises which are not covered by a local handler, and for
5769exception handlers which do not cover a local raise. The default is that these
5770warnings are not given.
5771
5772@item -gnatw.X
5773@emph{Disable warnings for No_Exception_Propagation mode.}
5774This switch disables warnings for exception usage when pragma Restrictions
5775(No_Exception_Propagation) is in effect.
5776
5777@item -gnatwy
5778@emph{Activate warnings for Ada compatibility issues.}
5779@cindex @option{-gnatwy} (@command{gcc})
5780@cindex Ada compatibility issues warnings
5781For the most part, newer versions of Ada are upwards compatible
5782with older versions. For example, Ada 2005 programs will almost
5783always work when compiled as Ada 2012.
5784However there are some exceptions (for example the fact that
5785@code{some} is now a reserved word in Ada 2012). This
5786switch activates several warnings to help in identifying
5787and correcting such incompatibilities. The default is that
5788these warnings are generated. Note that at one point Ada 2005
5789was called Ada 0Y, hence the choice of character.
5790This warning can also be turned on using @option{-gnatwa}.
5791
5792@item -gnatwY
5793@emph{Disable warnings for Ada compatibility issues.}
5794@cindex @option{-gnatwY} (@command{gcc})
5795@cindex Ada compatibility issues warnings
5796This switch suppresses the warnings intended to help in identifying
5797incompatibilities between Ada language versions.
5798
5799@item -gnatw.y
5800@emph{Activate information messages for why package spec needs body}
5801@cindex @option{-gnatw.y} (@command{gcc})
5802@cindex Package spec needing body
5803There are a number of cases in which a package spec needs a body.
5804For example, the use of pragma Elaborate_Body, or the declaration
5805of a procedure specification requiring a completion. This switch
5806causes information messages to be output showing why a package
5807specification requires a body. This can be useful in the case of
5808a large package specification which is unexpectedly requiring a
5809body. The default is that such information messages are not output.
5810
5811@item -gnatw.Y
5812@emph{Disable information messages for why package spec needs body}
5813@cindex @option{-gnatw.Y} (@command{gcc})
5814@cindex No information messages for why package spec needs body
5815This switch suppresses the output of information messages showing why
5816a package specification needs a body.
5817
5818@item -gnatwz
5819@emph{Activate warnings on unchecked conversions.}
5820@cindex @option{-gnatwz} (@command{gcc})
5821@cindex Unchecked_Conversion warnings
5822This switch activates warnings for unchecked conversions
5823where the types are known at compile time to have different
5824sizes. The default
5825is that such warnings are generated. Warnings are also
5826generated for subprogram pointers with different conventions,
5827and, on VMS only, for data pointers with different conventions.
5828This warning can also be turned on using @option{-gnatwa}.
5829
5830@item -gnatwZ
5831@emph{Suppress warnings on unchecked conversions.}
5832@cindex @option{-gnatwZ} (@command{gcc})
5833This switch suppresses warnings for unchecked conversions
5834where the types are known at compile time to have different
5835sizes or conventions.
5836
5837@item ^-Wunused^WARNINGS=UNUSED^
5838@cindex @option{-Wunused}
5839The warnings controlled by the @option{-gnatw} switch are generated by
5840the front end of the compiler. The @option{GCC} back end can provide
5841additional warnings and they are controlled by the @option{-W} switch.
5842For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5843warnings for entities that are declared but not referenced.
5844
5845@item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5846@cindex @option{-Wuninitialized}
5847Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5848the back end warning for uninitialized variables. This switch must be
5849used in conjunction with an optimization level greater than zero.
5850
5851@item -Wstack-usage=@var{len}
5852@cindex @option{-Wstack-usage}
5853Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5854See @ref{Static Stack Usage Analysis} for details.
5855
5856@item ^-Wall^/ALL_BACK_END_WARNINGS^
5857@cindex @option{-Wall}
5858This switch enables most warnings from the @option{GCC} back end.
5859The code generator detects a number of warning situations that are missed
5860by the @option{GNAT} front end, and this switch can be used to activate them.
5861The use of this switch also sets the default front end warning mode to
5862@option{-gnatwa}, that is, most front end warnings activated as well.
5863
5864@item ^-w^/NO_BACK_END_WARNINGS^
5865@cindex @option{-w}
5866Conversely, this switch suppresses warnings from the @option{GCC} back end.
5867The use of this switch also sets the default front end warning mode to
5868@option{-gnatws}, that is, front end warnings suppressed as well.
5869
5870@end table
5871
5872@noindent
5873@ifclear vms
5874A string of warning parameters can be used in the same parameter. For example:
5875
5876@smallexample
5877-gnatwaGe
5878@end smallexample
5879
5880@noindent
5881will turn on all optional warnings except for unrecognized pragma warnings,
5882and also specify that warnings should be treated as errors.
5883@end ifclear
5884
5885When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5886
5887@table @option
5888@c !sort!
5889@item -gnatw.a
5890@item -gnatwB
5891@item -gnatw.b
5892@item -gnatwC
5893@item -gnatw.C
5894@item -gnatwD
5895@item -gnatwF
5896@item -gnatwg
5897@item -gnatwH
5898@item -gnatwi
5899@item -gnatw.I
5900@item -gnatwJ
5901@item -gnatwK
5902@item -gnatwL
5903@item -gnatw.L
5904@item -gnatwM
5905@item -gnatw.m
5906@item -gnatwn
5907@item -gnatwo
5908@item -gnatw.O
5909@item -gnatwP
5910@item -gnatw.P
5911@item -gnatwq
5912@item -gnatwR
5913@item -gnatw.R
5914@item -gnatw.S
5915@item -gnatwT
5916@item -gnatw.T
5917@item -gnatwU
5918@item -gnatwv
5919@item -gnatww
5920@item -gnatw.W
5921@item -gnatwx
5922@item -gnatw.X
5923@item -gnatwy
5924@item -gnatwz
5925
5926@end table
5927
5928@node Debugging and Assertion Control
5929@subsection Debugging and Assertion Control
5930
5931@table @option
5932@item -gnata
5933@cindex @option{-gnata} (@command{gcc})
5934@findex Assert
5935@findex Debug
5936@cindex Assertions
5937
5938@noindent
5939The pragmas @code{Assert} and @code{Debug} normally have no effect and
5940are ignored. This switch, where @samp{a} stands for assert, causes
5941@code{Assert} and @code{Debug} pragmas to be activated.
5942
5943The pragmas have the form:
5944
5945@smallexample
5946@cartouche
5947   @b{pragma} Assert (@var{Boolean-expression} @r{[},
5948                      @var{static-string-expression}@r{]})
5949   @b{pragma} Debug (@var{procedure call})
5950@end cartouche
5951@end smallexample
5952
5953@noindent
5954The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5955If the result is @code{True}, the pragma has no effect (other than
5956possible side effects from evaluating the expression). If the result is
5957@code{False}, the exception @code{Assert_Failure} declared in the package
5958@code{System.Assertions} is
5959raised (passing @var{static-string-expression}, if present, as the
5960message associated with the exception). If no string expression is
5961given the default is a string giving the file name and line number
5962of the pragma.
5963
5964The @code{Debug} pragma causes @var{procedure} to be called. Note that
5965@code{pragma Debug} may appear within a declaration sequence, allowing
5966debugging procedures to be called between declarations.
5967
5968@ifset vms
5969@item /DEBUG@r{[}=debug-level@r{]}
5970@itemx  /NODEBUG
5971Specifies how much debugging information is to be included in
5972the resulting object file where 'debug-level' is one of the following:
5973@table @code
5974@item   TRACEBACK
5975Include both debugger symbol records and traceback
5976the object file.
5977This is the default setting.
5978@item   ALL
5979Include both debugger symbol records and traceback in
5980object file.
5981@item   NONE
5982Excludes both debugger symbol records and traceback
5983the object file. Same as /NODEBUG.
5984@item   SYMBOLS
5985Includes only debugger symbol records in the object
5986file. Note that this doesn't include traceback information.
5987@end table
5988@end ifset
5989@end table
5990
5991@node Validity Checking
5992@subsection Validity Checking
5993@findex Validity Checking
5994
5995@noindent
5996The Ada Reference Manual defines the concept of invalid values (see
5997RM 13.9.1). The primary source of invalid values is uninitialized
5998variables. A scalar variable that is left uninitialized may contain
5999an invalid value; the concept of invalid does not apply to access or
6000composite types.
6001
6002It is an error to read an invalid value, but the RM does not require
6003run-time checks to detect such errors, except for some minimal
6004checking to prevent erroneous execution (i.e. unpredictable
6005behavior). This corresponds to the @option{-gnatVd} switch below,
6006which is the default. For example, by default, if the expression of a
6007case statement is invalid, it will raise Constraint_Error rather than
6008causing a wild jump, and if an array index on the left-hand side of an
6009assignment is invalid, it will raise Constraint_Error rather than
6010overwriting an arbitrary memory location.
6011
6012The @option{-gnatVa} may be used to enable additional validity checks,
6013which are not required by the RM. These checks are often very
6014expensive (which is why the RM does not require them). These checks
6015are useful in tracking down uninitialized variables, but they are
6016not usually recommended for production builds.
6017
6018The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6019control; you can enable whichever validity checks you desire. However,
6020for most debugging purposes, @option{-gnatVa} is sufficient, and the
6021default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6022sufficient for non-debugging use.
6023
6024The @option{-gnatB} switch tells the compiler to assume that all
6025values are valid (that is, within their declared subtype range)
6026except in the context of a use of the Valid attribute. This means
6027the compiler can generate more efficient code, since the range
6028of values is better known at compile time. However, an uninitialized
6029variable can cause wild jumps and memory corruption in this mode.
6030
6031The @option{-gnatV^@var{x}^^} switch allows control over the validity
6032checking mode as described below.
6033@ifclear vms
6034The @code{x} argument is a string of letters that
6035indicate validity checks that are performed or not performed in addition
6036to the default checks required by Ada as described above.
6037@end ifclear
6038@ifset vms
6039The options allowed for this qualifier
6040indicate validity checks that are performed or not performed in addition
6041to the default checks required by Ada as described above.
6042@end ifset
6043
6044@table @option
6045@c !sort!
6046@item -gnatVa
6047@emph{All validity checks.}
6048@cindex @option{-gnatVa} (@command{gcc})
6049All validity checks are turned on.
6050@ifclear vms
6051That is, @option{-gnatVa} is
6052equivalent to @option{gnatVcdfimorst}.
6053@end ifclear
6054
6055@item -gnatVc
6056@emph{Validity checks for copies.}
6057@cindex @option{-gnatVc} (@command{gcc})
6058The right hand side of assignments, and the initializing values of
6059object declarations are validity checked.
6060
6061@item -gnatVd
6062@emph{Default (RM) validity checks.}
6063@cindex @option{-gnatVd} (@command{gcc})
6064Some validity checks are done by default following normal Ada semantics
6065(RM 13.9.1 (9-11)).
6066A check is done in case statements that the expression is within the range
6067of the subtype. If it is not, Constraint_Error is raised.
6068For assignments to array components, a check is done that the expression used
6069as index is within the range. If it is not, Constraint_Error is raised.
6070Both these validity checks may be turned off using switch @option{-gnatVD}.
6071They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6072switch @option{-gnatVd} will leave the checks turned on.
6073Switch @option{-gnatVD} should be used only if you are sure that all such
6074expressions have valid values. If you use this switch and invalid values
6075are present, then the program is erroneous, and wild jumps or memory
6076overwriting may occur.
6077
6078@item -gnatVe
6079@emph{Validity checks for elementary components.}
6080@cindex @option{-gnatVe} (@command{gcc})
6081In the absence of this switch, assignments to record or array components are
6082not validity checked, even if validity checks for assignments generally
6083(@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6084require valid data, but assignment of individual components does. So for
6085example, there is a difference between copying the elements of an array with a
6086slice assignment, compared to assigning element by element in a loop. This
6087switch allows you to turn off validity checking for components, even when they
6088are assigned component by component.
6089
6090@item -gnatVf
6091@emph{Validity checks for floating-point values.}
6092@cindex @option{-gnatVf} (@command{gcc})
6093In the absence of this switch, validity checking occurs only for discrete
6094values. If @option{-gnatVf} is specified, then validity checking also applies
6095for floating-point values, and NaNs and infinities are considered invalid,
6096as well as out of range values for constrained types. Note that this means
6097that standard IEEE infinity mode is not allowed. The exact contexts
6098in which floating-point values are checked depends on the setting of other
6099options. For example,
6100@option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6101@option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6102(the order does not matter) specifies that floating-point parameters of mode
6103@code{in} should be validity checked.
6104
6105@item -gnatVi
6106@emph{Validity checks for @code{in} mode parameters}
6107@cindex @option{-gnatVi} (@command{gcc})
6108Arguments for parameters of mode @code{in} are validity checked in function
6109and procedure calls at the point of call.
6110
6111@item -gnatVm
6112@emph{Validity checks for @code{in out} mode parameters.}
6113@cindex @option{-gnatVm} (@command{gcc})
6114Arguments for parameters of mode @code{in out} are validity checked in
6115procedure calls at the point of call. The @code{'m'} here stands for
6116modify, since this concerns parameters that can be modified by the call.
6117Note that there is no specific option to test @code{out} parameters,
6118but any reference within the subprogram will be tested in the usual
6119manner, and if an invalid value is copied back, any reference to it
6120will be subject to validity checking.
6121
6122@item -gnatVn
6123@emph{No validity checks.}
6124@cindex @option{-gnatVn} (@command{gcc})
6125This switch turns off all validity checking, including the default checking
6126for case statements and left hand side subscripts. Note that the use of
6127the switch @option{-gnatp} suppresses all run-time checks, including
6128validity checks, and thus implies @option{-gnatVn}. When this switch
6129is used, it cancels any other @option{-gnatV} previously issued.
6130
6131@item -gnatVo
6132@emph{Validity checks for operator and attribute operands.}
6133@cindex @option{-gnatVo} (@command{gcc})
6134Arguments for predefined operators and attributes are validity checked.
6135This includes all operators in package @code{Standard},
6136the shift operators defined as intrinsic in package @code{Interfaces}
6137and operands for attributes such as @code{Pos}. Checks are also made
6138on individual component values for composite comparisons, and on the
6139expressions in type conversions and qualified expressions. Checks are
6140also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6141
6142@item -gnatVp
6143@emph{Validity checks for parameters.}
6144@cindex @option{-gnatVp} (@command{gcc})
6145This controls the treatment of parameters within a subprogram (as opposed
6146to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6147of parameters on a call. If either of these call options is used, then
6148normally an assumption is made within a subprogram that the input arguments
6149have been validity checking at the point of call, and do not need checking
6150again within a subprogram). If @option{-gnatVp} is set, then this assumption
6151is not made, and parameters are not assumed to be valid, so their validity
6152will be checked (or rechecked) within the subprogram.
6153
6154@item -gnatVr
6155@emph{Validity checks for function returns.}
6156@cindex @option{-gnatVr} (@command{gcc})
6157The expression in @code{return} statements in functions is validity
6158checked.
6159
6160@item -gnatVs
6161@emph{Validity checks for subscripts.}
6162@cindex @option{-gnatVs} (@command{gcc})
6163All subscripts expressions are checked for validity, whether they appear
6164on the right side or left side (in default mode only left side subscripts
6165are validity checked).
6166
6167@item -gnatVt
6168@emph{Validity checks for tests.}
6169@cindex @option{-gnatVt} (@command{gcc})
6170Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6171statements are checked, as well as guard expressions in entry calls.
6172
6173@end table
6174
6175@noindent
6176The @option{-gnatV} switch may be followed by
6177^a string of letters^a list of options^
6178to turn on a series of validity checking options.
6179For example,
6180@option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6181specifies that in addition to the default validity checking, copies and
6182function return expressions are to be validity checked.
6183In order to make it easier
6184to specify the desired combination of effects,
6185@ifclear vms
6186the upper case letters @code{CDFIMORST} may
6187be used to turn off the corresponding lower case option.
6188@end ifclear
6189@ifset vms
6190the prefix @code{NO} on an option turns off the corresponding validity
6191checking:
6192@itemize @bullet
6193@item @code{NOCOPIES}
6194@item @code{NODEFAULT}
6195@item @code{NOFLOATS}
6196@item @code{NOIN_PARAMS}
6197@item @code{NOMOD_PARAMS}
6198@item @code{NOOPERANDS}
6199@item @code{NORETURNS}
6200@item @code{NOSUBSCRIPTS}
6201@item @code{NOTESTS}
6202@end itemize
6203@end ifset
6204Thus
6205@option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6206turns on all validity checking options except for
6207checking of @code{@b{in out}} procedure arguments.
6208
6209The specification of additional validity checking generates extra code (and
6210in the case of @option{-gnatVa} the code expansion can be substantial).
6211However, these additional checks can be very useful in detecting
6212uninitialized variables, incorrect use of unchecked conversion, and other
6213errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6214is useful in conjunction with the extra validity checking, since this
6215ensures that wherever possible uninitialized variables have invalid values.
6216
6217See also the pragma @code{Validity_Checks} which allows modification of
6218the validity checking mode at the program source level, and also allows for
6219temporary disabling of validity checks.
6220
6221@node Style Checking
6222@subsection Style Checking
6223@findex Style checking
6224
6225@noindent
6226The @option{-gnaty^x^(option,option,@dots{})^} switch
6227@cindex @option{-gnaty} (@command{gcc})
6228causes the compiler to
6229enforce specified style rules. A limited set of style rules has been used
6230in writing the GNAT sources themselves. This switch allows user programs
6231to activate all or some of these checks. If the source program fails a
6232specified style check, an appropriate message is given, preceded by
6233the character sequence ``(style)''. This message does not prevent
6234successful compilation (unless the @option{-gnatwe} switch is used).
6235
6236Note that this is by no means intended to be a general facility for
6237checking arbitrary coding standards. It is simply an embedding of the
6238style rules we have chosen for the GNAT sources. If you are starting
6239a project which does not have established style standards, you may
6240find it useful to adopt the entire set of GNAT coding standards, or
6241some subset of them.
6242@ifclear FSFEDITION
6243If you already have an established set of coding
6244standards, then the selected style checking options may
6245indeed correspond to choices you have made, but for general checking
6246of an existing set of coding rules, you should look to the gnatcheck
6247tool, which is designed for that purpose.
6248@end ifclear
6249
6250@ifset vms
6251@code{(option,option,@dots{})} is a sequence of keywords
6252@end ifset
6253@ifclear vms
6254The string @var{x} is a sequence of letters or digits
6255@end ifclear
6256indicating the particular style
6257checks to be performed. The following checks are defined:
6258
6259@table @option
6260@c !sort!
6261@item 0-9
6262@emph{Specify indentation level.}
6263If a digit from 1-9 appears
6264^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6265then proper indentation is checked, with the digit indicating the
6266indentation level required. A value of zero turns off this style check.
6267The general style of required indentation is as specified by
6268the examples in the Ada Reference Manual. Full line comments must be
6269aligned with the @code{--} starting on a column that is a multiple of
6270the alignment level, or they may be aligned the same way as the following
6271non-blank line (this is useful when full line comments appear in the middle
6272of a statement, or they may be aligned with the source line on the previous
6273non-blank line.
6274
6275@item ^a^ATTRIBUTE^
6276@emph{Check attribute casing.}
6277Attribute names, including the case of keywords such as @code{digits}
6278used as attributes names, must be written in mixed case, that is, the
6279initial letter and any letter following an underscore must be uppercase.
6280All other letters must be lowercase.
6281
6282@item ^A^ARRAY_INDEXES^
6283@emph{Use of array index numbers in array attributes.}
6284When using the array attributes First, Last, Range,
6285or Length, the index number must be omitted for one-dimensional arrays
6286and is required for multi-dimensional arrays.
6287
6288@item ^b^BLANKS^
6289@emph{Blanks not allowed at statement end.}
6290Trailing blanks are not allowed at the end of statements. The purpose of this
6291rule, together with h (no horizontal tabs), is to enforce a canonical format
6292for the use of blanks to separate source tokens.
6293
6294@item ^B^BOOLEAN_OPERATORS^
6295@emph{Check Boolean operators.}
6296The use of AND/OR operators is not permitted except in the cases of modular
6297operands, array operands, and simple stand-alone boolean variables or
6298boolean constants. In all other cases @code{and then}/@code{or else} are
6299required.
6300
6301@item ^c^COMMENTS^
6302@emph{Check comments, double space.}
6303Comments must meet the following set of rules:
6304
6305@itemize @bullet
6306
6307@item
6308The ``@code{--}'' that starts the column must either start in column one,
6309or else at least one blank must precede this sequence.
6310
6311@item
6312Comments that follow other tokens on a line must have at least one blank
6313following the ``@code{--}'' at the start of the comment.
6314
6315@item
6316Full line comments must have at least two blanks following the
6317``@code{--}'' that starts the comment, with the following exceptions.
6318
6319@item
6320A line consisting only of the ``@code{--}'' characters, possibly preceded
6321by blanks is permitted.
6322
6323@item
6324A comment starting with ``@code{--x}'' where @code{x} is a special character
6325is permitted.
6326This allows proper processing of the output generated by specialized tools
6327including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6328annotation
6329language (where ``@code{--#}'' is used). For the purposes of this rule, a
6330special character is defined as being in one of the ASCII ranges
6331@code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6332Note that this usage is not permitted
6333in GNAT implementation units (i.e., when @option{-gnatg} is used).
6334
6335@item
6336A line consisting entirely of minus signs, possibly preceded by blanks, is
6337permitted. This allows the construction of box comments where lines of minus
6338signs are used to form the top and bottom of the box.
6339
6340@item
6341A comment that starts and ends with ``@code{--}'' is permitted as long as at
6342least one blank follows the initial ``@code{--}''. Together with the preceding
6343rule, this allows the construction of box comments, as shown in the following
6344example:
6345@smallexample
6346---------------------------
6347-- This is a box comment --
6348-- with two text lines.  --
6349---------------------------
6350@end smallexample
6351@end itemize
6352
6353@item ^C^COMMENTS1^
6354@emph{Check comments, single space.}
6355This is identical to @code{^c^COMMENTS^} except that only one space
6356is required following the @code{--} of a comment instead of two.
6357
6358@item ^d^DOS_LINE_ENDINGS^
6359@emph{Check no DOS line terminators present.}
6360All lines must be terminated by a single ASCII.LF
6361character (in particular the DOS line terminator sequence CR/LF is not
6362allowed).
6363
6364@item ^e^END^
6365@emph{Check end/exit labels.}
6366Optional labels on @code{end} statements ending subprograms and on
6367@code{exit} statements exiting named loops, are required to be present.
6368
6369@item ^f^VTABS^
6370@emph{No form feeds or vertical tabs.}
6371Neither form feeds nor vertical tab characters are permitted
6372in the source text.
6373
6374@item ^g^GNAT^
6375@emph{GNAT style mode.}
6376The set of style check switches is set to match that used by the GNAT sources.
6377This may be useful when developing code that is eventually intended to be
6378incorporated into GNAT. For further details, see GNAT sources.
6379
6380@item ^h^HTABS^
6381@emph{No horizontal tabs.}
6382Horizontal tab characters are not permitted in the source text.
6383Together with the b (no blanks at end of line) check, this
6384enforces a canonical form for the use of blanks to separate
6385source tokens.
6386
6387@item ^i^IF_THEN^
6388@emph{Check if-then layout.}
6389The keyword @code{then} must appear either on the same
6390line as corresponding @code{if}, or on a line on its own, lined
6391up under the @code{if}.
6392
6393@item ^I^IN_MODE^
6394@emph{check mode IN keywords.}
6395Mode @code{in} (the default mode) is not
6396allowed to be given explicitly. @code{in out} is fine,
6397but not @code{in} on its own.
6398
6399@item ^k^KEYWORD^
6400@emph{Check keyword casing.}
6401All keywords must be in lower case (with the exception of keywords
6402such as @code{digits} used as attribute names to which this check
6403does not apply).
6404
6405@item ^l^LAYOUT^
6406@emph{Check layout.}
6407Layout of statement and declaration constructs must follow the
6408recommendations in the Ada Reference Manual, as indicated by the
6409form of the syntax rules. For example an @code{else} keyword must
6410be lined up with the corresponding @code{if} keyword.
6411
6412There are two respects in which the style rule enforced by this check
6413option are more liberal than those in the Ada Reference Manual. First
6414in the case of record declarations, it is permissible to put the
6415@code{record} keyword on the same line as the @code{type} keyword, and
6416then the @code{end} in @code{end record} must line up under @code{type}.
6417This is also permitted when the type declaration is split on two lines.
6418For example, any of the following three layouts is acceptable:
6419
6420@smallexample @c ada
6421@cartouche
6422type q is record
6423   a : integer;
6424   b : integer;
6425end record;
6426
6427type q is
6428   record
6429      a : integer;
6430      b : integer;
6431   end record;
6432
6433type q is
6434   record
6435      a : integer;
6436      b : integer;
6437end record;
6438
6439@end cartouche
6440@end smallexample
6441
6442@noindent
6443Second, in the case of a block statement, a permitted alternative
6444is to put the block label on the same line as the @code{declare} or
6445@code{begin} keyword, and then line the @code{end} keyword up under
6446the block label. For example both the following are permitted:
6447
6448@smallexample @c ada
6449@cartouche
6450Block : declare
6451   A : Integer := 3;
6452begin
6453   Proc (A, A);
6454end Block;
6455
6456Block :
6457   declare
6458      A : Integer := 3;
6459   begin
6460      Proc (A, A);
6461   end Block;
6462@end cartouche
6463@end smallexample
6464
6465@noindent
6466The same alternative format is allowed for loops. For example, both of
6467the following are permitted:
6468
6469@smallexample @c ada
6470@cartouche
6471Clear : while J < 10 loop
6472   A (J) := 0;
6473end loop Clear;
6474
6475Clear :
6476   while J < 10 loop
6477      A (J) := 0;
6478   end loop Clear;
6479@end cartouche
6480@end smallexample
6481
6482@item ^Lnnn^MAX_NESTING=nnn^
6483@emph{Set maximum nesting level.}
6484The maximum level of nesting of constructs (including subprograms, loops,
6485blocks, packages, and conditionals) may not exceed the given value
6486@option{nnn}. A value of zero disconnects this style check.
6487
6488@item ^m^LINE_LENGTH^
6489@emph{Check maximum line length.}
6490The length of source lines must not exceed 79 characters, including
6491any trailing blanks. The value of 79 allows convenient display on an
649280 character wide device or window, allowing for possible special
6493treatment of 80 character lines. Note that this count is of
6494characters in the source text. This means that a tab character counts
6495as one character in this count and a wide character sequence counts as
6496a single character (however many bytes are needed in the encoding).
6497
6498@item ^Mnnn^MAX_LENGTH=nnn^
6499@emph{Set maximum line length.}
6500The length of lines must not exceed the
6501given value @option{nnn}. The maximum value that can be specified is 32767.
6502If neither style option for setting the line length is used, then the
6503default is 255. This also controls the maximum length of lexical elements,
6504where the only restriction is that they must fit on a single line.
6505
6506@item ^n^STANDARD_CASING^
6507@emph{Check casing of entities in Standard.}
6508Any identifier from Standard must be cased
6509to match the presentation in the Ada Reference Manual (for example,
6510@code{Integer} and @code{ASCII.NUL}).
6511
6512@item ^N^NONE^
6513@emph{Turn off all style checks.}
6514All style check options are turned off.
6515
6516@item ^o^ORDERED_SUBPROGRAMS^
6517@emph{Check order of subprogram bodies.}
6518All subprogram bodies in a given scope
6519(e.g.@: a package body) must be in alphabetical order. The ordering
6520rule uses normal Ada rules for comparing strings, ignoring casing
6521of letters, except that if there is a trailing numeric suffix, then
6522the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6523before Junk10).
6524
6525@item ^O^OVERRIDING_INDICATORS^
6526@emph{Check that overriding subprograms are explicitly marked as such.}
6527The declaration of a primitive operation of a type extension that overrides
6528an inherited operation must carry an overriding indicator.
6529
6530@item ^p^PRAGMA^
6531@emph{Check pragma casing.}
6532Pragma names must be written in mixed case, that is, the
6533initial letter and any letter following an underscore must be uppercase.
6534All other letters must be lowercase. An exception is that SPARK_Mode is
6535allowed as an alternative for Spark_Mode.
6536
6537@item ^r^REFERENCES^
6538@emph{Check references.}
6539All identifier references must be cased in the same way as the
6540corresponding declaration. No specific casing style is imposed on
6541identifiers. The only requirement is for consistency of references
6542with declarations.
6543
6544@item ^s^SPECS^
6545@emph{Check separate specs.}
6546Separate declarations (``specs'') are required for subprograms (a
6547body is not allowed to serve as its own declaration). The only
6548exception is that parameterless library level procedures are
6549not required to have a separate declaration. This exception covers
6550the most frequent form of main program procedures.
6551
6552@item ^S^STATEMENTS_AFTER_THEN_ELSE^
6553@emph{Check no statements after @code{then}/@code{else}.}
6554No statements are allowed
6555on the same line as a @code{then} or @code{else} keyword following the
6556keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6557affected, and a special exception allows a pragma to appear after @code{else}.
6558
6559@item ^t^TOKEN^
6560@emph{Check token spacing.}
6561The following token spacing rules are enforced:
6562
6563@itemize @bullet
6564
6565@item
6566The keywords @code{abs} and @code{not} must be followed by a space.
6567
6568@item
6569The token @code{=>} must be surrounded by spaces.
6570
6571@item
6572The token @code{<>} must be preceded by a space or a left parenthesis.
6573
6574@item
6575Binary operators other than @code{**} must be surrounded by spaces.
6576There is no restriction on the layout of the @code{**} binary operator.
6577
6578@item
6579Colon must be surrounded by spaces.
6580
6581@item
6582Colon-equal (assignment, initialization) must be surrounded by spaces.
6583
6584@item
6585Comma must be the first non-blank character on the line, or be
6586immediately preceded by a non-blank character, and must be followed
6587by a space.
6588
6589@item
6590If the token preceding a left parenthesis ends with a letter or digit, then
6591a space must separate the two tokens.
6592
6593@item
6594if the token following a right parenthesis starts with a letter or digit, then
6595a space must separate the two tokens.
6596
6597@item
6598A right parenthesis must either be the first non-blank character on
6599a line, or it must be preceded by a non-blank character.
6600
6601@item
6602A semicolon must not be preceded by a space, and must not be followed by
6603a non-blank character.
6604
6605@item
6606A unary plus or minus may not be followed by a space.
6607
6608@item
6609A vertical bar must be surrounded by spaces.
6610@end itemize
6611
6612@item
6613Exactly one blank (and no other white space) must appear between
6614a @code{not} token and a following @code{in} token.
6615
6616@item ^u^UNNECESSARY_BLANK_LINES^
6617@emph{Check unnecessary blank lines.}
6618Unnecessary blank lines are not allowed. A blank line is considered
6619unnecessary if it appears at the end of the file, or if more than
6620one blank line occurs in sequence.
6621
6622@item ^x^XTRA_PARENS^
6623@emph{Check extra parentheses.}
6624Unnecessary extra level of parentheses (C-style) are not allowed
6625around conditions in @code{if} statements, @code{while} statements and
6626@code{exit} statements.
6627
6628@item ^y^ALL_BUILTIN^
6629@emph{Set all standard style check options}
6630This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6631options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6632@option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6633@option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6634
6635@ifclear vms
6636@item -
6637@emph{Remove style check options}
6638This causes any subsequent options in the string to act as canceling the
6639corresponding style check option. To cancel maximum nesting level control,
6640use @option{L} parameter witout any integer value after that, because any
6641digit following @option{-} in the parameter string of the @option{-gnaty}
6642option will be threated as canceling indentation check. The same is true
6643for @option{M} parameter. @option{y} and @option{N} parameters are not
6644allowed after @option{-}.
6645
6646@item +
6647This causes any subsequent options in the string to enable the corresponding
6648style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6649if any.
6650@end ifclear
6651
6652@ifset vms
6653@item NOxxx
6654@emph{Removing style check options}
6655If the name of a style check is preceded by @option{NO} then the corresponding
6656style check is turned off. For example @option{NOCOMMENTS} turns off style
6657checking for comments.
6658@end ifset
6659@end table
6660
6661@noindent
6662In the above rules, appearing in column one is always permitted, that is,
6663counts as meeting either a requirement for a required preceding space,
6664or as meeting a requirement for no preceding space.
6665
6666Appearing at the end of a line is also always permitted, that is, counts
6667as meeting either a requirement for a following space, or as meeting
6668a requirement for no following space.
6669
6670@noindent
6671If any of these style rules is violated, a message is generated giving
6672details on the violation. The initial characters of such messages are
6673always ``@code{(style)}''. Note that these messages are treated as warning
6674messages, so they normally do not prevent the generation of an object
6675file. The @option{-gnatwe} switch can be used to treat warning messages,
6676including style messages, as fatal errors.
6677
6678The switch
6679@ifclear vms
6680@option{-gnaty} on its own (that is not
6681followed by any letters or digits) is equivalent
6682to the use of @option{-gnatyy} as described above, that is all
6683built-in standard style check options are enabled.
6684
6685@end ifclear
6686@ifset vms
6687/STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6688the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6689XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6690@end ifset
6691
6692The switch
6693@ifclear vms
6694@option{-gnatyN}
6695@end ifclear
6696@ifset vms
6697/STYLE_CHECKS=NONE
6698@end ifset
6699clears any previously set style checks.
6700
6701@node Run-Time Checks
6702@subsection Run-Time Checks
6703@cindex Division by zero
6704@cindex Access before elaboration
6705@cindex Checks, division by zero
6706@cindex Checks, access before elaboration
6707@cindex Checks, stack overflow checking
6708
6709@noindent
6710By default, the following checks are suppressed: integer overflow
6711checks, stack overflow checks, and checks for access before
6712elaboration on subprogram calls. All other checks, including range
6713checks and array bounds checks, are turned on by default. The
6714following @command{gcc} switches refine this default behavior.
6715
6716@table @option
6717@c !sort!
6718@item -gnatp
6719@cindex @option{-gnatp} (@command{gcc})
6720@cindex Suppressing checks
6721@cindex Checks, suppressing
6722@findex Suppress
6723This switch causes the unit to be compiled
6724as though @code{pragma Suppress (All_checks)}
6725had been present in the source. Validity checks are also eliminated (in
6726other words @option{-gnatp} also implies @option{-gnatVn}.
6727Use this switch to improve the performance
6728of the code at the expense of safety in the presence of invalid data or
6729program bugs.
6730
6731Note that when checks are suppressed, the compiler is allowed, but not
6732required, to omit the checking code. If the run-time cost of the
6733checking code is zero or near-zero, the compiler will generate it even
6734if checks are suppressed. In particular, if the compiler can prove
6735that a certain check will necessarily fail, it will generate code to
6736do an unconditional ``raise'', even if checks are suppressed. The
6737compiler warns in this case. Another case in which checks may not be
6738eliminated is when they are embedded in certain run time routines such
6739as math library routines.
6740
6741Of course, run-time checks are omitted whenever the compiler can prove
6742that they will not fail, whether or not checks are suppressed.
6743
6744Note that if you suppress a check that would have failed, program
6745execution is erroneous, which means the behavior is totally
6746unpredictable. The program might crash, or print wrong answers, or
6747do anything else. It might even do exactly what you wanted it to do
6748(and then it might start failing mysteriously next week or next
6749year). The compiler will generate code based on the assumption that
6750the condition being checked is true, which can result in disaster if
6751that assumption is wrong.
6752
6753The checks subject to suppression include all the checks defined by
6754the Ada standard, the additional implementation defined checks
6755@code{Alignment_Check}, @code{Atomic_Synchronization}, and
6756@code{Validity_Check}, as well as any checks introduced using
6757@code{pragma Check_Name}.
6758
6759The @option{-gnatp} switch has no effect if a subsequent
6760@option{-gnat-p} switch appears.
6761
6762@item -gnat-p
6763@cindex @option{-gnat-p} (@command{gcc})
6764@cindex Suppressing checks
6765@cindex Checks, suppressing
6766@findex Suppress
6767This switch cancels the effect of a previous @option{gnatp} switch.
6768
6769@item -gnato??
6770@cindex @option{-gnato??} (@command{gcc})
6771@cindex Overflow checks
6772@cindex Overflow mode
6773@cindex Check, overflow
6774This switch controls the mode used for computing intermediate
6775arithmetic integer operations, and also enables overflow checking.
6776For a full description of overflow mode and checking control, see
6777the ``Overflow Check Handling in GNAT'' appendix in this
6778User's Guide.
6779
6780Overflow checks are always enabled by this switch. The argument
6781controls the mode, using the codes
6782
6783@itemize
6784@item 1 = STRICT
6785In STRICT mode, intermediate operations are always done using the
6786base type, and overflow checking ensures that the result is within
6787the base type range.
6788
6789@item 2 = MINIMIZED
6790In MINIMIZED mode, overflows in intermediate operations are avoided
6791where possible by using a larger integer type for the computation
6792(typically @code{Long_Long_Integer}). Overflow checking ensures that
6793the result fits in this larger integer type.
6794
6795@item 3 = ELIMINATED
6796In ELIMINATED mode, overflows in intermediate operations are avoided
6797by using multi-precision arithmetic. In this case, overflow checking
6798has no effect on intermediate operations (since overflow is impossible).
6799@end itemize
6800
6801If two digits are present after @option{-gnato} then the first digit
6802sets the mode for expressions outside assertions, and the second digit
6803sets the mode for expressions within assertions. Here assertions is used
6804in the technical sense (which includes for example precondition and
6805postcondition expressions).
6806
6807If one digit is present, the corresponding mode is applicable to both
6808expressions within and outside assertion expressions.
6809
6810If no digits are present, the default is to enable overflow checks
6811and set STRICT mode for both kinds of expressions. This is compatible
6812with the use of @option{-gnato} in previous versions of GNAT.
6813
6814@findex Machine_Overflows
6815Note that the @option{-gnato??} switch does not affect the code generated
6816for any floating-point operations; it applies only to integer semantics.
6817For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6818attribute set to @code{False} and the normal mode of operation is to
6819generate IEEE NaN and infinite values on overflow or invalid operations
6820(such as dividing 0.0 by 0.0).
6821
6822The reason that we distinguish overflow checking from other kinds of
6823range constraint checking is that a failure of an overflow check, unlike
6824for example the failure of a range check, can result in an incorrect
6825value, but cannot cause random memory destruction (like an out of range
6826subscript), or a wild jump (from an out of range case value). Overflow
6827checking is also quite expensive in time and space, since in general it
6828requires the use of double length arithmetic.
6829
6830Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6831so overflow checking is not performed in default mode. This means that out of
6832the box, with the default settings, @value{EDITION} does not do all the checks
6833expected from the language description in the Ada Reference Manual.
6834If you want all constraint checks to be performed, as described in this Manual,
6835then you must explicitly use the @option{-gnato??}
6836switch either on the @command{gnatmake} or @command{gcc} command.
6837
6838@item -gnatE
6839@cindex @option{-gnatE} (@command{gcc})
6840@cindex Elaboration checks
6841@cindex Check, elaboration
6842Enables dynamic checks for access-before-elaboration
6843on subprogram calls and generic instantiations.
6844Note that @option{-gnatE} is not necessary for safety, because in the
6845default mode, GNAT ensures statically that the checks would not fail.
6846For full details of the effect and use of this switch,
6847@xref{Compiling with gcc}.
6848
6849@item -fstack-check
6850@cindex @option{-fstack-check} (@command{gcc})
6851@cindex Stack Overflow Checking
6852@cindex Checks, stack overflow checking
6853Activates stack overflow checking. For full details of the effect and use of
6854this switch see @ref{Stack Overflow Checking}.
6855@end table
6856
6857@findex Unsuppress
6858@noindent
6859The setting of these switches only controls the default setting of the
6860checks. You may modify them using either @code{Suppress} (to remove
6861checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6862the program source.
6863
6864@node Using gcc for Syntax Checking
6865@subsection Using @command{gcc} for Syntax Checking
6866@table @option
6867@item -gnats
6868@cindex @option{-gnats} (@command{gcc})
6869@ifclear vms
6870
6871@noindent
6872The @code{s} stands for ``syntax''.
6873@end ifclear
6874
6875Run GNAT in syntax checking only mode. For
6876example, the command
6877
6878@smallexample
6879$ gcc -c -gnats x.adb
6880@end smallexample
6881
6882@noindent
6883compiles file @file{x.adb} in syntax-check-only mode. You can check a
6884series of files in a single command
6885@ifclear vms
6886, and can use wild cards to specify such a group of files.
6887Note that you must specify the @option{-c} (compile
6888only) flag in addition to the @option{-gnats} flag.
6889@end ifclear
6890.
6891You may use other switches in conjunction with @option{-gnats}. In
6892particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6893format of any generated error messages.
6894
6895When the source file is empty or contains only empty lines and/or comments,
6896the output is a warning:
6897
6898@smallexample
6899$ gcc -c -gnats -x ada toto.txt
6900toto.txt:1:01: warning: empty file, contains no compilation units
6901$
6902@end smallexample
6903
6904Otherwise, the output is simply the error messages, if any. No object file or
6905ALI file is generated by a syntax-only compilation. Also, no units other
6906than the one specified are accessed. For example, if a unit @code{X}
6907@code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6908check only mode does not access the source file containing unit
6909@code{Y}.
6910
6911@cindex Multiple units, syntax checking
6912Normally, GNAT allows only a single unit in a source file. However, this
6913restriction does not apply in syntax-check-only mode, and it is possible
6914to check a file containing multiple compilation units concatenated
6915together. This is primarily used by the @code{gnatchop} utility
6916(@pxref{Renaming Files with gnatchop}).
6917@end table
6918
6919@node Using gcc for Semantic Checking
6920@subsection Using @command{gcc} for Semantic Checking
6921@table @option
6922@item -gnatc
6923@cindex @option{-gnatc} (@command{gcc})
6924
6925@ifclear vms
6926@noindent
6927The @code{c} stands for ``check''.
6928@end ifclear
6929Causes the compiler to operate in semantic check mode,
6930with full checking for all illegalities specified in the
6931Ada Reference Manual, but without generation of any object code
6932(no object file is generated).
6933
6934Because dependent files must be accessed, you must follow the GNAT
6935semantic restrictions on file structuring to operate in this mode:
6936
6937@itemize @bullet
6938@item
6939The needed source files must be accessible
6940(@pxref{Search Paths and the Run-Time Library (RTL)}).
6941
6942@item
6943Each file must contain only one compilation unit.
6944
6945@item
6946The file name and unit name must match (@pxref{File Naming Rules}).
6947@end itemize
6948
6949The output consists of error messages as appropriate. No object file is
6950generated. An @file{ALI} file is generated for use in the context of
6951cross-reference tools, but this file is marked as not being suitable
6952for binding (since no object file is generated).
6953The checking corresponds exactly to the notion of
6954legality in the Ada Reference Manual.
6955
6956Any unit can be compiled in semantics-checking-only mode, including
6957units that would not normally be compiled (subunits,
6958and specifications where a separate body is present).
6959@end table
6960
6961@node Compiling Different Versions of Ada
6962@subsection Compiling Different Versions of Ada
6963
6964@noindent
6965The switches described in this section allow you to explicitly specify
6966the version of the Ada language that your programs are written in.
6967The default mode is Ada 2012,
6968but you can also specify Ada 95, Ada 2005 mode, or
6969indicate Ada 83 compatibility mode.
6970
6971@table @option
6972@cindex Compatibility with Ada 83
6973
6974@item -gnat83 (Ada 83 Compatibility Mode)
6975@cindex @option{-gnat83} (@command{gcc})
6976@cindex ACVC, Ada 83 tests
6977@cindex Ada 83 mode
6978
6979@noindent
6980Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6981specifies that the program is to be compiled in Ada 83 mode. With
6982@option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6983semantics where this can be done easily.
6984It is not possible to guarantee this switch does a perfect
6985job; some subtle tests, such as are
6986found in earlier ACVC tests (and that have been removed from the ACATS suite
6987for Ada 95), might not compile correctly.
6988Nevertheless, this switch may be useful in some circumstances, for example
6989where, due to contractual reasons, existing code needs to be maintained
6990using only Ada 83 features.
6991
6992With few exceptions (most notably the need to use @code{<>} on
6993@cindex Generic formal parameters
6994unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6995reserved words, and the use of packages
6996with optional bodies), it is not necessary to specify the
6997@option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6998exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6999a correct Ada 83 program is usually also a correct program
7000in these later versions of the language standard.
7001For further information, please refer to @ref{Compatibility and Porting Guide}.
7002
7003@item -gnat95 (Ada 95 mode)
7004@cindex @option{-gnat95} (@command{gcc})
7005@cindex Ada 95 mode
7006
7007@noindent
7008This switch directs the compiler to implement the Ada 95 version of the
7009language.
7010Since Ada 95 is almost completely upwards
7011compatible with Ada 83, Ada 83 programs may generally be compiled using
7012this switch (see the description of the @option{-gnat83} switch for further
7013information about Ada 83 mode).
7014If an Ada 2005 program is compiled in Ada 95 mode,
7015uses of the new Ada 2005 features will cause error
7016messages or warnings.
7017
7018This switch also can be used to cancel the effect of a previous
7019@option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7020switch earlier in the command line.
7021
7022@item -gnat05 or -gnat2005 (Ada 2005 mode)
7023@cindex @option{-gnat05} (@command{gcc})
7024@cindex @option{-gnat2005} (@command{gcc})
7025@cindex Ada 2005 mode
7026
7027@noindent
7028This switch directs the compiler to implement the Ada 2005 version of the
7029language, as documented in the official Ada standards document.
7030Since Ada 2005 is almost completely upwards
7031compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7032may generally be compiled using this switch (see the description of the
7033@option{-gnat83} and @option{-gnat95} switches for further
7034information).
7035
7036@item -gnat12 or -gnat2012 (Ada 2012 mode)
7037@cindex @option{-gnat12} (@command{gcc})
7038@cindex @option{-gnat2012} (@command{gcc})
7039@cindex Ada 2012 mode
7040
7041@noindent
7042This switch directs the compiler to implement the Ada 2012 version of the
7043language (also the default).
7044Since Ada 2012 is almost completely upwards
7045compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7046Ada 83 and Ada 95 programs
7047may generally be compiled using this switch (see the description of the
7048@option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7049for further information).
7050
7051@item -gnatX (Enable GNAT Extensions)
7052@cindex @option{-gnatX} (@command{gcc})
7053@cindex Ada language extensions
7054@cindex GNAT extensions
7055
7056@noindent
7057This switch directs the compiler to implement the latest version of the
7058language (currently Ada 2012) and also to enable certain GNAT implementation
7059extensions that are not part of any Ada standard. For a full list of these
7060extensions, see the GNAT reference manual.
7061
7062@end table
7063
7064@node Character Set Control
7065@subsection Character Set Control
7066@table @option
7067@item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7068@cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7069
7070@noindent
7071Normally GNAT recognizes the Latin-1 character set in source program
7072identifiers, as described in the Ada Reference Manual.
7073This switch causes
7074GNAT to recognize alternate character sets in identifiers. @var{c} is a
7075single character ^^or word^ indicating the character set, as follows:
7076
7077@table @code
7078@item 1
7079ISO 8859-1 (Latin-1) identifiers
7080
7081@item 2
7082ISO 8859-2 (Latin-2) letters allowed in identifiers
7083
7084@item 3
7085ISO 8859-3 (Latin-3) letters allowed in identifiers
7086
7087@item 4
7088ISO 8859-4 (Latin-4) letters allowed in identifiers
7089
7090@item 5
7091ISO 8859-5 (Cyrillic) letters allowed in identifiers
7092
7093@item 9
7094ISO 8859-15 (Latin-9) letters allowed in identifiers
7095
7096@item ^p^PC^
7097IBM PC letters (code page 437) allowed in identifiers
7098
7099@item ^8^PC850^
7100IBM PC letters (code page 850) allowed in identifiers
7101
7102@item ^f^FULL_UPPER^
7103Full upper-half codes allowed in identifiers
7104
7105@item ^n^NO_UPPER^
7106No upper-half codes allowed in identifiers
7107
7108@item ^w^WIDE^
7109Wide-character codes (that is, codes greater than 255)
7110allowed in identifiers
7111@end table
7112
7113@xref{Foreign Language Representation}, for full details on the
7114implementation of these character sets.
7115
7116@item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7117@cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7118Specify the method of encoding for wide characters.
7119@var{e} is one of the following:
7120
7121@table @code
7122
7123@item ^h^HEX^
7124Hex encoding (brackets coding also recognized)
7125
7126@item ^u^UPPER^
7127Upper half encoding (brackets encoding also recognized)
7128
7129@item ^s^SHIFT_JIS^
7130Shift/JIS encoding (brackets encoding also recognized)
7131
7132@item ^e^EUC^
7133EUC encoding (brackets encoding also recognized)
7134
7135@item ^8^UTF8^
7136UTF-8 encoding (brackets encoding also recognized)
7137
7138@item ^b^BRACKETS^
7139Brackets encoding only (default value)
7140@end table
7141For full details on these encoding
7142methods see @ref{Wide Character Encodings}.
7143Note that brackets coding is always accepted, even if one of the other
7144options is specified, so for example @option{-gnatW8} specifies that both
7145brackets and UTF-8 encodings will be recognized. The units that are
7146with'ed directly or indirectly will be scanned using the specified
7147representation scheme, and so if one of the non-brackets scheme is
7148used, it must be used consistently throughout the program. However,
7149since brackets encoding is always recognized, it may be conveniently
7150used in standard libraries, allowing these libraries to be used with
7151any of the available coding schemes.
7152
7153Note that brackets encoding only applies to program text. Within comments,
7154brackets are considered to be normal graphic characters, and bracket sequences
7155are never recognized as wide characters.
7156
7157If no @option{-gnatW?} parameter is present, then the default
7158representation is normally Brackets encoding only. However, if the
7159first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7160byte order mark or BOM for UTF-8), then these three characters are
7161skipped and the default representation for the file is set to UTF-8.
7162
7163Note that the wide character representation that is specified (explicitly
7164or by default) for the main program also acts as the default encoding used
7165for Wide_Text_IO files if not specifically overridden by a WCEM form
7166parameter.
7167
7168@end table
7169
7170When no @option{-gnatW?} is specified, then characters (other than wide
7171characters represented using brackets notation) are treated as 8-bit
7172Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7173and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7174characters in the range 16#00#..16#1F# are not accepted in program text
7175or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7176in program text, but allowed and ignored in comments. Note in particular
7177that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7178as an end of line in this default mode. If your source program contains
7179instances of the NEL character used as a line terminator,
7180you must use UTF-8 encoding for the whole
7181source program. In default mode, all lines must be ended by a standard
7182end of line sequence (CR, CR/LF, or LF).
7183
7184Note that the convention of simply accepting all upper half characters in
7185comments means that programs that use standard ASCII for program text, but
7186UTF-8 encoding for comments are accepted in default mode, providing that the
7187comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7188This is a common mode for many programs with foreign language comments.
7189
7190@node File Naming Control
7191@subsection File Naming Control
7192
7193@table @option
7194@item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7195@cindex @option{-gnatk} (@command{gcc})
7196Activates file name ``krunching''. @var{n}, a decimal integer in the range
71971-999, indicates the maximum allowable length of a file name (not
7198including the @file{.ads} or @file{.adb} extension). The default is not
7199to enable file name krunching.
7200
7201For the source file naming rules, @xref{File Naming Rules}.
7202@end table
7203
7204@node Subprogram Inlining Control
7205@subsection Subprogram Inlining Control
7206
7207@table @option
7208@c !sort!
7209@item -gnatn[12]
7210@cindex @option{-gnatn} (@command{gcc})
7211@ifclear vms
7212The @code{n} here is intended to suggest the first syllable of the
7213word ``inline''.
7214@end ifclear
7215GNAT recognizes and processes @code{Inline} pragmas. However, for the
7216inlining to actually occur, optimization must be enabled and, in order
7217to enable inlining of subprograms specified by pragma @code{Inline},
7218you must also specify this switch.
7219In the absence of this switch, GNAT does not attempt
7220inlining and does not need to access the bodies of
7221subprograms for which @code{pragma Inline} is specified if they are not
7222in the current unit.
7223
7224You can optionally specify the inlining level: 1 for moderate inlining across
7225modules, which is a good compromise between compilation times and performances
7226at run time, or 2 for full inlining across modules, which may bring about
7227longer compilation times. If no inlining level is specified, the compiler will
7228pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7229@option{-Os} and 2 for @option{-O3}.
7230
7231If you specify this switch the compiler will access these bodies,
7232creating an extra source dependency for the resulting object file, and
7233where possible, the call will be inlined.
7234For further details on when inlining is possible
7235see @ref{Inlining of Subprograms}.
7236
7237@item -gnatN
7238@cindex @option{-gnatN} (@command{gcc})
7239This switch activates front-end inlining which also
7240generates additional dependencies.
7241
7242When using a gcc-based back end (in practice this means using any version
7243of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7244@option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7245Historically front end inlining was more extensive than the gcc back end
7246inlining, but that is no longer the case.
7247@end table
7248
7249@node Auxiliary Output Control
7250@subsection Auxiliary Output Control
7251
7252@table @option
7253@item -gnatt
7254@cindex @option{-gnatt} (@command{gcc})
7255@cindex Writing internal trees
7256@cindex Internal trees, writing to file
7257Causes GNAT to write the internal tree for a unit to a file (with the
7258extension @file{.adt}.
7259This not normally required, but is used by separate analysis tools.
7260Typically
7261these tools do the necessary compilations automatically, so you should
7262not have to specify this switch in normal operation.
7263Note that the combination of switches @option{-gnatct}
7264generates a tree in the form required by ASIS applications.
7265
7266@item -gnatu
7267@cindex @option{-gnatu} (@command{gcc})
7268Print a list of units required by this compilation on @file{stdout}.
7269The listing includes all units on which the unit being compiled depends
7270either directly or indirectly.
7271
7272@ifclear vms
7273@item -pass-exit-codes
7274@cindex @option{-pass-exit-codes} (@command{gcc})
7275If this switch is not used, the exit code returned by @command{gcc} when
7276compiling multiple files indicates whether all source files have
7277been successfully used to generate object files or not.
7278
7279When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7280exit status and allows an integrated development environment to better
7281react to a compilation failure. Those exit status are:
7282
7283@table @asis
7284@item 5
7285There was an error in at least one source file.
7286@item 3
7287At least one source file did not generate an object file.
7288@item 2
7289The compiler died unexpectedly (internal error for example).
7290@item 0
7291An object file has been generated for every source file.
7292@end table
7293@end ifclear
7294@end table
7295
7296@node Debugging Control
7297@subsection Debugging Control
7298
7299@table @option
7300@c !sort!
7301@cindex Debugging options
7302@ifclear vms
7303@item -gnatd@var{x}
7304@cindex @option{-gnatd} (@command{gcc})
7305Activate internal debugging switches. @var{x} is a letter or digit, or
7306string of letters or digits, which specifies the type of debugging
7307outputs desired. Normally these are used only for internal development
7308or system debugging purposes. You can find full documentation for these
7309switches in the body of the @code{Debug} unit in the compiler source
7310file @file{debug.adb}.
7311@end ifclear
7312
7313@item -gnatG[=nn]
7314@cindex @option{-gnatG} (@command{gcc})
7315This switch causes the compiler to generate auxiliary output containing
7316a pseudo-source listing of the generated expanded code. Like most Ada
7317compilers, GNAT works by first transforming the high level Ada code into
7318lower level constructs. For example, tasking operations are transformed
7319into calls to the tasking run-time routines. A unique capability of GNAT
7320is to list this expanded code in a form very close to normal Ada source.
7321This is very useful in understanding the implications of various Ada
7322usage on the efficiency of the generated code. There are many cases in
7323Ada (e.g.@: the use of controlled types), where simple Ada statements can
7324generate a lot of run-time code. By using @option{-gnatG} you can identify
7325these cases, and consider whether it may be desirable to modify the coding
7326approach to improve efficiency.
7327
7328The optional parameter @code{nn} if present after -gnatG specifies an
7329alternative maximum line length that overrides the normal default of 72.
7330This value is in the range 40-999999, values less than 40 being silently
7331reset to 40. The equal sign is optional.
7332
7333The format of the output is very similar to standard Ada source, and is
7334easily understood by an Ada programmer. The following special syntactic
7335additions correspond to low level features used in the generated code that
7336do not have any exact analogies in pure Ada source form. The following
7337is a partial list of these special constructions. See the spec
7338of package @code{Sprint} in file @file{sprint.ads} for a full list.
7339
7340If the switch @option{-gnatL} is used in conjunction with
7341@cindex @option{-gnatL} (@command{gcc})
7342@option{-gnatG}, then the original source lines are interspersed
7343in the expanded source (as comment lines with the original line number).
7344
7345@table @code
7346@item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7347Shows the storage pool being used for an allocator.
7348
7349@item at end @var{procedure-name};
7350Shows the finalization (cleanup) procedure for a scope.
7351
7352@item (if @var{expr} then @var{expr} else @var{expr})
7353Conditional expression equivalent to the @code{x?y:z} construction in C.
7354
7355@item @var{target}^^^(@var{source})
7356A conversion with floating-point truncation instead of rounding.
7357
7358@item @var{target}?(@var{source})
7359A conversion that bypasses normal Ada semantic checking. In particular
7360enumeration types and fixed-point types are treated simply as integers.
7361
7362@item @var{target}?^^^(@var{source})
7363Combines the above two cases.
7364
7365@item @var{x} #/ @var{y}
7366@itemx @var{x} #mod @var{y}
7367@itemx @var{x} #* @var{y}
7368@itemx @var{x} #rem @var{y}
7369A division or multiplication of fixed-point values which are treated as
7370integers without any kind of scaling.
7371
7372@item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7373Shows the storage pool associated with a @code{free} statement.
7374
7375@item [subtype or type declaration]
7376Used to list an equivalent declaration for an internally generated
7377type that is referenced elsewhere in the listing.
7378
7379@c @item freeze @var{type-name} @ovar{actions}
7380@c Expanding @ovar macro inline (explanation in macro def comments)
7381@item freeze @var{type-name} @r{[}@var{actions}@r{]}
7382Shows the point at which @var{type-name} is frozen, with possible
7383associated actions to be performed at the freeze point.
7384
7385@item reference @var{itype}
7386Reference (and hence definition) to internal type @var{itype}.
7387
7388@item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7389Intrinsic function call.
7390
7391@item @var{label-name} : label
7392Declaration of label @var{labelname}.
7393
7394@item #$ @var{subprogram-name}
7395An implicit call to a run-time support routine
7396(to meet the requirement of H.3.1(9) in a
7397convenient manner).
7398
7399@item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7400A multiple concatenation (same effect as @var{expr} & @var{expr} &
7401@var{expr}, but handled more efficiently).
7402
7403@item [constraint_error]
7404Raise the @code{Constraint_Error} exception.
7405
7406@item @var{expression}'reference
7407A pointer to the result of evaluating @var{expression}.
7408
7409@item @var{target-type}!(@var{source-expression})
7410An unchecked conversion of @var{source-expression} to @var{target-type}.
7411
7412@item [@var{numerator}/@var{denominator}]
7413Used to represent internal real literals (that) have no exact
7414representation in base 2-16 (for example, the result of compile time
7415evaluation of the expression 1.0/27.0).
7416@end table
7417
7418@item -gnatD[=nn]
7419@cindex @option{-gnatD} (@command{gcc})
7420When used in conjunction with @option{-gnatG}, this switch causes
7421the expanded source, as described above for
7422@option{-gnatG} to be written to files with names
7423@file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7424instead of to the standard output file. For
7425example, if the source file name is @file{hello.adb}, then a file
7426@file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7427information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7428will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7429you to do source level debugging using the generated code which is
7430sometimes useful for complex code, for example to find out exactly
7431which part of a complex construction raised an exception. This switch
7432also suppress generation of cross-reference information (see
7433@option{-gnatx}) since otherwise the cross-reference information
7434would refer to the @file{^.dg^.DG^} file, which would cause
7435confusion since this is not the original source file.
7436
7437Note that @option{-gnatD} actually implies @option{-gnatG}
7438automatically, so it is not necessary to give both options.
7439In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7440
7441If the switch @option{-gnatL} is used in conjunction with
7442@cindex @option{-gnatL} (@command{gcc})
7443@option{-gnatDG}, then the original source lines are interspersed
7444in the expanded source (as comment lines with the original line number).
7445
7446The optional parameter @code{nn} if present after -gnatD specifies an
7447alternative maximum line length that overrides the normal default of 72.
7448This value is in the range 40-999999, values less than 40 being silently
7449reset to 40. The equal sign is optional.
7450
7451@item -gnatr
7452@cindex @option{-gnatr} (@command{gcc})
7453@cindex pragma Restrictions
7454This switch causes pragma Restrictions to be treated as Restriction_Warnings
7455so that violation of restrictions causes warnings rather than illegalities.
7456This is useful during the development process when new restrictions are added
7457or investigated. The switch also causes pragma Profile to be treated as
7458Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7459restriction warnings rather than restrictions.
7460
7461@ifclear vms
7462@item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7463@cindex @option{-gnatR} (@command{gcc})
7464This switch controls output from the compiler of a listing showing
7465representation information for declared types and objects. For
7466@option{-gnatR0}, no information is output (equivalent to omitting
7467the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7468so @option{-gnatR} with no parameter has the same effect), size and alignment
7469information is listed for declared array and record types. For
7470@option{-gnatR2}, size and alignment information is listed for all
7471declared types and objects. The @code{Linker_Section} is also listed for any
7472entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7473latter case occurs for objects of a type for which a @code{Linker_Section}
7474is set).
7475
7476Finally @option{-gnatR3} includes symbolic
7477expressions for values that are computed at run time for
7478variant records. These symbolic expressions have a mostly obvious
7479format with #n being used to represent the value of the n'th
7480discriminant. See source files @file{repinfo.ads/adb} in the
7481@code{GNAT} sources for full details on the format of @option{-gnatR3}
7482output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7483the output is to a file with the name @file{^file.rep^file_REP^} where
7484file is the name of the corresponding source file.
7485
7486@item -gnatRm[s]
7487This form of the switch controls output of subprogram conventions
7488and parameter passing mechanisms for all subprograms. A following
7489@code{s} means output to a file as described above.
7490@end ifclear
7491@ifset vms
7492@item /REPRESENTATION_INFO
7493@cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7494This qualifier controls output from the compiler of a listing showing
7495representation information for declared types and objects. For
7496@option{/REPRESENTATION_INFO=NONE}, no information is output
7497(equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7498@option{/REPRESENTATION_INFO} without option is equivalent to
7499@option{/REPRESENTATION_INFO=ARRAYS}.
7500For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7501information is listed for declared array and record types. For
7502@option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7503is listed for all expression information for values that are computed
7504at run time for variant records. These symbolic expressions have a mostly
7505obvious format with #n being used to represent the value of the n'th
7506discriminant. See source files @file{REPINFO.ADS/ADB} in the
7507@code{GNAT} sources for full details on the format of
7508@option{/REPRESENTATION_INFO=SYMBOLIC} output.
7509If _FILE is added at the end of an option
7510(e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7511then the output is to a file with the name @file{file_REP} where
7512file is the name of the corresponding source file.
7513
7514@item /REPRESENTATION_INFO=MECHANISMS
7515This qualifier form controls output of subprogram conventions
7516and parameter passing mechanisms for all subprograms. It is
7517possible to append _FILE as described above to cause information
7518to be written to a file.
7519@end ifset
7520
7521Note that it is possible for record components to have zero size. In
7522this case, the component clause uses an obvious extension of permitted
7523Ada syntax, for example @code{at 0 range 0 .. -1}.
7524
7525Representation information requires that code be generated (since it is the
7526code generator that lays out complex data structures). If an attempt is made
7527to output representation information when no code is generated, for example
7528when a subunit is compiled on its own, then no information can be generated
7529and the compiler outputs a message to this effect.
7530
7531@item -gnatS
7532@cindex @option{-gnatS} (@command{gcc})
7533The use of the switch @option{-gnatS} for an
7534Ada compilation will cause the compiler to output a
7535representation of package Standard in a form very
7536close to standard Ada. It is not quite possible to
7537do this entirely in standard Ada (since new
7538numeric base types cannot be created in standard
7539Ada), but the output is easily
7540readable to any Ada programmer, and is useful to
7541determine the characteristics of target dependent
7542types in package Standard.
7543
7544@item -gnatx
7545@cindex @option{-gnatx} (@command{gcc})
7546Normally the compiler generates full cross-referencing information in
7547the @file{ALI} file. This information is used by a number of tools,
7548including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7549suppresses this information. This saves some space and may slightly
7550speed up compilation, but means that these tools cannot be used.
7551@end table
7552
7553@node Exception Handling Control
7554@subsection Exception Handling Control
7555
7556@noindent
7557GNAT uses two methods for handling exceptions at run-time. The
7558@code{setjmp/longjmp} method saves the context when entering
7559a frame with an exception handler. Then when an exception is
7560raised, the context can be restored immediately, without the
7561need for tracing stack frames. This method provides very fast
7562exception propagation, but introduces significant overhead for
7563the use of exception handlers, even if no exception is raised.
7564
7565The other approach is called ``zero cost'' exception handling.
7566With this method, the compiler builds static tables to describe
7567the exception ranges. No dynamic code is required when entering
7568a frame containing an exception handler. When an exception is
7569raised, the tables are used to control a back trace of the
7570subprogram invocation stack to locate the required exception
7571handler. This method has considerably poorer performance for
7572the propagation of exceptions, but there is no overhead for
7573exception handlers if no exception is raised. Note that in this
7574mode and in the context of mixed Ada and C/C++ programming,
7575to propagate an exception through a C/C++ code, the C/C++ code
7576must be compiled with the @option{-funwind-tables} GCC's
7577option.
7578
7579The following switches may be used to control which of the
7580two exception handling methods is used.
7581
7582@table @option
7583@c !sort!
7584
7585@item --RTS=sjlj
7586@cindex @option{--RTS=sjlj} (@command{gnatmake})
7587This switch causes the setjmp/longjmp run-time (when available) to be used
7588for exception handling. If the default
7589mechanism for the target is zero cost exceptions, then
7590this switch can be used to modify this default, and must be
7591used for all units in the partition.
7592This option is rarely used. One case in which it may be
7593advantageous is if you have an application where exception
7594raising is common and the overall performance of the
7595application is improved by favoring exception propagation.
7596
7597@item --RTS=zcx
7598@cindex @option{--RTS=zcx} (@command{gnatmake})
7599@cindex Zero Cost Exceptions
7600This switch causes the zero cost approach to be used
7601for exception handling. If this is the default mechanism for the
7602target (see below), then this switch is unneeded. If the default
7603mechanism for the target is setjmp/longjmp exceptions, then
7604this switch can be used to modify this default, and must be
7605used for all units in the partition.
7606This option can only be used if the zero cost approach
7607is available for the target in use, otherwise it will generate an error.
7608@end table
7609
7610@noindent
7611The same option @option{--RTS} must be used both for @command{gcc}
7612and @command{gnatbind}. Passing this option to @command{gnatmake}
7613(@pxref{Switches for gnatmake}) will ensure the required consistency
7614through the compilation and binding steps.
7615
7616@node Units to Sources Mapping Files
7617@subsection Units to Sources Mapping Files
7618
7619@table @option
7620
7621@item -gnatem=@var{path}
7622@cindex @option{-gnatem} (@command{gcc})
7623A mapping file is a way to communicate to the compiler two mappings:
7624from unit names to file names (without any directory information) and from
7625file names to path names (with full directory information). These mappings
7626are used by the compiler to short-circuit the path search.
7627
7628The use of mapping files is not required for correct operation of the
7629compiler, but mapping files can improve efficiency, particularly when
7630sources are read over a slow network connection. In normal operation,
7631you need not be concerned with the format or use of mapping files,
7632and the @option{-gnatem} switch is not a switch that you would use
7633explicitly. It is intended primarily for use by automatic tools such as
7634@command{gnatmake} running under the project file facility. The
7635description here of the format of mapping files is provided
7636for completeness and for possible use by other tools.
7637
7638A mapping file is a sequence of sets of three lines. In each set, the
7639first line is the unit name, in lower case, with @code{%s} appended
7640for specs and @code{%b} appended for bodies; the second line is the
7641file name; and the third line is the path name.
7642
7643Example:
7644@smallexample
7645   main%b
7646   main.2.ada
7647   /gnat/project1/sources/main.2.ada
7648@end smallexample
7649
7650When the switch @option{-gnatem} is specified, the compiler will
7651create in memory the two mappings from the specified file. If there is
7652any problem (nonexistent file, truncated file or duplicate entries),
7653no mapping will be created.
7654
7655Several @option{-gnatem} switches may be specified; however, only the
7656last one on the command line will be taken into account.
7657
7658When using a project file, @command{gnatmake} creates a temporary
7659mapping file and communicates it to the compiler using this switch.
7660
7661@end table
7662
7663@node Integrated Preprocessing
7664@subsection Integrated Preprocessing
7665
7666@noindent
7667GNAT sources may be preprocessed immediately before compilation.
7668In this case, the actual
7669text of the source is not the text of the source file, but is derived from it
7670through a process called preprocessing. Integrated preprocessing is specified
7671through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7672indicates, through a text file, the preprocessing data to be used.
7673@option{-gnateD} specifies or modifies the values of preprocessing symbol.
7674
7675@noindent
7676Note that when integrated preprocessing is used, the output from the
7677preprocessor is not written to any external file. Instead it is passed
7678internally to the compiler. If you need to preserve the result of
7679preprocessing in a file, then you should use @command{gnatprep}
7680to perform the desired preprocessing in stand-alone mode.
7681
7682@noindent
7683It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7684used when Integrated Preprocessing is used. The reason is that preprocessing
7685with another Preprocessing Data file without changing the sources will
7686not trigger recompilation without this switch.
7687
7688@noindent
7689Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7690always trigger recompilation for sources that are preprocessed,
7691because @command{gnatmake} cannot compute the checksum of the source after
7692preprocessing.
7693
7694@noindent
7695The actual preprocessing function is described in details in section
7696@ref{Preprocessing with gnatprep}. This section only describes how integrated
7697preprocessing is triggered and parameterized.
7698
7699@table @code
7700
7701@item -gnatep=@var{file}
7702@cindex @option{-gnatep} (@command{gcc})
7703This switch indicates to the compiler the file name (without directory
7704information) of the preprocessor data file to use. The preprocessor data file
7705should be found in the source directories. Note that when the compiler is
7706called by a builder such as (@command{gnatmake} with a project
7707file, if the object directory is not also a source directory, the builder needs
7708to be called with @option{-x}.
7709
7710@noindent
7711A preprocessing data file is a text file with significant lines indicating
7712how should be preprocessed either a specific source or all sources not
7713mentioned in other lines. A significant line is a nonempty, non-comment line.
7714Comments are similar to Ada comments.
7715
7716@noindent
7717Each significant line starts with either a literal string or the character '*'.
7718A literal string is the file name (without directory information) of the source
7719to preprocess. A character '*' indicates the preprocessing for all the sources
7720that are not specified explicitly on other lines (order of the lines is not
7721significant). It is an error to have two lines with the same file name or two
7722lines starting with the character '*'.
7723
7724@noindent
7725After the file name or the character '*', another optional literal string
7726indicating the file name of the definition file to be used for preprocessing
7727(@pxref{Form of Definitions File}). The definition files are found by the
7728compiler in one of the source directories. In some cases, when compiling
7729a source in a directory other than the current directory, if the definition
7730file is in the current directory, it may be necessary to add the current
7731directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7732the compiler would not find the definition file.
7733
7734@noindent
7735Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7736be found. Those ^switches^switches^ are:
7737
7738@table @code
7739
7740@item -b
7741Causes both preprocessor lines and the lines deleted by
7742preprocessing to be replaced by blank lines, preserving the line number.
7743This ^switch^switch^ is always implied; however, if specified after @option{-c}
7744it cancels the effect of @option{-c}.
7745
7746@item -c
7747Causes both preprocessor lines and the lines deleted
7748by preprocessing to be retained as comments marked
7749with the special string ``@code{--! }''.
7750
7751@item -Dsymbol=value
7752Define or redefine a symbol, associated with value. A symbol is an Ada
7753identifier, or an Ada reserved word, with the exception of @code{if},
7754@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7755@code{value} is either a literal string, an Ada identifier or any Ada reserved
7756word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7757same name defined in a definition file.
7758
7759@item -s
7760Causes a sorted list of symbol names and values to be
7761listed on the standard output file.
7762
7763@item -u
7764Causes undefined symbols to be treated as having the value @code{FALSE}
7765in the context
7766of a preprocessor test. In the absence of this option, an undefined symbol in
7767a @code{#if} or @code{#elsif} test will be treated as an error.
7768
7769@end table
7770
7771@noindent
7772Examples of valid lines in a preprocessor data file:
7773
7774@smallexample
7775  "toto.adb"  "prep.def" -u
7776  --  preprocess "toto.adb", using definition file "prep.def",
7777  --  undefined symbol are False.
7778
7779  * -c -DVERSION=V101
7780  --  preprocess all other sources without a definition file;
7781  --  suppressed lined are commented; symbol VERSION has the value V101.
7782
7783  "titi.adb" "prep2.def" -s
7784  --  preprocess "titi.adb", using definition file "prep2.def";
7785  --  list all symbols with their values.
7786@end smallexample
7787
7788@item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7789@cindex @option{-gnateD} (@command{gcc})
7790Define or redefine a preprocessing symbol, associated with value. If no value
7791is given on the command line, then the value of the symbol is @code{True}.
7792A symbol is an identifier, following normal Ada (case-insensitive)
7793rules for its syntax, and value is either an arbitrary string between double
7794quotes or any sequence (including an empty sequence) of characters from the
7795set (letters, digits, period, underline).
7796Ada reserved words may be used as symbols, with the exceptions of @code{if},
7797@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7798
7799@ifclear vms
7800@noindent
7801Examples:
7802
7803@smallexample
7804   -gnateDToto=Titi
7805   -gnateDFoo
7806   -gnateDFoo=\"Foo-Bar\"
7807@end smallexample
7808@end ifclear
7809
7810@noindent
7811A symbol declared with this ^switch^switch^ on the command line replaces a
7812symbol with the same name either in a definition file or specified with a
7813^switch^switch^ -D in the preprocessor data file.
7814
7815@noindent
7816This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7817
7818@item -gnateG
7819When integrated preprocessing is performed and the preprocessor modifies
7820the source text, write the result of this preprocessing into a file
7821<source>^.prep^_prep^.
7822
7823@end table
7824
7825@node Code Generation Control
7826@subsection Code Generation Control
7827
7828@noindent
7829
7830The GCC technology provides a wide range of target dependent
7831@option{-m} switches for controlling
7832details of code generation with respect to different versions of
7833architectures. This includes variations in instruction sets (e.g.@:
7834different members of the power pc family), and different requirements
7835for optimal arrangement of instructions (e.g.@: different members of
7836the x86 family). The list of available @option{-m} switches may be
7837found in the GCC documentation.
7838
7839Use of these @option{-m} switches may in some cases result in improved
7840code performance.
7841
7842The @value{EDITION} technology is tested and qualified without any
7843@option{-m} switches,
7844so generally the most reliable approach is to avoid the use of these
7845switches. However, we generally expect most of these switches to work
7846successfully with @value{EDITION}, and many customers have reported successful
7847use of these options.
7848
7849Our general advice is to avoid the use of @option{-m} switches unless
7850special needs lead to requirements in this area. In particular,
7851there is no point in using @option{-m} switches to improve performance
7852unless you actually see a performance improvement.
7853
7854@ifset vms
7855@node Return Codes
7856@subsection Return Codes
7857@cindex Return Codes
7858@cindex @option{/RETURN_CODES=VMS}
7859
7860@noindent
7861On VMS, GNAT compiled programs return POSIX-style codes by default,
7862e.g.@: @option{/RETURN_CODES=POSIX}.
7863
7864To enable VMS style return codes, use GNAT BIND and LINK with the option
7865@option{/RETURN_CODES=VMS}. For example:
7866
7867@smallexample
7868GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7869GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7870@end smallexample
7871
7872@noindent
7873Programs built with /RETURN_CODES=VMS are suitable to be called in
7874VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7875are suitable for spawning with appropriate GNAT RTL routines.
7876
7877@end ifset
7878
7879@node Search Paths and the Run-Time Library (RTL)
7880@section Search Paths and the Run-Time Library (RTL)
7881
7882@noindent
7883With the GNAT source-based library system, the compiler must be able to
7884find source files for units that are needed by the unit being compiled.
7885Search paths are used to guide this process.
7886
7887The compiler compiles one source file whose name must be given
7888explicitly on the command line. In other words, no searching is done
7889for this file. To find all other source files that are needed (the most
7890common being the specs of units), the compiler examines the following
7891directories, in the following order:
7892
7893@enumerate
7894@item
7895The directory containing the source file of the main unit being compiled
7896(the file name on the command line).
7897
7898@item
7899Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7900@command{gcc} command line, in the order given.
7901
7902@item
7903@findex ADA_PRJ_INCLUDE_FILE
7904Each of the directories listed in the text file whose name is given
7905by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7906
7907@noindent
7908@env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7909driver when project files are used. It should not normally be set
7910by other means.
7911
7912@item
7913@findex ADA_INCLUDE_PATH
7914Each of the directories listed in the value of the
7915@env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7916@ifclear vms
7917Construct this value
7918exactly as the @env{PATH} environment variable: a list of directory
7919names separated by colons (semicolons when working with the NT version).
7920@end ifclear
7921@ifset vms
7922Normally, define this value as a logical name containing a comma separated
7923list of directory names.
7924
7925This variable can also be defined by means of an environment string
7926(an argument to the HP C exec* set of functions).
7927
7928Logical Name:
7929@smallexample
7930DEFINE ANOTHER_PATH FOO:[BAG]
7931DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7932@end smallexample
7933
7934By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7935first, followed by the standard Ada
7936libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7937If this is not redefined, the user will obtain the HP Ada 83 IO packages
7938(Text_IO, Sequential_IO, etc)
7939instead of the standard Ada packages. Thus, in order to get the standard Ada
7940packages by default, ADA_INCLUDE_PATH must be redefined.
7941@end ifset
7942
7943@item
7944The content of the @file{ada_source_path} file which is part of the GNAT
7945installation tree and is used to store standard libraries such as the
7946GNAT Run Time Library (RTL) source files.
7947@ifclear vms
7948@ref{Installing a library}
7949@end ifclear
7950@end enumerate
7951
7952@noindent
7953Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7954inhibits the use of the directory
7955containing the source file named in the command line. You can still
7956have this directory on your search path, but in this case it must be
7957explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7958
7959Specifying the switch @option{-nostdinc}
7960inhibits the search of the default location for the GNAT Run Time
7961Library (RTL) source files.
7962
7963The compiler outputs its object files and ALI files in the current
7964working directory.
7965@ifclear vms
7966Caution: The object file can be redirected with the @option{-o} switch;
7967however, @command{gcc} and @code{gnat1} have not been coordinated on this
7968so the @file{ALI} file will not go to the right place. Therefore, you should
7969avoid using the @option{-o} switch.
7970@end ifclear
7971
7972@findex System.IO
7973The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7974children make up the GNAT RTL, together with the simple @code{System.IO}
7975package used in the @code{"Hello World"} example. The sources for these units
7976are needed by the compiler and are kept together in one directory. Not
7977all of the bodies are needed, but all of the sources are kept together
7978anyway. In a normal installation, you need not specify these directory
7979names when compiling or binding. Either the environment variables or
7980the built-in defaults cause these files to be found.
7981
7982In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7983@code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7984consisting of child units of @code{GNAT}. This is a collection of generally
7985useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7986This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7987
7988Besides simplifying access to the RTL, a major use of search paths is
7989in compiling sources from multiple directories. This can make
7990development environments much more flexible.
7991
7992@node Order of Compilation Issues
7993@section Order of Compilation Issues
7994
7995@noindent
7996If, in our earlier example, there was a spec for the @code{hello}
7997procedure, it would be contained in the file @file{hello.ads}; yet this
7998file would not have to be explicitly compiled. This is the result of the
7999model we chose to implement library management. Some of the consequences
8000of this model are as follows:
8001
8002@itemize @bullet
8003@item
8004There is no point in compiling specs (except for package
8005specs with no bodies) because these are compiled as needed by clients. If
8006you attempt a useless compilation, you will receive an error message.
8007It is also useless to compile subunits because they are compiled as needed
8008by the parent.
8009
8010@item
8011There are no order of compilation requirements: performing a
8012compilation never obsoletes anything. The only way you can obsolete
8013something and require recompilations is to modify one of the
8014source files on which it depends.
8015
8016@item
8017There is no library as such, apart from the ALI files
8018(@pxref{The Ada Library Information Files}, for information on the format
8019of these files). For now we find it convenient to create separate ALI files,
8020but eventually the information therein may be incorporated into the object
8021file directly.
8022
8023@item
8024When you compile a unit, the source files for the specs of all units
8025that it @code{with}'s, all its subunits, and the bodies of any generics it
8026instantiates must be available (reachable by the search-paths mechanism
8027described above), or you will receive a fatal error message.
8028@end itemize
8029
8030@node Examples
8031@section Examples
8032
8033@noindent
8034The following are some typical Ada compilation command line examples:
8035
8036@table @code
8037@item $ gcc -c xyz.adb
8038Compile body in file @file{xyz.adb} with all default options.
8039
8040@ifclear vms
8041@item $ gcc -c -O2 -gnata xyz-def.adb
8042@end ifclear
8043@ifset vms
8044@item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8045@end ifset
8046
8047Compile the child unit package in file @file{xyz-def.adb} with extensive
8048optimizations, and pragma @code{Assert}/@code{Debug} statements
8049enabled.
8050
8051@item $ gcc -c -gnatc abc-def.adb
8052Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8053mode.
8054@end table
8055
8056@node Binding with gnatbind
8057@chapter Binding with @code{gnatbind}
8058@findex gnatbind
8059
8060@menu
8061* Running gnatbind::
8062* Switches for gnatbind::
8063* Command-Line Access::
8064* Search Paths for gnatbind::
8065* Examples of gnatbind Usage::
8066@end menu
8067
8068@noindent
8069This chapter describes the GNAT binder, @code{gnatbind}, which is used
8070to bind compiled GNAT objects.
8071
8072Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8073driver (see @ref{The GNAT Driver and Project Files}).
8074
8075The @code{gnatbind} program performs four separate functions:
8076
8077@enumerate
8078@item
8079Checks that a program is consistent, in accordance with the rules in
8080Chapter 10 of the Ada Reference Manual. In particular, error
8081messages are generated if a program uses inconsistent versions of a
8082given unit.
8083
8084@item
8085Checks that an acceptable order of elaboration exists for the program
8086and issues an error message if it cannot find an order of elaboration
8087that satisfies the rules in Chapter 10 of the Ada Language Manual.
8088
8089@item
8090Generates a main program incorporating the given elaboration order.
8091This program is a small Ada package (body and spec) that
8092must be subsequently compiled
8093using the GNAT compiler. The necessary compilation step is usually
8094performed automatically by @command{gnatlink}. The two most important
8095functions of this program
8096are to call the elaboration routines of units in an appropriate order
8097and to call the main program.
8098
8099@item
8100Determines the set of object files required by the given main program.
8101This information is output in the forms of comments in the generated program,
8102to be read by the @command{gnatlink} utility used to link the Ada application.
8103@end enumerate
8104
8105@node Running gnatbind
8106@section Running @code{gnatbind}
8107
8108@noindent
8109The form of the @code{gnatbind} command is
8110
8111@smallexample
8112@c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8113@c Expanding @ovar macro inline (explanation in macro def comments)
8114$ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8115@end smallexample
8116
8117@noindent
8118where @file{@var{mainprog}.adb} is the Ada file containing the main program
8119unit body. @code{gnatbind} constructs an Ada
8120package in two files whose names are
8121@file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8122For example, if given the
8123parameter @file{hello.ali}, for a main program contained in file
8124@file{hello.adb}, the binder output files would be @file{b~hello.ads}
8125and @file{b~hello.adb}.
8126
8127When doing consistency checking, the binder takes into consideration
8128any source files it can locate. For example, if the binder determines
8129that the given main program requires the package @code{Pack}, whose
8130@file{.ALI}
8131file is @file{pack.ali} and whose corresponding source spec file is
8132@file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8133(using the same search path conventions as previously described for the
8134@command{gcc} command). If it can locate this source file, it checks that
8135the time stamps
8136or source checksums of the source and its references to in @file{ALI} files
8137match. In other words, any @file{ALI} files that mentions this spec must have
8138resulted from compiling this version of the source file (or in the case
8139where the source checksums match, a version close enough that the
8140difference does not matter).
8141
8142@cindex Source files, use by binder
8143The effect of this consistency checking, which includes source files, is
8144that the binder ensures that the program is consistent with the latest
8145version of the source files that can be located at bind time. Editing a
8146source file without compiling files that depend on the source file cause
8147error messages to be generated by the binder.
8148
8149For example, suppose you have a main program @file{hello.adb} and a
8150package @code{P}, from file @file{p.ads} and you perform the following
8151steps:
8152
8153@enumerate
8154@item
8155Enter @code{gcc -c hello.adb} to compile the main program.
8156
8157@item
8158Enter @code{gcc -c p.ads} to compile package @code{P}.
8159
8160@item
8161Edit file @file{p.ads}.
8162
8163@item
8164Enter @code{gnatbind hello}.
8165@end enumerate
8166
8167@noindent
8168At this point, the file @file{p.ali} contains an out-of-date time stamp
8169because the file @file{p.ads} has been edited. The attempt at binding
8170fails, and the binder generates the following error messages:
8171
8172@smallexample
8173error: "hello.adb" must be recompiled ("p.ads" has been modified)
8174error: "p.ads" has been modified and must be recompiled
8175@end smallexample
8176
8177@noindent
8178Now both files must be recompiled as indicated, and then the bind can
8179succeed, generating a main program. You need not normally be concerned
8180with the contents of this file, but for reference purposes a sample
8181binder output file is given in @ref{Example of Binder Output File}.
8182
8183In most normal usage, the default mode of @command{gnatbind} which is to
8184generate the main package in Ada, as described in the previous section.
8185In particular, this means that any Ada programmer can read and understand
8186the generated main program. It can also be debugged just like any other
8187Ada code provided the @option{^-g^/DEBUG^} switch is used for
8188@command{gnatbind} and @command{gnatlink}.
8189
8190@node Switches for gnatbind
8191@section Switches for @command{gnatbind}
8192
8193@noindent
8194The following switches are available with @code{gnatbind}; details will
8195be presented in subsequent sections.
8196
8197@menu
8198* Consistency-Checking Modes::
8199* Binder Error Message Control::
8200* Elaboration Control::
8201* Output Control::
8202* Dynamic Allocation Control::
8203* Binding with Non-Ada Main Programs::
8204* Binding Programs with No Main Subprogram::
8205@end menu
8206
8207@table @option
8208@c !sort!
8209
8210@item --version
8211@cindex @option{--version} @command{gnatbind}
8212Display Copyright and version, then exit disregarding all other options.
8213
8214@item --help
8215@cindex @option{--help} @command{gnatbind}
8216If @option{--version} was not used, display usage, then exit disregarding
8217all other options.
8218
8219@item -a
8220@cindex @option{-a} @command{gnatbind}
8221Indicates that, if supported by the platform, the adainit procedure should
8222be treated as an initialisation routine by the linker (a constructor). This
8223is intended to be used by the Project Manager to automatically initialize
8224shared Stand-Alone Libraries.
8225
8226@item ^-aO^/OBJECT_SEARCH^
8227@cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8228Specify directory to be searched for ALI files.
8229
8230@item ^-aI^/SOURCE_SEARCH^
8231@cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8232Specify directory to be searched for source file.
8233
8234@item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8235@cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8236Output ALI list (to standard output or to the named file).
8237
8238@item ^-b^/REPORT_ERRORS=BRIEF^
8239@cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8240Generate brief messages to @file{stderr} even if verbose mode set.
8241
8242@item ^-c^/NOOUTPUT^
8243@cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8244Check only, no generation of binder output file.
8245
8246@item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8247@cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8248This switch can be used to change the default task stack size value
8249to a specified size @var{nn}, which is expressed in bytes by default, or
8250in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8251with @var{m}.
8252In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8253in effect, to completing all task specs with
8254@smallexample @c ada
8255   pragma Storage_Size (nn);
8256@end smallexample
8257When they do not already have such a pragma.
8258
8259@item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8260@cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8261This switch can be used to change the default secondary stack size value
8262to a specified size @var{nn}, which is expressed in bytes by default, or
8263in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8264with @var{m}.
8265
8266The secondary stack is used to deal with functions that return a variable
8267sized result, for example a function returning an unconstrained
8268String. There are two ways in which this secondary stack is allocated.
8269
8270For most targets, the secondary stack is growing on demand and is allocated
8271as a chain of blocks in the heap. The -D option is not very
8272relevant. It only give some control over the size of the allocated
8273blocks (whose size is the minimum of the default secondary stack size value,
8274and the actual size needed for the current allocation request).
8275
8276For certain targets, notably VxWorks 653,
8277the secondary stack is allocated by carving off a fixed ratio chunk of the
8278primary task stack. The -D option is used to define the
8279size of the environment task's secondary stack.
8280
8281@item ^-e^/ELABORATION_DEPENDENCIES^
8282@cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8283Output complete list of elaboration-order dependencies.
8284
8285@item ^-E^/STORE_TRACEBACKS^
8286@cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8287Store tracebacks in exception occurrences when the target supports it.
8288@ignore
8289@c The following may get moved to an appendix
8290This option is currently supported on the following targets:
8291all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8292@end ignore
8293See also the packages @code{GNAT.Traceback} and
8294@code{GNAT.Traceback.Symbolic} for more information.
8295@ifclear vms
8296Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8297@command{gcc} option.
8298@end ifclear
8299
8300@item ^-F^/FORCE_ELABS_FLAGS^
8301@cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8302Force the checks of elaboration flags. @command{gnatbind} does not normally
8303generate checks of elaboration flags for the main executable, except when
8304a Stand-Alone Library is used. However, there are cases when this cannot be
8305detected by gnatbind. An example is importing an interface of a Stand-Alone
8306Library through a pragma Import and only specifying through a linker switch
8307this Stand-Alone Library. This switch is used to guarantee that elaboration
8308flag checks are generated.
8309
8310@item ^-h^/HELP^
8311@cindex @option{^-h^/HELP^} (@command{gnatbind})
8312Output usage (help) information
8313
8314@item ^-H32^/32_MALLOC^
8315@cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8316Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8317For further details see @ref{Dynamic Allocation Control}.
8318
8319@item ^-H64^/64_MALLOC^
8320@cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8321Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8322@cindex @code{__gnat_malloc}
8323For further details see @ref{Dynamic Allocation Control}.
8324
8325@item ^-I^/SEARCH^
8326@cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8327Specify directory to be searched for source and ALI files.
8328
8329@item ^-I-^/NOCURRENT_DIRECTORY^
8330@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8331Do not look for sources in the current directory where @code{gnatbind} was
8332invoked, and do not look for ALI files in the directory containing the
8333ALI file named in the @code{gnatbind} command line.
8334
8335@item ^-l^/ORDER_OF_ELABORATION^
8336@cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8337Output chosen elaboration order.
8338
8339@item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8340@cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8341Bind the units for library building. In this case the adainit and
8342adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8343are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8344^@var{xxx}final^@var{XXX}FINAL^.
8345Implies ^-n^/NOCOMPILE^.
8346@ifclear vms
8347(@xref{GNAT and Libraries}, for more details.)
8348@end ifclear
8349@ifset vms
8350On OpenVMS, these init and final procedures are exported in uppercase
8351letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8352the init procedure will be "TOTOINIT" and the exported name of the final
8353procedure will be "TOTOFINAL".
8354@end ifset
8355
8356@item ^-Mxyz^/RENAME_MAIN=xyz^
8357@cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8358Rename generated main program from main to xyz. This option is
8359supported on cross environments only.
8360
8361@item ^-m^/ERROR_LIMIT=^@var{n}
8362@cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8363Limit number of detected errors or warnings to @var{n}, where @var{n} is
8364in the range 1..999999. The default value if no switch is
8365given is 9999. If the number of warnings reaches this limit, then a
8366message is output and further warnings are suppressed, the bind
8367continues in this case. If the number of errors reaches this
8368limit, then a message is output and the bind is abandoned.
8369A value of zero means that no limit is enforced. The equal
8370sign is optional.
8371
8372@ifset unw
8373Furthermore, under Windows, the sources pointed to by the libraries path
8374set in the registry are not searched for.
8375@end ifset
8376
8377@item ^-n^/NOMAIN^
8378@cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8379No main program.
8380
8381@item -nostdinc
8382@cindex @option{-nostdinc} (@command{gnatbind})
8383Do not look for sources in the system default directory.
8384
8385@item -nostdlib
8386@cindex @option{-nostdlib} (@command{gnatbind})
8387Do not look for library files in the system default directory.
8388
8389@item --RTS=@var{rts-path}
8390@cindex @option{--RTS} (@code{gnatbind})
8391Specifies the default location of the runtime library. Same meaning as the
8392equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8393
8394@item ^-o ^/OUTPUT=^@var{file}
8395@cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8396Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8397Note that if this option is used, then linking must be done manually,
8398gnatlink cannot be used.
8399
8400@item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8401@cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8402Output object list (to standard output or to the named file).
8403
8404@item ^-p^/PESSIMISTIC_ELABORATION^
8405@cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8406Pessimistic (worst-case) elaboration order
8407
8408@item ^-P^-P^
8409@cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8410Generate binder file suitable for CodePeer.
8411
8412@item ^-R^-R^
8413@cindex @option{^-R^-R^} (@command{gnatbind})
8414Output closure source list.
8415
8416@item ^-s^/READ_SOURCES=ALL^
8417@cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8418Require all source files to be present.
8419
8420@item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8421@cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8422Specifies the value to be used when detecting uninitialized scalar
8423objects with pragma Initialize_Scalars.
8424The @var{xxx} ^string specified with the switch^option^ may be either
8425@itemize @bullet
8426@item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8427@item ``@option{^lo^LOW^}'' for the lowest possible value
8428@item ``@option{^hi^HIGH^}'' for the highest possible value
8429@item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8430value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8431@end itemize
8432
8433In addition, you can specify @option{-Sev} to indicate that the value is
8434to be set at run time. In this case, the program will look for an environment
8435@cindex GNAT_INIT_SCALARS
8436variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8437of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8438If no environment variable is found, or if it does not have a valid value,
8439then the default is @option{in} (invalid values).
8440
8441@ifclear vms
8442@item -static
8443@cindex @option{-static} (@code{gnatbind})
8444Link against a static GNAT run time.
8445
8446@item -shared
8447@cindex @option{-shared} (@code{gnatbind})
8448Link against a shared GNAT run time when available.
8449@end ifclear
8450
8451@item ^-t^/NOTIME_STAMP_CHECK^
8452@cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8453Tolerate time stamp and other consistency errors
8454
8455@item ^-T@var{n}^/TIME_SLICE=@var{n}^
8456@cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8457Set the time slice value to @var{n} milliseconds. If the system supports
8458the specification of a specific time slice value, then the indicated value
8459is used. If the system does not support specific time slice values, but
8460does support some general notion of round-robin scheduling, then any
8461nonzero value will activate round-robin scheduling.
8462
8463A value of zero is treated specially. It turns off time
8464slicing, and in addition, indicates to the tasking run time that the
8465semantics should match as closely as possible the Annex D
8466requirements of the Ada RM, and in particular sets the default
8467scheduling policy to @code{FIFO_Within_Priorities}.
8468
8469@item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8470@cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8471Enable dynamic stack usage, with @var{n} results stored and displayed
8472at program termination. A result is generated when a task
8473terminates. Results that can't be stored are displayed on the fly, at
8474task termination. This option is currently not supported on Itanium
8475platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8476
8477@item ^-v^/REPORT_ERRORS=VERBOSE^
8478@cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8479Verbose mode. Write error messages, header, summary output to
8480@file{stdout}.
8481
8482@ifclear vms
8483@item -w@var{x}
8484@cindex @option{-w} (@code{gnatbind})
8485Warning mode (@var{x}=s/e for suppress/treat as error)
8486@end ifclear
8487
8488@ifset vms
8489@item /WARNINGS=NORMAL
8490@cindex @option{/WARNINGS} (@code{gnatbind})
8491Normal warnings mode. Warnings are issued but ignored
8492
8493@item /WARNINGS=SUPPRESS
8494@cindex @option{/WARNINGS} (@code{gnatbind})
8495All warning messages are suppressed
8496
8497@item /WARNINGS=ERROR
8498@cindex @option{/WARNINGS} (@code{gnatbind})
8499Warning messages are treated as fatal errors
8500@end ifset
8501
8502@item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8503@cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8504Override default wide character encoding for standard Text_IO files.
8505
8506@item ^-x^/READ_SOURCES=NONE^
8507@cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8508Exclude source files (check object consistency only).
8509
8510@ifset vms
8511@item /READ_SOURCES=AVAILABLE
8512@cindex @option{/READ_SOURCES} (@code{gnatbind})
8513Default mode, in which sources are checked for consistency only if
8514they are available.
8515@end ifset
8516
8517@item ^-X@var{nnn}^/RETURN_CODES=POSIX^
8518@cindex @option{^-X@var{nnn}^/RETURN_CODES=POSIX^} (@code{gnatbind})
8519Set default exit status value, normally 0 for POSIX compliance.
8520
8521@ifset vms
8522@item /RETURN_CODES=VMS
8523@cindex @option{/RETURN_CODES=VMS} (@code{gnatbind})
8524VMS default normal successful return value is 1.
8525@end ifset
8526
8527@item ^-y^/ENABLE_LEAP_SECONDS^
8528@cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8529Enable leap seconds support in @code{Ada.Calendar} and its children.
8530
8531@item ^-z^/ZERO_MAIN^
8532@cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8533No main subprogram.
8534@end table
8535
8536@ifclear vms
8537@noindent
8538You may obtain this listing of switches by running @code{gnatbind} with
8539no arguments.
8540@end ifclear
8541
8542@node Consistency-Checking Modes
8543@subsection Consistency-Checking Modes
8544
8545@noindent
8546As described earlier, by default @code{gnatbind} checks
8547that object files are consistent with one another and are consistent
8548with any source files it can locate. The following switches control binder
8549access to sources.
8550
8551@table @option
8552@c !sort!
8553@item ^-s^/READ_SOURCES=ALL^
8554@cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8555Require source files to be present. In this mode, the binder must be
8556able to locate all source files that are referenced, in order to check
8557their consistency. In normal mode, if a source file cannot be located it
8558is simply ignored. If you specify this switch, a missing source
8559file is an error.
8560
8561@item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8562@cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8563Override default wide character encoding for standard Text_IO files.
8564Normally the default wide character encoding method used for standard
8565[Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8566the main source input (see description of switch
8567@option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8568use of this switch for the binder (which has the same set of
8569possible arguments) overrides this default as specified.
8570
8571@item ^-x^/READ_SOURCES=NONE^
8572@cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8573Exclude source files. In this mode, the binder only checks that ALI
8574files are consistent with one another. Source files are not accessed.
8575The binder runs faster in this mode, and there is still a guarantee that
8576the resulting program is self-consistent.
8577If a source file has been edited since it was last compiled, and you
8578specify this switch, the binder will not detect that the object
8579file is out of date with respect to the source file. Note that this is the
8580mode that is automatically used by @command{gnatmake} because in this
8581case the checking against sources has already been performed by
8582@command{gnatmake} in the course of compilation (i.e.@: before binding).
8583
8584@ifset vms
8585@item /READ_SOURCES=AVAILABLE
8586@cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8587This is the default mode in which source files are checked if they are
8588available, and ignored if they are not available.
8589@end ifset
8590@end table
8591
8592@node Binder Error Message Control
8593@subsection Binder Error Message Control
8594
8595@noindent
8596The following switches provide control over the generation of error
8597messages from the binder:
8598
8599@table @option
8600@c !sort!
8601@item ^-v^/REPORT_ERRORS=VERBOSE^
8602@cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8603Verbose mode. In the normal mode, brief error messages are generated to
8604@file{stderr}. If this switch is present, a header is written
8605to @file{stdout} and any error messages are directed to @file{stdout}.
8606All that is written to @file{stderr} is a brief summary message.
8607
8608@item ^-b^/REPORT_ERRORS=BRIEF^
8609@cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8610Generate brief error messages to @file{stderr} even if verbose mode is
8611specified. This is relevant only when used with the
8612@option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8613
8614@ifclear vms
8615@item -m@var{n}
8616@cindex @option{-m} (@code{gnatbind})
8617Limits the number of error messages to @var{n}, a decimal integer in the
8618range 1-999. The binder terminates immediately if this limit is reached.
8619
8620@item -M@var{xxx}
8621@cindex @option{-M} (@code{gnatbind})
8622Renames the generated main program from @code{main} to @code{xxx}.
8623This is useful in the case of some cross-building environments, where
8624the actual main program is separate from the one generated
8625by @code{gnatbind}.
8626@end ifclear
8627
8628@item ^-ws^/WARNINGS=SUPPRESS^
8629@cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8630@cindex Warnings
8631Suppress all warning messages.
8632
8633@item ^-we^/WARNINGS=ERROR^
8634@cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8635Treat any warning messages as fatal errors.
8636
8637@ifset vms
8638@item /WARNINGS=NORMAL
8639Standard mode with warnings generated, but warnings do not get treated
8640as errors.
8641@end ifset
8642
8643@item ^-t^/NOTIME_STAMP_CHECK^
8644@cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8645@cindex Time stamp checks, in binder
8646@cindex Binder consistency checks
8647@cindex Consistency checks, in binder
8648The binder performs a number of consistency checks including:
8649
8650@itemize @bullet
8651@item
8652Check that time stamps of a given source unit are consistent
8653@item
8654Check that checksums of a given source unit are consistent
8655@item
8656Check that consistent versions of @code{GNAT} were used for compilation
8657@item
8658Check consistency of configuration pragmas as required
8659@end itemize
8660
8661@noindent
8662Normally failure of such checks, in accordance with the consistency
8663requirements of the Ada Reference Manual, causes error messages to be
8664generated which abort the binder and prevent the output of a binder
8665file and subsequent link to obtain an executable.
8666
8667The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8668into warnings, so that
8669binding and linking can continue to completion even in the presence of such
8670errors. The result may be a failed link (due to missing symbols), or a
8671non-functional executable which has undefined semantics.
8672@emph{This means that
8673@option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8674with extreme care.}
8675@end table
8676
8677@node Elaboration Control
8678@subsection Elaboration Control
8679
8680@noindent
8681The following switches provide additional control over the elaboration
8682order. For full details see @ref{Elaboration Order Handling in GNAT}.
8683
8684@table @option
8685@item ^-p^/PESSIMISTIC_ELABORATION^
8686@cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8687Normally the binder attempts to choose an elaboration order that is
8688likely to minimize the likelihood of an elaboration order error resulting
8689in raising a @code{Program_Error} exception. This switch reverses the
8690action of the binder, and requests that it deliberately choose an order
8691that is likely to maximize the likelihood of an elaboration error.
8692This is useful in ensuring portability and avoiding dependence on
8693accidental fortuitous elaboration ordering.
8694
8695Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8696switch if dynamic
8697elaboration checking is used (@option{-gnatE} switch used for compilation).
8698This is because in the default static elaboration mode, all necessary
8699@code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8700These implicit pragmas are still respected by the binder in
8701@option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8702safe elaboration order is assured.
8703
8704Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8705production use; it is more for debugging/experimental use.
8706@end table
8707
8708@node Output Control
8709@subsection Output Control
8710
8711@noindent
8712The following switches allow additional control over the output
8713generated by the binder.
8714
8715@table @option
8716@c !sort!
8717
8718@item ^-c^/NOOUTPUT^
8719@cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8720Check only. Do not generate the binder output file. In this mode the
8721binder performs all error checks but does not generate an output file.
8722
8723@item ^-e^/ELABORATION_DEPENDENCIES^
8724@cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8725Output complete list of elaboration-order dependencies, showing the
8726reason for each dependency. This output can be rather extensive but may
8727be useful in diagnosing problems with elaboration order. The output is
8728written to @file{stdout}.
8729
8730@item ^-h^/HELP^
8731@cindex @option{^-h^/HELP^} (@code{gnatbind})
8732Output usage information. The output is written to @file{stdout}.
8733
8734@item ^-K^/LINKER_OPTION_LIST^
8735@cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8736Output linker options to @file{stdout}. Includes library search paths,
8737contents of pragmas Ident and Linker_Options, and libraries added
8738by @code{gnatbind}.
8739
8740@item ^-l^/ORDER_OF_ELABORATION^
8741@cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8742Output chosen elaboration order. The output is written to @file{stdout}.
8743
8744@item ^-O^/OBJECT_LIST^
8745@cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8746Output full names of all the object files that must be linked to provide
8747the Ada component of the program. The output is written to @file{stdout}.
8748This list includes the files explicitly supplied and referenced by the user
8749as well as implicitly referenced run-time unit files. The latter are
8750omitted if the corresponding units reside in shared libraries. The
8751directory names for the run-time units depend on the system configuration.
8752
8753@item ^-o ^/OUTPUT=^@var{file}
8754@cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8755Set name of output file to @var{file} instead of the normal
8756@file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8757binder generated body filename.
8758Note that if this option is used, then linking must be done manually.
8759It is not possible to use gnatlink in this case, since it cannot locate
8760the binder file.
8761
8762@item ^-r^/RESTRICTION_LIST^
8763@cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8764Generate list of @code{pragma Restrictions} that could be applied to
8765the current unit. This is useful for code audit purposes, and also may
8766be used to improve code generation in some cases.
8767
8768@end table
8769
8770@node Dynamic Allocation Control
8771@subsection Dynamic Allocation Control
8772
8773@noindent
8774The heap control switches -- @option{-H32} and @option{-H64} --
8775determine whether dynamic allocation uses 32-bit or 64-bit memory.
8776They only affect compiler-generated allocations via @code{__gnat_malloc};
8777explicit calls to @code{malloc} and related functions from the C
8778run-time library are unaffected.
8779
8780@table @option
8781@item -H32
8782Allocate memory on 32-bit heap
8783
8784@item -H64
8785Allocate memory on 64-bit heap.  This is the default
8786unless explicitly overridden by a @code{'Size} clause on the access type.
8787@end table
8788
8789@ifset vms
8790@noindent
8791See also @ref{Access types and 32/64-bit allocation}.
8792@end ifset
8793@ifclear vms
8794@noindent
8795These switches are only effective on VMS platforms.
8796@end ifclear
8797
8798
8799@node Binding with Non-Ada Main Programs
8800@subsection Binding with Non-Ada Main Programs
8801
8802@noindent
8803In our description so far we have assumed that the main
8804program is in Ada, and that the task of the binder is to generate a
8805corresponding function @code{main} that invokes this Ada main
8806program. GNAT also supports the building of executable programs where
8807the main program is not in Ada, but some of the called routines are
8808written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8809The following switch is used in this situation:
8810
8811@table @option
8812@item ^-n^/NOMAIN^
8813@cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8814No main program. The main program is not in Ada.
8815@end table
8816
8817@noindent
8818In this case, most of the functions of the binder are still required,
8819but instead of generating a main program, the binder generates a file
8820containing the following callable routines:
8821
8822@table @code
8823@item adainit
8824@findex adainit
8825You must call this routine to initialize the Ada part of the program by
8826calling the necessary elaboration routines. A call to @code{adainit} is
8827required before the first call to an Ada subprogram.
8828
8829Note that it is assumed that the basic execution environment must be setup
8830to be appropriate for Ada execution at the point where the first Ada
8831subprogram is called. In particular, if the Ada code will do any
8832floating-point operations, then the FPU must be setup in an appropriate
8833manner. For the case of the x86, for example, full precision mode is
8834required. The procedure GNAT.Float_Control.Reset may be used to ensure
8835that the FPU is in the right state.
8836
8837@item adafinal
8838@findex adafinal
8839You must call this routine to perform any library-level finalization
8840required by the Ada subprograms. A call to @code{adafinal} is required
8841after the last call to an Ada subprogram, and before the program
8842terminates.
8843@end table
8844
8845@noindent
8846If the @option{^-n^/NOMAIN^} switch
8847@cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8848@cindex Binder, multiple input files
8849is given, more than one ALI file may appear on
8850the command line for @code{gnatbind}. The normal @dfn{closure}
8851calculation is performed for each of the specified units. Calculating
8852the closure means finding out the set of units involved by tracing
8853@code{with} references. The reason it is necessary to be able to
8854specify more than one ALI file is that a given program may invoke two or
8855more quite separate groups of Ada units.
8856
8857The binder takes the name of its output file from the last specified ALI
8858file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8859@cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8860The output is an Ada unit in source form that can be compiled with GNAT.
8861This compilation occurs automatically as part of the @command{gnatlink}
8862processing.
8863
8864Currently the GNAT run time requires a FPU using 80 bits mode
8865precision. Under targets where this is not the default it is required to
8866call GNAT.Float_Control.Reset before using floating point numbers (this
8867include float computation, float input and output) in the Ada code. A
8868side effect is that this could be the wrong mode for the foreign code
8869where floating point computation could be broken after this call.
8870
8871@node Binding Programs with No Main Subprogram
8872@subsection Binding Programs with No Main Subprogram
8873
8874@noindent
8875It is possible to have an Ada program which does not have a main
8876subprogram. This program will call the elaboration routines of all the
8877packages, then the finalization routines.
8878
8879The following switch is used to bind programs organized in this manner:
8880
8881@table @option
8882@item ^-z^/ZERO_MAIN^
8883@cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8884Normally the binder checks that the unit name given on the command line
8885corresponds to a suitable main subprogram. When this switch is used,
8886a list of ALI files can be given, and the execution of the program
8887consists of elaboration of these units in an appropriate order. Note
8888that the default wide character encoding method for standard Text_IO
8889files is always set to Brackets if this switch is set (you can use
8890the binder switch
8891@option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8892@end table
8893
8894@node Command-Line Access
8895@section Command-Line Access
8896
8897@noindent
8898The package @code{Ada.Command_Line} provides access to the command-line
8899arguments and program name. In order for this interface to operate
8900correctly, the two variables
8901
8902@smallexample
8903@group
8904int gnat_argc;
8905char **gnat_argv;
8906@end group
8907@end smallexample
8908
8909@noindent
8910@findex gnat_argv
8911@findex gnat_argc
8912are declared in one of the GNAT library routines. These variables must
8913be set from the actual @code{argc} and @code{argv} values passed to the
8914main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8915generates the C main program to automatically set these variables.
8916If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8917set these variables. If they are not set, the procedures in
8918@code{Ada.Command_Line} will not be available, and any attempt to use
8919them will raise @code{Constraint_Error}. If command line access is
8920required, your main program must set @code{gnat_argc} and
8921@code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8922it.
8923
8924@node Search Paths for gnatbind
8925@section Search Paths for @code{gnatbind}
8926
8927@noindent
8928The binder takes the name of an ALI file as its argument and needs to
8929locate source files as well as other ALI files to verify object consistency.
8930
8931For source files, it follows exactly the same search rules as @command{gcc}
8932(@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8933directories searched are:
8934
8935@enumerate
8936@item
8937The directory containing the ALI file named in the command line, unless
8938the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8939
8940@item
8941All directories specified by @option{^-I^/SEARCH^}
8942switches on the @code{gnatbind}
8943command line, in the order given.
8944
8945@item
8946@findex ADA_PRJ_OBJECTS_FILE
8947Each of the directories listed in the text file whose name is given
8948by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8949
8950@noindent
8951@env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8952driver when project files are used. It should not normally be set
8953by other means.
8954
8955@item
8956@findex ADA_OBJECTS_PATH
8957Each of the directories listed in the value of the
8958@env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8959@ifset unw
8960Construct this value
8961exactly as the @env{PATH} environment variable: a list of directory
8962names separated by colons (semicolons when working with the NT version
8963of GNAT).
8964@end ifset
8965@ifset vms
8966Normally, define this value as a logical name containing a comma separated
8967list of directory names.
8968
8969This variable can also be defined by means of an environment string
8970(an argument to the HP C exec* set of functions).
8971
8972Logical Name:
8973@smallexample
8974DEFINE ANOTHER_PATH FOO:[BAG]
8975DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8976@end smallexample
8977
8978By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8979first, followed by the standard Ada
8980libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8981If this is not redefined, the user will obtain the HP Ada 83 IO packages
8982(Text_IO, Sequential_IO, etc)
8983instead of the standard Ada packages. Thus, in order to get the standard Ada
8984packages by default, ADA_OBJECTS_PATH must be redefined.
8985@end ifset
8986
8987@item
8988The content of the @file{ada_object_path} file which is part of the GNAT
8989installation tree and is used to store standard libraries such as the
8990GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8991specified.
8992@ifclear vms
8993@ref{Installing a library}
8994@end ifclear
8995@end enumerate
8996
8997@noindent
8998In the binder the switch @option{^-I^/SEARCH^}
8999@cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9000is used to specify both source and
9001library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9002@cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9003instead if you want to specify
9004source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9005@cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9006if you want to specify library paths
9007only. This means that for the binder
9008@option{^-I^/SEARCH=^}@var{dir} is equivalent to
9009@option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9010@option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9011The binder generates the bind file (a C language source file) in the
9012current working directory.
9013
9014@findex Ada
9015@findex System
9016@findex Interfaces
9017@findex GNAT
9018The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9019children make up the GNAT Run-Time Library, together with the package
9020GNAT and its children, which contain a set of useful additional
9021library functions provided by GNAT. The sources for these units are
9022needed by the compiler and are kept together in one directory. The ALI
9023files and object files generated by compiling the RTL are needed by the
9024binder and the linker and are kept together in one directory, typically
9025different from the directory containing the sources. In a normal
9026installation, you need not specify these directory names when compiling
9027or binding. Either the environment variables or the built-in defaults
9028cause these files to be found.
9029
9030Besides simplifying access to the RTL, a major use of search paths is
9031in compiling sources from multiple directories. This can make
9032development environments much more flexible.
9033
9034@node Examples of gnatbind Usage
9035@section Examples of @code{gnatbind} Usage
9036
9037@noindent
9038This section contains a number of examples of using the GNAT binding
9039utility @code{gnatbind}.
9040
9041@table @code
9042@item gnatbind hello
9043The main program @code{Hello} (source program in @file{hello.adb}) is
9044bound using the standard switch settings. The generated main program is
9045@file{b~hello.adb}. This is the normal, default use of the binder.
9046
9047@ifclear vms
9048@item gnatbind hello -o mainprog.adb
9049@end ifclear
9050@ifset vms
9051@item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9052@end ifset
9053The main program @code{Hello} (source program in @file{hello.adb}) is
9054bound using the standard switch settings. The generated main program is
9055@file{mainprog.adb} with the associated spec in
9056@file{mainprog.ads}. Note that you must specify the body here not the
9057spec. Note that if this option is used, then linking must be done manually,
9058since gnatlink will not be able to find the generated file.
9059@end table
9060
9061@c ------------------------------------
9062@node Linking with gnatlink
9063@chapter Linking with @command{gnatlink}
9064@c ------------------------------------
9065@findex gnatlink
9066
9067@noindent
9068This chapter discusses @command{gnatlink}, a tool that links
9069an Ada program and builds an executable file. This utility
9070invokes the system linker ^(via the @command{gcc} command)^^
9071with a correct list of object files and library references.
9072@command{gnatlink} automatically determines the list of files and
9073references for the Ada part of a program. It uses the binder file
9074generated by the @command{gnatbind} to determine this list.
9075
9076Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9077driver (see @ref{The GNAT Driver and Project Files}).
9078
9079@menu
9080* Running gnatlink::
9081* Switches for gnatlink::
9082@end menu
9083
9084@node Running gnatlink
9085@section Running @command{gnatlink}
9086
9087@noindent
9088The form of the @command{gnatlink} command is
9089
9090@smallexample
9091@c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9092@c            @ovar{non-Ada objects} @ovar{linker options}
9093@c Expanding @ovar macro inline (explanation in macro def comments)
9094$ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9095           @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9096
9097@end smallexample
9098
9099@noindent
9100The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9101non-Ada objects
9102or linker options) may be in any order, provided that no non-Ada object may
9103be mistaken for a main @file{ALI} file.
9104Any file name @file{F} without the @file{.ali}
9105extension will be taken as the main @file{ALI} file if a file exists
9106whose name is the concatenation of @file{F} and @file{.ali}.
9107
9108@noindent
9109@file{@var{mainprog}.ali} references the ALI file of the main program.
9110The @file{.ali} extension of this file can be omitted. From this
9111reference, @command{gnatlink} locates the corresponding binder file
9112@file{b~@var{mainprog}.adb} and, using the information in this file along
9113with the list of non-Ada objects and linker options, constructs a
9114linker command file to create the executable.
9115
9116The arguments other than the @command{gnatlink} switches and the main
9117@file{ALI} file are passed to the linker uninterpreted.
9118They typically include the names of
9119object files for units written in other languages than Ada and any library
9120references required to resolve references in any of these foreign language
9121units, or in @code{Import} pragmas in any Ada units.
9122
9123@var{linker options} is an optional list of linker specific
9124switches.
9125The default linker called by gnatlink is @command{gcc} which in
9126turn calls the appropriate system linker.
9127
9128One useful option for the linker is @option{-s}: it reduces the size of the
9129executable by removing all symbol table and relocation information from the
9130executable.
9131
9132Standard options for the linker such as @option{-lmy_lib} or
9133@option{-Ldir} can be added as is.
9134For options that are not recognized by
9135@command{gcc} as linker options, use the @command{gcc} switches
9136@option{-Xlinker} or @option{-Wl,}.
9137
9138Refer to the GCC documentation for
9139details.
9140
9141Here is an example showing how to generate a linker map:
9142
9143@smallexample
9144$ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9145@end smallexample
9146
9147Using @var{linker options} it is possible to set the program stack and
9148heap size.
9149@ifset unw
9150See @ref{Setting Stack Size from gnatlink} and
9151@ref{Setting Heap Size from gnatlink}.
9152@end ifset
9153
9154@command{gnatlink} determines the list of objects required by the Ada
9155program and prepends them to the list of objects passed to the linker.
9156@command{gnatlink} also gathers any arguments set by the use of
9157@code{pragma Linker_Options} and adds them to the list of arguments
9158presented to the linker.
9159
9160@ifset vms
9161@command{gnatlink} accepts the following types of extra files on the command
9162line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9163(@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9164handled according to their extension.
9165@end ifset
9166
9167@node Switches for gnatlink
9168@section Switches for @command{gnatlink}
9169
9170@noindent
9171The following switches are available with the @command{gnatlink} utility:
9172
9173@table @option
9174@c !sort!
9175
9176@item --version
9177@cindex @option{--version} @command{gnatlink}
9178Display Copyright and version, then exit disregarding all other options.
9179
9180@item --help
9181@cindex @option{--help} @command{gnatlink}
9182If @option{--version} was not used, display usage, then exit disregarding
9183all other options.
9184
9185@item ^-f^/FORCE_OBJECT_FILE_LIST^
9186@cindex Command line length
9187@cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9188On some targets, the command line length is limited, and @command{gnatlink}
9189will generate a separate file for the linker if the list of object files
9190is too long.
9191The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9192to be generated even if
9193the limit is not exceeded. This is useful in some cases to deal with
9194special situations where the command line length is exceeded.
9195
9196@item ^-g^/DEBUG^
9197@cindex Debugging information, including
9198@cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9199The option to include debugging information causes the Ada bind file (in
9200other words, @file{b~@var{mainprog}.adb}) to be compiled with
9201@option{^-g^/DEBUG^}.
9202In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9203@file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9204Without @option{^-g^/DEBUG^}, the binder removes these files by
9205default. The same procedure apply if a C bind file was generated using
9206@option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9207are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9208
9209@item ^-n^/NOCOMPILE^
9210@cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9211Do not compile the file generated by the binder. This may be used when
9212a link is rerun with different options, but there is no need to recompile
9213the binder file.
9214
9215@item ^-v^/VERBOSE^
9216@cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9217Causes additional information to be output, including a full list of the
9218included object files. This switch option is most useful when you want
9219to see what set of object files are being used in the link step.
9220
9221@item ^-v -v^/VERBOSE/VERBOSE^
9222@cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9223Very verbose mode. Requests that the compiler operate in verbose mode when
9224it compiles the binder file, and that the system linker run in verbose mode.
9225
9226@item ^-o ^/EXECUTABLE=^@var{exec-name}
9227@cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9228@var{exec-name} specifies an alternate name for the generated
9229executable program. If this switch is omitted, the executable has the same
9230name as the main unit. For example, @code{gnatlink try.ali} creates
9231an executable called @file{^try^TRY.EXE^}.
9232
9233@ifclear vms
9234@item -b @var{target}
9235@cindex @option{-b} (@command{gnatlink})
9236Compile your program to run on @var{target}, which is the name of a
9237system configuration. You must have a GNAT cross-compiler built if
9238@var{target} is not the same as your host system.
9239
9240@item -B@var{dir}
9241@cindex @option{-B} (@command{gnatlink})
9242Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9243from @var{dir} instead of the default location. Only use this switch
9244when multiple versions of the GNAT compiler are available.
9245@xref{Directory Options,,, gcc, The GNU Compiler Collection},
9246for further details. You would normally use the @option{-b} or
9247@option{-V} switch instead.
9248
9249@item -M
9250When linking an executable, create a map file. The name of the map file
9251has the same name as the executable with extension ".map".
9252
9253@item -M=mapfile
9254When linking an executable, create a map file. The name of the map file is
9255"mapfile".
9256
9257@item --GCC=@var{compiler_name}
9258@cindex @option{--GCC=compiler_name} (@command{gnatlink})
9259Program used for compiling the binder file. The default is
9260@command{gcc}. You need to use quotes around @var{compiler_name} if
9261@code{compiler_name} contains spaces or other separator characters.
9262As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9263use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9264inserted after your command name. Thus in the above example the compiler
9265command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9266A limitation of this syntax is that the name and path name of the executable
9267itself must not include any embedded spaces. If the compiler executable is
9268different from the default one (gcc or <prefix>-gcc), then the back-end
9269switches in the ALI file are not used to compile the binder generated source.
9270For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9271switches will be used for @option{--GCC="gcc -gnatv"}. If several
9272@option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9273is taken into account. However, all the additional switches are also taken
9274into account. Thus,
9275@option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9276@option{--GCC="bar -x -y -z -t"}.
9277
9278@item --LINK=@var{name}
9279@cindex @option{--LINK=} (@command{gnatlink})
9280@var{name} is the name of the linker to be invoked. This is especially
9281useful in mixed language programs since languages such as C++ require
9282their own linker to be used. When this switch is omitted, the default
9283name for the linker is @command{gcc}. When this switch is used, the
9284specified linker is called instead of @command{gcc} with exactly the same
9285parameters that would have been passed to @command{gcc} so if the desired
9286linker requires different parameters it is necessary to use a wrapper
9287script that massages the parameters before invoking the real linker. It
9288may be useful to control the exact invocation by using the verbose
9289switch.
9290
9291@end ifclear
9292
9293@ifset vms
9294@item /DEBUG=TRACEBACK
9295@cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9296This qualifier causes sufficient information to be included in the
9297executable file to allow a traceback, but does not include the full
9298symbol information needed by the debugger.
9299
9300@item /IDENTIFICATION="<string>"
9301@code{"<string>"} specifies the string to be stored in the image file
9302identification field in the image header.
9303It overrides any pragma @code{Ident} specified string.
9304
9305@item /NOINHIBIT-EXEC
9306Generate the executable file even if there are linker warnings.
9307
9308@item /NOSTART_FILES
9309Don't link in the object file containing the ``main'' transfer address.
9310Used when linking with a foreign language main program compiled with an
9311HP compiler.
9312
9313@item /STATIC
9314Prefer linking with object libraries over sharable images, even without
9315/DEBUG.
9316@end ifset
9317
9318@end table
9319
9320@node The GNAT Make Program gnatmake
9321@chapter The GNAT Make Program @command{gnatmake}
9322@findex gnatmake
9323
9324@menu
9325* Running gnatmake::
9326* Switches for gnatmake::
9327* Mode Switches for gnatmake::
9328* Notes on the Command Line::
9329* How gnatmake Works::
9330* Examples of gnatmake Usage::
9331@end menu
9332@noindent
9333A typical development cycle when working on an Ada program consists of
9334the following steps:
9335
9336@enumerate
9337@item
9338Edit some sources to fix bugs.
9339
9340@item
9341Add enhancements.
9342
9343@item
9344Compile all sources affected.
9345
9346@item
9347Rebind and relink.
9348
9349@item
9350Test.
9351@end enumerate
9352
9353@noindent
9354The third step can be tricky, because not only do the modified files
9355@cindex Dependency rules
9356have to be compiled, but any files depending on these files must also be
9357recompiled. The dependency rules in Ada can be quite complex, especially
9358in the presence of overloading, @code{use} clauses, generics and inlined
9359subprograms.
9360
9361@command{gnatmake} automatically takes care of the third and fourth steps
9362of this process. It determines which sources need to be compiled,
9363compiles them, and binds and links the resulting object files.
9364
9365Unlike some other Ada make programs, the dependencies are always
9366accurately recomputed from the new sources. The source based approach of
9367the GNAT compilation model makes this possible. This means that if
9368changes to the source program cause corresponding changes in
9369dependencies, they will always be tracked exactly correctly by
9370@command{gnatmake}.
9371
9372@node Running gnatmake
9373@section Running @command{gnatmake}
9374
9375@noindent
9376The usual form of the @command{gnatmake} command is
9377
9378@smallexample
9379@c $ gnatmake @ovar{switches} @var{file_name}
9380@c       @ovar{file_names} @ovar{mode_switches}
9381@c Expanding @ovar macro inline (explanation in macro def comments)
9382$ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9383      @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9384@end smallexample
9385
9386@noindent
9387The only required argument is one @var{file_name}, which specifies
9388a compilation unit that is a main program. Several @var{file_names} can be
9389specified: this will result in several executables being built.
9390If @code{switches} are present, they can be placed before the first
9391@var{file_name}, between @var{file_names} or after the last @var{file_name}.
9392If @var{mode_switches} are present, they must always be placed after
9393the last @var{file_name} and all @code{switches}.
9394
9395If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9396extension may be omitted from the @var{file_name} arguments. However, if
9397you are using non-standard extensions, then it is required that the
9398extension be given. A relative or absolute directory path can be
9399specified in a @var{file_name}, in which case, the input source file will
9400be searched for in the specified directory only. Otherwise, the input
9401source file will first be searched in the directory where
9402@command{gnatmake} was invoked and if it is not found, it will be search on
9403the source path of the compiler as described in
9404@ref{Search Paths and the Run-Time Library (RTL)}.
9405
9406All @command{gnatmake} output (except when you specify
9407@option{^-M^/DEPENDENCIES_LIST^}) is to
9408@file{stderr}. The output produced by the
9409@option{^-M^/DEPENDENCIES_LIST^} switch is send to
9410@file{stdout}.
9411
9412@node Switches for gnatmake
9413@section Switches for @command{gnatmake}
9414
9415@noindent
9416You may specify any of the following switches to @command{gnatmake}:
9417
9418@table @option
9419@c !sort!
9420
9421@item --version
9422@cindex @option{--version} @command{gnatmake}
9423Display Copyright and version, then exit disregarding all other options.
9424
9425@item --help
9426@cindex @option{--help} @command{gnatmake}
9427If @option{--version} was not used, display usage, then exit disregarding
9428all other options.
9429
9430@ifclear vms
9431@item --GCC=@var{compiler_name}
9432@cindex @option{--GCC=compiler_name} (@command{gnatmake})
9433Program used for compiling. The default is `@command{gcc}'. You need to use
9434quotes around @var{compiler_name} if @code{compiler_name} contains
9435spaces or other separator characters. As an example @option{--GCC="foo -x
9436-y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9437compiler. A limitation of this syntax is that the name and path name of
9438the executable itself must not include any embedded spaces. Note that
9439switch @option{-c} is always inserted after your command name. Thus in the
9440above example the compiler command that will be used by @command{gnatmake}
9441will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9442used, only the last @var{compiler_name} is taken into account. However,
9443all the additional switches are also taken into account. Thus,
9444@option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9445@option{--GCC="bar -x -y -z -t"}.
9446
9447@item --GNATBIND=@var{binder_name}
9448@cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9449Program used for binding. The default is `@code{gnatbind}'. You need to
9450use quotes around @var{binder_name} if @var{binder_name} contains spaces
9451or other separator characters. As an example @option{--GNATBIND="bar -x
9452-y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9453binder. Binder switches that are normally appended by @command{gnatmake}
9454to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9455A limitation of this syntax is that the name and path name of the executable
9456itself must not include any embedded spaces.
9457
9458@item --GNATLINK=@var{linker_name}
9459@cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9460Program used for linking. The default is `@command{gnatlink}'. You need to
9461use quotes around @var{linker_name} if @var{linker_name} contains spaces
9462or other separator characters. As an example @option{--GNATLINK="lan -x
9463-y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9464linker. Linker switches that are normally appended by @command{gnatmake} to
9465`@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9466A limitation of this syntax is that the name and path name of the executable
9467itself must not include any embedded spaces.
9468
9469@end ifclear
9470
9471@item ^--subdirs^/SUBDIRS^=subdir
9472Actual object directory of each project file is the subdirectory subdir of the
9473object directory specified or defaulted in the project file.
9474
9475@item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9476Disallow simultaneous compilations in the same object directory when
9477project files are used.
9478
9479@item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9480By default, shared library projects are not allowed to import static library
9481projects. When this switch is used on the command line, this restriction is
9482relaxed.
9483
9484@item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9485Specify a source info file. This switch is active only when project files
9486are used. If the source info file is specified as a relative path, then it is
9487relative to the object directory of the main project. If the source info file
9488does not exist, then after the Project Manager has successfully parsed and
9489processed the project files and found the sources, it creates the source info
9490file. If the source info file already exists and can be read successfully,
9491then the Project Manager will get all the needed information about the sources
9492from the source info file and will not look for them. This reduces the time
9493to process the project files, especially when looking for sources that take a
9494long time. If the source info file exists but cannot be parsed successfully,
9495the Project Manager will attempt to recreate it. If the Project Manager fails
9496to create the source info file, a message is issued, but gnatmake does not
9497fail. @command{gnatmake} "trusts" the source info file. This means that
9498if the source files have changed (addition, deletion, moving to a different
9499source directory), then the source info file need to be deleted and recreated.
9500
9501@ifclear vms
9502@item --create-map-file
9503When linking an executable, create a map file. The name of the map file
9504has the same name as the executable with extension ".map".
9505
9506@item --create-map-file=mapfile
9507When linking an executable, create a map file. The name of the map file is
9508"mapfile".
9509
9510@end ifclear
9511
9512@item ^-a^/ALL_FILES^
9513@cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9514Consider all files in the make process, even the GNAT internal system
9515files (for example, the predefined Ada library files), as well as any
9516locked files. Locked files are files whose ALI file is write-protected.
9517By default,
9518@command{gnatmake} does not check these files,
9519because the assumption is that the GNAT internal files are properly up
9520to date, and also that any write protected ALI files have been properly
9521installed. Note that if there is an installation problem, such that one
9522of these files is not up to date, it will be properly caught by the
9523binder.
9524You may have to specify this switch if you are working on GNAT
9525itself. The switch @option{^-a^/ALL_FILES^} is also useful
9526in conjunction with @option{^-f^/FORCE_COMPILE^}
9527if you need to recompile an entire application,
9528including run-time files, using special configuration pragmas,
9529such as a @code{Normalize_Scalars} pragma.
9530
9531By default
9532@code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9533internal files with
9534@ifclear vms
9535@code{gcc -c -gnatpg} rather than @code{gcc -c}.
9536@end ifclear
9537@ifset vms
9538the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9539@end ifset
9540
9541@item ^-b^/ACTIONS=BIND^
9542@cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9543Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9544compilation and binding, but no link.
9545Can be combined with @option{^-l^/ACTIONS=LINK^}
9546to do binding and linking. When not combined with
9547@option{^-c^/ACTIONS=COMPILE^}
9548all the units in the closure of the main program must have been previously
9549compiled and must be up to date. The root unit specified by @var{file_name}
9550may be given without extension, with the source extension or, if no GNAT
9551Project File is specified, with the ALI file extension.
9552
9553@item ^-c^/ACTIONS=COMPILE^
9554@cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9555Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9556is also specified. Do not perform linking, except if both
9557@option{^-b^/ACTIONS=BIND^} and
9558@option{^-l^/ACTIONS=LINK^} are also specified.
9559If the root unit specified by @var{file_name} is not a main unit, this is the
9560default. Otherwise @command{gnatmake} will attempt binding and linking
9561unless all objects are up to date and the executable is more recent than
9562the objects.
9563
9564@item ^-C^/MAPPING^
9565@cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9566Use a temporary mapping file. A mapping file is a way to communicate
9567to the compiler two mappings: from unit names to file names (without
9568any directory information) and from file names to path names (with
9569full directory information). A mapping file can make the compiler's
9570file searches faster, especially if there are many source directories,
9571or the sources are read over a slow network connection. If
9572@option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9573@option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9574is initially populated based on the project file. If
9575@option{^-C^/MAPPING^} is used without
9576@option{^-P^/PROJECT_FILE^},
9577the mapping file is initially empty. Each invocation of the compiler
9578will add any newly accessed sources to the mapping file.
9579
9580@item ^-C=^/USE_MAPPING_FILE=^@var{file}
9581@cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9582Use a specific mapping file. The file, specified as a path name (absolute or
9583relative) by this switch, should already exist, otherwise the switch is
9584ineffective. The specified mapping file will be communicated to the compiler.
9585This switch is not compatible with a project file
9586(^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9587(^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9588
9589@item ^-d^/DISPLAY_PROGRESS^
9590@cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9591Display progress for each source, up to date or not, as a single line
9592
9593@smallexample
9594completed x out of y (zz%)
9595@end smallexample
9596
9597If the file needs to be compiled this is displayed after the invocation of
9598the compiler. These lines are displayed even in quiet output mode.
9599
9600@item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9601@cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9602Put all object files and ALI file in directory @var{dir}.
9603If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9604and ALI files go in the current working directory.
9605
9606This switch cannot be used when using a project file.
9607
9608@item -eInnn
9609@cindex @option{-eI} (@command{gnatmake})
9610Indicates that the main source is a multi-unit source and the rank of the unit
9611in the source file is nnn. nnn needs to be a positive number and a valid
9612index in the source. This switch cannot be used when @command{gnatmake} is
9613invoked for several mains.
9614
9615@ifclear vms
9616@item -eL
9617@cindex @option{-eL} (@command{gnatmake})
9618@cindex symbolic links
9619Follow all symbolic links when processing project files.
9620This should be used if your project uses symbolic links for files or
9621directories, but is not needed in other cases.
9622
9623@cindex naming scheme
9624This also assumes that no directory matches the naming scheme for files (for
9625instance that you do not have a directory called "sources.ads" when using the
9626default GNAT naming scheme).
9627
9628When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9629save a lot of system calls (several per source file and object file), which
9630can result in a significant speed up to load and manipulate a project file,
9631especially when using source files from a remote system.
9632
9633@end ifclear
9634
9635@item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9636@cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9637Output the commands for the compiler, the binder and the linker
9638on ^standard output^SYS$OUTPUT^,
9639instead of ^standard error^SYS$ERROR^.
9640
9641@item ^-f^/FORCE_COMPILE^
9642@cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9643Force recompilations. Recompile all sources, even though some object
9644files may be up to date, but don't recompile predefined or GNAT internal
9645files or locked files (files with a write-protected ALI file),
9646unless the @option{^-a^/ALL_FILES^} switch is also specified.
9647
9648@item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9649@cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9650When using project files, if some errors or warnings are detected during
9651parsing and verbose mode is not in effect (no use of switch
9652^-v^/VERBOSE^), then error lines start with the full path name of the project
9653file, rather than its simple file name.
9654
9655@item ^-g^/DEBUG^
9656@cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9657Enable debugging. This switch is simply passed to the compiler and to the
9658linker.
9659
9660@item ^-i^/IN_PLACE^
9661@cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9662In normal mode, @command{gnatmake} compiles all object files and ALI files
9663into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9664then instead object files and ALI files that already exist are overwritten
9665in place. This means that once a large project is organized into separate
9666directories in the desired manner, then @command{gnatmake} will automatically
9667maintain and update this organization. If no ALI files are found on the
9668Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9669the new object and ALI files are created in the
9670directory containing the source being compiled. If another organization
9671is desired, where objects and sources are kept in different directories,
9672a useful technique is to create dummy ALI files in the desired directories.
9673When detecting such a dummy file, @command{gnatmake} will be forced to
9674recompile the corresponding source file, and it will be put the resulting
9675object and ALI files in the directory where it found the dummy file.
9676
9677@item ^-j^/PROCESSES=^@var{n}
9678@cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9679@cindex Parallel make
9680Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9681machine compilations will occur in parallel. If @var{n} is 0, then the
9682maximum number of parallel compilations is the number of core processors
9683on the platform. In the event of compilation errors, messages from various
9684compilations might get interspersed (but @command{gnatmake} will give you the
9685full ordered list of failing compiles at the end). If this is problematic,
9686rerun the make process with n set to 1 to get a clean list of messages.
9687
9688@item ^-k^/CONTINUE_ON_ERROR^
9689@cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9690Keep going. Continue as much as possible after a compilation error. To
9691ease the programmer's task in case of compilation errors, the list of
9692sources for which the compile fails is given when @command{gnatmake}
9693terminates.
9694
9695If @command{gnatmake} is invoked with several @file{file_names} and with this
9696switch, if there are compilation errors when building an executable,
9697@command{gnatmake} will not attempt to build the following executables.
9698
9699@item ^-l^/ACTIONS=LINK^
9700@cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9701Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9702and linking. Linking will not be performed if combined with
9703@option{^-c^/ACTIONS=COMPILE^}
9704but not with @option{^-b^/ACTIONS=BIND^}.
9705When not combined with @option{^-b^/ACTIONS=BIND^}
9706all the units in the closure of the main program must have been previously
9707compiled and must be up to date, and the main program needs to have been bound.
9708The root unit specified by @var{file_name}
9709may be given without extension, with the source extension or, if no GNAT
9710Project File is specified, with the ALI file extension.
9711
9712@item ^-m^/MINIMAL_RECOMPILATION^
9713@cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9714Specify that the minimum necessary amount of recompilations
9715be performed. In this mode @command{gnatmake} ignores time
9716stamp differences when the only
9717modifications to a source file consist in adding/removing comments,
9718empty lines, spaces or tabs. This means that if you have changed the
9719comments in a source file or have simply reformatted it, using this
9720switch will tell @command{gnatmake} not to recompile files that depend on it
9721(provided other sources on which these files depend have undergone no
9722semantic modifications). Note that the debugging information may be
9723out of date with respect to the sources if the @option{-m} switch causes
9724a compilation to be switched, so the use of this switch represents a
9725trade-off between compilation time and accurate debugging information.
9726
9727@item ^-M^/DEPENDENCIES_LIST^
9728@cindex Dependencies, producing list
9729@cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9730Check if all objects are up to date. If they are, output the object
9731dependences to @file{stdout} in a form that can be directly exploited in
9732a @file{Makefile}. By default, each source file is prefixed with its
9733(relative or absolute) directory name. This name is whatever you
9734specified in the various @option{^-aI^/SOURCE_SEARCH^}
9735and @option{^-I^/SEARCH^} switches. If you use
9736@code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9737@option{^-q^/QUIET^}
9738(see below), only the source file names,
9739without relative paths, are output. If you just specify the
9740@option{^-M^/DEPENDENCIES_LIST^}
9741switch, dependencies of the GNAT internal system files are omitted. This
9742is typically what you want. If you also specify
9743the @option{^-a^/ALL_FILES^} switch,
9744dependencies of the GNAT internal files are also listed. Note that
9745dependencies of the objects in external Ada libraries (see switch
9746@option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9747are never reported.
9748
9749@item ^-n^/DO_OBJECT_CHECK^
9750@cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9751Don't compile, bind, or link. Checks if all objects are up to date.
9752If they are not, the full name of the first file that needs to be
9753recompiled is printed.
9754Repeated use of this option, followed by compiling the indicated source
9755file, will eventually result in recompiling all required units.
9756
9757@item ^-o ^/EXECUTABLE=^@var{exec_name}
9758@cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9759Output executable name. The name of the final executable program will be
9760@var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9761name for the executable will be the name of the input file in appropriate form
9762for an executable file on the host system.
9763
9764This switch cannot be used when invoking @command{gnatmake} with several
9765@file{file_names}.
9766
9767@item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9768@cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9769When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9770automatically missing object directories, library directories and exec
9771directories.
9772
9773@item ^-P^/PROJECT_FILE=^@var{project}
9774@cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9775Use project file @var{project}. Only one such switch can be used.
9776@xref{gnatmake and Project Files}.
9777
9778@item ^-q^/QUIET^
9779@cindex @option{^-q^/QUIET^} (@command{gnatmake})
9780Quiet. When this flag is not set, the commands carried out by
9781@command{gnatmake} are displayed.
9782
9783@item ^-s^/SWITCH_CHECK/^
9784@cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9785Recompile if compiler switches have changed since last compilation.
9786All compiler switches but -I and -o are taken into account in the
9787following way:
9788orders between different ``first letter'' switches are ignored, but
9789orders between same switches are taken into account. For example,
9790@option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9791is equivalent to @option{-O -g}.
9792
9793This switch is recommended when Integrated Preprocessing is used.
9794
9795@item ^-u^/UNIQUE^
9796@cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9797Unique. Recompile at most the main files. It implies -c. Combined with
9798-f, it is equivalent to calling the compiler directly. Note that using
9799^-u^/UNIQUE^ with a project file and no main has a special meaning
9800(@pxref{Project Files and Main Subprograms}).
9801
9802@item ^-U^/ALL_PROJECTS^
9803@cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9804When used without a project file or with one or several mains on the command
9805line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9806on the command line, all sources of all project files are checked and compiled
9807if not up to date, and libraries are rebuilt, if necessary.
9808
9809@item ^-v^/REASONS^
9810@cindex @option{^-v^/REASONS^} (@command{gnatmake})
9811Verbose. Display the reason for all recompilations @command{gnatmake}
9812decides are necessary, with the highest verbosity level.
9813
9814@item ^-vl^/LOW_VERBOSITY^
9815@cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9816Verbosity level Low. Display fewer lines than in verbosity Medium.
9817
9818@item ^-vm^/MEDIUM_VERBOSITY^
9819@cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9820Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9821
9822@item ^-vh^/HIGH_VERBOSITY^
9823@cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9824Verbosity level High. Equivalent to ^-v^/REASONS^.
9825
9826@item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9827Indicate the verbosity of the parsing of GNAT project files.
9828@xref{Switches Related to Project Files}.
9829
9830@item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9831@cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9832Indicate that sources that are not part of any Project File may be compiled.
9833Normally, when using Project Files, only sources that are part of a Project
9834File may be compile. When this switch is used, a source outside of all Project
9835Files may be compiled. The ALI file and the object file will be put in the
9836object directory of the main Project. The compilation switches used will only
9837be those specified on the command line. Even when
9838@option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9839command line need to be sources of a project file.
9840
9841@item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9842Indicate that external variable @var{name} has the value @var{value}.
9843The Project Manager will use this value for occurrences of
9844@code{external(name)} when parsing the project file.
9845@xref{Switches Related to Project Files}.
9846
9847@item ^-z^/NOMAIN^
9848@cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9849No main subprogram. Bind and link the program even if the unit name
9850given on the command line is a package name. The resulting executable
9851will execute the elaboration routines of the package and its closure,
9852then the finalization routines.
9853
9854@end table
9855
9856@table @asis
9857@item @command{gcc} @asis{switches}
9858@ifclear vms
9859Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9860is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9861@end ifclear
9862@ifset vms
9863Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9864but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9865automatically treated as a compiler switch, and passed on to all
9866compilations that are carried out.
9867@end ifset
9868@end table
9869
9870@noindent
9871Source and library search path switches:
9872
9873@table @option
9874@c !sort!
9875@item ^-aI^/SOURCE_SEARCH=^@var{dir}
9876@cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9877When looking for source files also look in directory @var{dir}.
9878The order in which source files search is undertaken is
9879described in @ref{Search Paths and the Run-Time Library (RTL)}.
9880
9881@item ^-aL^/SKIP_MISSING=^@var{dir}
9882@cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9883Consider @var{dir} as being an externally provided Ada library.
9884Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9885files have been located in directory @var{dir}. This allows you to have
9886missing bodies for the units in @var{dir} and to ignore out of date bodies
9887for the same units. You still need to specify
9888the location of the specs for these units by using the switches
9889@option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9890or @option{^-I^/SEARCH=^@var{dir}}.
9891Note: this switch is provided for compatibility with previous versions
9892of @command{gnatmake}. The easier method of causing standard libraries
9893to be excluded from consideration is to write-protect the corresponding
9894ALI files.
9895
9896@item ^-aO^/OBJECT_SEARCH=^@var{dir}
9897@cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9898When searching for library and object files, look in directory
9899@var{dir}. The order in which library files are searched is described in
9900@ref{Search Paths for gnatbind}.
9901
9902@item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9903@cindex Search paths, for @command{gnatmake}
9904@cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9905Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9906^-aI^/SOURCE_SEARCH=^@var{dir}}.
9907
9908@item ^-I^/SEARCH=^@var{dir}
9909@cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9910Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9911^-aI^/SOURCE_SEARCH=^@var{dir}}.
9912
9913@item ^-I-^/NOCURRENT_DIRECTORY^
9914@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9915@cindex Source files, suppressing search
9916Do not look for source files in the directory containing the source
9917file named in the command line.
9918Do not look for ALI or object files in the directory
9919where @command{gnatmake} was invoked.
9920
9921@item ^-L^/LIBRARY_SEARCH=^@var{dir}
9922@cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9923@cindex Linker libraries
9924Add directory @var{dir} to the list of directories in which the linker
9925will search for libraries. This is equivalent to
9926@option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9927@ifclear vms
9928Furthermore, under Windows, the sources pointed to by the libraries path
9929set in the registry are not searched for.
9930@end ifclear
9931
9932@item -nostdinc
9933@cindex @option{-nostdinc} (@command{gnatmake})
9934Do not look for source files in the system default directory.
9935
9936@item -nostdlib
9937@cindex @option{-nostdlib} (@command{gnatmake})
9938Do not look for library files in the system default directory.
9939
9940@item --RTS=@var{rts-path}
9941@cindex @option{--RTS} (@command{gnatmake})
9942Specifies the default location of the runtime library. GNAT looks for the
9943runtime
9944in the following directories, and stops as soon as a valid runtime is found
9945(@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9946@file{ada_object_path} present):
9947
9948@itemize @bullet
9949@item <current directory>/$rts_path
9950
9951@item <default-search-dir>/$rts_path
9952
9953@item <default-search-dir>/rts-$rts_path
9954@end itemize
9955
9956@noindent
9957The selected path is handled like a normal RTS path.
9958
9959@end table
9960
9961@node Mode Switches for gnatmake
9962@section Mode Switches for @command{gnatmake}
9963
9964@noindent
9965The mode switches (referred to as @code{mode_switches}) allow the
9966inclusion of switches that are to be passed to the compiler itself, the
9967binder or the linker. The effect of a mode switch is to cause all
9968subsequent switches up to the end of the switch list, or up to the next
9969mode switch, to be interpreted as switches to be passed on to the
9970designated component of GNAT.
9971
9972@table @option
9973@c !sort!
9974@item -cargs @var{switches}
9975@cindex @option{-cargs} (@command{gnatmake})
9976Compiler switches. Here @var{switches} is a list of switches
9977that are valid switches for @command{gcc}. They will be passed on to
9978all compile steps performed by @command{gnatmake}.
9979
9980@item -bargs @var{switches}
9981@cindex @option{-bargs} (@command{gnatmake})
9982Binder switches. Here @var{switches} is a list of switches
9983that are valid switches for @code{gnatbind}. They will be passed on to
9984all bind steps performed by @command{gnatmake}.
9985
9986@item -largs @var{switches}
9987@cindex @option{-largs} (@command{gnatmake})
9988Linker switches. Here @var{switches} is a list of switches
9989that are valid switches for @command{gnatlink}. They will be passed on to
9990all link steps performed by @command{gnatmake}.
9991
9992@item -margs @var{switches}
9993@cindex @option{-margs} (@command{gnatmake})
9994Make switches. The switches are directly interpreted by @command{gnatmake},
9995regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9996or @option{-largs}.
9997@end table
9998
9999@node Notes on the Command Line
10000@section Notes on the Command Line
10001
10002@noindent
10003This section contains some additional useful notes on the operation
10004of the @command{gnatmake} command.
10005
10006@itemize @bullet
10007@item
10008@cindex Recompilation, by @command{gnatmake}
10009If @command{gnatmake} finds no ALI files, it recompiles the main program
10010and all other units required by the main program.
10011This means that @command{gnatmake}
10012can be used for the initial compile, as well as during subsequent steps of
10013the development cycle.
10014
10015@item
10016If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10017is a subunit or body of a generic unit, @command{gnatmake} recompiles
10018@file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10019warning.
10020
10021@item
10022In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10023is used to specify both source and
10024library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10025instead if you just want to specify
10026source paths only and @option{^-aO^/OBJECT_SEARCH^}
10027if you want to specify library paths
10028only.
10029
10030@item
10031@command{gnatmake} will ignore any files whose ALI file is write-protected.
10032This may conveniently be used to exclude standard libraries from
10033consideration and in particular it means that the use of the
10034@option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10035unless @option{^-a^/ALL_FILES^} is also specified.
10036
10037@item
10038@command{gnatmake} has been designed to make the use of Ada libraries
10039particularly convenient. Assume you have an Ada library organized
10040as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10041of your Ada compilation units,
10042whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10043specs of these units, but no bodies. Then to compile a unit
10044stored in @code{main.adb}, which uses this Ada library you would just type
10045
10046@smallexample
10047@ifclear vms
10048$ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
10049@end ifclear
10050@ifset vms
10051$ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10052           /SKIP_MISSING=@i{[OBJ_DIR]} main
10053@end ifset
10054@end smallexample
10055
10056@item
10057Using @command{gnatmake} along with the
10058@option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10059switch provides a mechanism for avoiding unnecessary recompilations. Using
10060this switch,
10061you can update the comments/format of your
10062source files without having to recompile everything. Note, however, that
10063adding or deleting lines in a source files may render its debugging
10064info obsolete. If the file in question is a spec, the impact is rather
10065limited, as that debugging info will only be useful during the
10066elaboration phase of your program. For bodies the impact can be more
10067significant. In all events, your debugger will warn you if a source file
10068is more recent than the corresponding object, and alert you to the fact
10069that the debugging information may be out of date.
10070@end itemize
10071
10072@node How gnatmake Works
10073@section How @command{gnatmake} Works
10074
10075@noindent
10076Generally @command{gnatmake} automatically performs all necessary
10077recompilations and you don't need to worry about how it works. However,
10078it may be useful to have some basic understanding of the @command{gnatmake}
10079approach and in particular to understand how it uses the results of
10080previous compilations without incorrectly depending on them.
10081
10082First a definition: an object file is considered @dfn{up to date} if the
10083corresponding ALI file exists and if all the source files listed in the
10084dependency section of this ALI file have time stamps matching those in
10085the ALI file. This means that neither the source file itself nor any
10086files that it depends on have been modified, and hence there is no need
10087to recompile this file.
10088
10089@command{gnatmake} works by first checking if the specified main unit is up
10090to date. If so, no compilations are required for the main unit. If not,
10091@command{gnatmake} compiles the main program to build a new ALI file that
10092reflects the latest sources. Then the ALI file of the main unit is
10093examined to find all the source files on which the main program depends,
10094and @command{gnatmake} recursively applies the above procedure on all these
10095files.
10096
10097This process ensures that @command{gnatmake} only trusts the dependencies
10098in an existing ALI file if they are known to be correct. Otherwise it
10099always recompiles to determine a new, guaranteed accurate set of
10100dependencies. As a result the program is compiled ``upside down'' from what may
10101be more familiar as the required order of compilation in some other Ada
10102systems. In particular, clients are compiled before the units on which
10103they depend. The ability of GNAT to compile in any order is critical in
10104allowing an order of compilation to be chosen that guarantees that
10105@command{gnatmake} will recompute a correct set of new dependencies if
10106necessary.
10107
10108When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10109imported by several of the executables, it will be recompiled at most once.
10110
10111Note: when using non-standard naming conventions
10112(@pxref{Using Other File Names}), changing through a configuration pragmas
10113file the version of a source and invoking @command{gnatmake} to recompile may
10114have no effect, if the previous version of the source is still accessible
10115by @command{gnatmake}. It may be necessary to use the switch
10116^-f^/FORCE_COMPILE^.
10117
10118@node Examples of gnatmake Usage
10119@section Examples of @command{gnatmake} Usage
10120
10121@table @code
10122@item gnatmake hello.adb
10123Compile all files necessary to bind and link the main program
10124@file{hello.adb} (containing unit @code{Hello}) and bind and link the
10125resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10126
10127@item gnatmake main1 main2 main3
10128Compile all files necessary to bind and link the main programs
10129@file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10130(containing unit @code{Main2}) and @file{main3.adb}
10131(containing unit @code{Main3}) and bind and link the resulting object files
10132to generate three executable files @file{^main1^MAIN1.EXE^},
10133@file{^main2^MAIN2.EXE^}
10134and @file{^main3^MAIN3.EXE^}.
10135
10136@ifclear vms
10137@item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10138@end ifclear
10139
10140@ifset vms
10141@item gnatmake Main_Unit /QUIET
10142/COMPILER_QUALIFIERS /OPTIMIZE=ALL
10143/BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10144@end ifset
10145Compile all files necessary to bind and link the main program unit
10146@code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10147be done with optimization level 2 and the order of elaboration will be
10148listed by the binder. @command{gnatmake} will operate in quiet mode, not
10149displaying commands it is executing.
10150@end table
10151
10152@c *************************
10153@node Improving Performance
10154@chapter Improving Performance
10155@cindex Improving performance
10156
10157@noindent
10158This chapter presents several topics related to program performance.
10159It first describes some of the tradeoffs that need to be considered
10160and some of the techniques for making your program run faster.
10161It then documents
10162@ifclear FSFEDITION
10163the @command{gnatelim} tool and
10164@end ifclear
10165unused subprogram/data
10166elimination feature, which can reduce the size of program executables.
10167
10168@ifnottex
10169@menu
10170* Performance Considerations::
10171* Text_IO Suggestions::
10172@ifclear FSFEDITION
10173* Reducing Size of Ada Executables with gnatelim::
10174@end ifclear
10175* Reducing Size of Executables with unused subprogram/data elimination::
10176@end menu
10177@end ifnottex
10178
10179@c *****************************
10180@node Performance Considerations
10181@section Performance Considerations
10182
10183@noindent
10184The GNAT system provides a number of options that allow a trade-off
10185between
10186
10187@itemize @bullet
10188@item
10189performance of the generated code
10190
10191@item
10192speed of compilation
10193
10194@item
10195minimization of dependences and recompilation
10196
10197@item
10198the degree of run-time checking.
10199@end itemize
10200
10201@noindent
10202The defaults (if no options are selected) aim at improving the speed
10203of compilation and minimizing dependences, at the expense of performance
10204of the generated code:
10205
10206@itemize @bullet
10207@item
10208no optimization
10209
10210@item
10211no inlining of subprogram calls
10212
10213@item
10214all run-time checks enabled except overflow and elaboration checks
10215@end itemize
10216
10217@noindent
10218These options are suitable for most program development purposes. This
10219chapter describes how you can modify these choices, and also provides
10220some guidelines on debugging optimized code.
10221
10222@menu
10223* Controlling Run-Time Checks::
10224* Use of Restrictions::
10225* Optimization Levels::
10226* Debugging Optimized Code::
10227* Inlining of Subprograms::
10228* Vectorization of loops::
10229* Other Optimization Switches::
10230* Optimization and Strict Aliasing::
10231* Aliased Variables and Optimization::
10232* Atomic Variables and Optimization::
10233* Passive Task Optimization::
10234
10235@ifset vms
10236* Coverage Analysis::
10237@end ifset
10238@end menu
10239
10240@node Controlling Run-Time Checks
10241@subsection Controlling Run-Time Checks
10242
10243@noindent
10244By default, GNAT generates all run-time checks, except integer overflow
10245checks, stack overflow checks, and checks for access before elaboration on
10246subprogram calls. The latter are not required in default mode, because all
10247necessary checking is done at compile time.
10248@cindex @option{-gnatp} (@command{gcc})
10249@cindex @option{-gnato} (@command{gcc})
10250Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10251be modified. @xref{Run-Time Checks}.
10252
10253Our experience is that the default is suitable for most development
10254purposes.
10255
10256We treat integer overflow specially because these
10257are quite expensive and in our experience are not as important as other
10258run-time checks in the development process. Note that division by zero
10259is not considered an overflow check, and divide by zero checks are
10260generated where required by default.
10261
10262Elaboration checks are off by default, and also not needed by default, since
10263GNAT uses a static elaboration analysis approach that avoids the need for
10264run-time checking. This manual contains a full chapter discussing the issue
10265of elaboration checks, and if the default is not satisfactory for your use,
10266you should read this chapter.
10267
10268For validity checks, the minimal checks required by the Ada Reference
10269Manual (for case statements and assignments to array elements) are on
10270by default. These can be suppressed by use of the @option{-gnatVn} switch.
10271Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10272is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10273it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10274are also suppressed entirely if @option{-gnatp} is used.
10275
10276@cindex Overflow checks
10277@cindex Checks, overflow
10278@findex Suppress
10279@findex Unsuppress
10280@cindex pragma Suppress
10281@cindex pragma Unsuppress
10282Note that the setting of the switches controls the default setting of
10283the checks. They may be modified using either @code{pragma Suppress} (to
10284remove checks) or @code{pragma Unsuppress} (to add back suppressed
10285checks) in the program source.
10286
10287@node Use of Restrictions
10288@subsection Use of Restrictions
10289
10290@noindent
10291The use of pragma Restrictions allows you to control which features are
10292permitted in your program. Apart from the obvious point that if you avoid
10293relatively expensive features like finalization (enforceable by the use
10294of pragma Restrictions (No_Finalization), the use of this pragma does not
10295affect the generated code in most cases.
10296
10297One notable exception to this rule is that the possibility of task abort
10298results in some distributed overhead, particularly if finalization or
10299exception handlers are used. The reason is that certain sections of code
10300have to be marked as non-abortable.
10301
10302If you use neither the @code{abort} statement, nor asynchronous transfer
10303of control (@code{select @dots{} then abort}), then this distributed overhead
10304is removed, which may have a general positive effect in improving
10305overall performance.  Especially code involving frequent use of tasking
10306constructs and controlled types will show much improved performance.
10307The relevant restrictions pragmas are
10308
10309@smallexample @c ada
10310   pragma Restrictions (No_Abort_Statements);
10311   pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10312@end smallexample
10313
10314@noindent
10315It is recommended that these restriction pragmas be used if possible. Note
10316that this also means that you can write code without worrying about the
10317possibility of an immediate abort at any point.
10318
10319@node Optimization Levels
10320@subsection Optimization Levels
10321@cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10322
10323@noindent
10324Without any optimization ^option,^qualifier,^
10325the compiler's goal is to reduce the cost of
10326compilation and to make debugging produce the expected results.
10327Statements are independent: if you stop the program with a breakpoint between
10328statements, you can then assign a new value to any variable or change
10329the program counter to any other statement in the subprogram and get exactly
10330the results you would expect from the source code.
10331
10332Turning on optimization makes the compiler attempt to improve the
10333performance and/or code size at the expense of compilation time and
10334possibly the ability to debug the program.
10335
10336If you use multiple
10337^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10338the last such option is the one that is effective.
10339
10340@noindent
10341The default is optimization off. This results in the fastest compile
10342times, but GNAT makes absolutely no attempt to optimize, and the
10343generated programs are considerably larger and slower than when
10344optimization is enabled. You can use the
10345@ifclear vms
10346@option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10347@option{-O2}, @option{-O3}, and @option{-Os})
10348@end ifclear
10349@ifset vms
10350@code{OPTIMIZE} qualifier
10351@end ifset
10352to @command{gcc} to control the optimization level:
10353
10354@table @option
10355@item ^-O0^/OPTIMIZE=NONE^
10356No optimization (the default);
10357generates unoptimized code but has
10358the fastest compilation time.
10359
10360Note that many other compilers do fairly extensive optimization
10361even if ``no optimization'' is specified. With gcc, it is
10362very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10363execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10364really does mean no optimization at all. This difference between
10365gcc and other compilers should be kept in mind when doing
10366performance comparisons.
10367
10368@item ^-O1^/OPTIMIZE=SOME^
10369Moderate optimization;
10370optimizes reasonably well but does not
10371degrade compilation time significantly.
10372
10373@item ^-O2^/OPTIMIZE=ALL^
10374@ifset vms
10375@itemx /OPTIMIZE=DEVELOPMENT
10376@end ifset
10377Full optimization;
10378generates highly optimized code and has
10379the slowest compilation time.
10380
10381@item ^-O3^/OPTIMIZE=INLINING^
10382Full optimization as in @option{-O2};
10383also uses more aggressive automatic inlining of subprograms within a unit
10384(@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10385
10386@item ^-Os^/OPTIMIZE=SPACE^
10387Optimize space usage (code and data) of resulting program.
10388@end table
10389
10390@noindent
10391Higher optimization levels perform more global transformations on the
10392program and apply more expensive analysis algorithms in order to generate
10393faster and more compact code. The price in compilation time, and the
10394resulting improvement in execution time,
10395both depend on the particular application and the hardware environment.
10396You should experiment to find the best level for your application.
10397
10398Since the precise set of optimizations done at each level will vary from
10399release to release (and sometime from target to target), it is best to think
10400of the optimization settings in general terms.
10401@xref{Optimize Options,, Options That Control Optimization, gcc, Using
10402the GNU Compiler Collection (GCC)}, for details about
10403^the @option{-O} settings and a number of @option{-f} options that^how to^
10404individually enable or disable specific optimizations.
10405
10406Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10407been tested extensively at all optimization levels. There are some bugs
10408which appear only with optimization turned on, but there have also been
10409bugs which show up only in @emph{unoptimized} code. Selecting a lower
10410level of optimization does not improve the reliability of the code
10411generator, which in practice is highly reliable at all optimization
10412levels.
10413
10414Note regarding the use of @option{-O3}: The use of this optimization level
10415is generally discouraged with GNAT, since it often results in larger
10416executables which may run more slowly. See further discussion of this point
10417in @ref{Inlining of Subprograms}.
10418
10419@node Debugging Optimized Code
10420@subsection Debugging Optimized Code
10421@cindex Debugging optimized code
10422@cindex Optimization and debugging
10423
10424@noindent
10425Although it is possible to do a reasonable amount of debugging at
10426@ifclear vms
10427nonzero optimization levels,
10428the higher the level the more likely that
10429@end ifclear
10430@ifset vms
10431@option{/OPTIMIZE} settings other than @code{NONE},
10432such settings will make it more likely that
10433@end ifset
10434source-level constructs will have been eliminated by optimization.
10435For example, if a loop is strength-reduced, the loop
10436control variable may be completely eliminated and thus cannot be
10437displayed in the debugger.
10438This can only happen at @option{-O2} or @option{-O3}.
10439Explicit temporary variables that you code might be eliminated at
10440^level^setting^ @option{-O1} or higher.
10441
10442The use of the @option{^-g^/DEBUG^} switch,
10443@cindex @option{^-g^/DEBUG^} (@command{gcc})
10444which is needed for source-level debugging,
10445affects the size of the program executable on disk,
10446and indeed the debugging information can be quite large.
10447However, it has no effect on the generated code (and thus does not
10448degrade performance)
10449
10450Since the compiler generates debugging tables for a compilation unit before
10451it performs optimizations, the optimizing transformations may invalidate some
10452of the debugging data.  You therefore need to anticipate certain
10453anomalous situations that may arise while debugging optimized code.
10454These are the most common cases:
10455
10456@enumerate
10457@item
10458@i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10459commands show
10460the PC bouncing back and forth in the code.  This may result from any of
10461the following optimizations:
10462
10463@itemize @bullet
10464@item
10465@i{Common subexpression elimination:} using a single instance of code for a
10466quantity that the source computes several times.  As a result you
10467may not be able to stop on what looks like a statement.
10468
10469@item
10470@i{Invariant code motion:} moving an expression that does not change within a
10471loop, to the beginning of the loop.
10472
10473@item
10474@i{Instruction scheduling:} moving instructions so as to
10475overlap loads and stores (typically) with other code, or in
10476general to move computations of values closer to their uses. Often
10477this causes you to pass an assignment statement without the assignment
10478happening and then later bounce back to the statement when the
10479value is actually needed.  Placing a breakpoint on a line of code
10480and then stepping over it may, therefore, not always cause all the
10481expected side-effects.
10482@end itemize
10483
10484@item
10485@i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10486two identical pieces of code are merged and the program counter suddenly
10487jumps to a statement that is not supposed to be executed, simply because
10488it (and the code following) translates to the same thing as the code
10489that @emph{was} supposed to be executed.  This effect is typically seen in
10490sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10491a @code{break} in a C @code{^switch^switch^} statement.
10492
10493@item
10494@i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10495There are various reasons for this effect:
10496
10497@itemize @bullet
10498@item
10499In a subprogram prologue, a parameter may not yet have been moved to its
10500``home''.
10501
10502@item
10503A variable may be dead, and its register re-used.  This is
10504probably the most common cause.
10505
10506@item
10507As mentioned above, the assignment of a value to a variable may
10508have been moved.
10509
10510@item
10511A variable may be eliminated entirely by value propagation or
10512other means.  In this case, GCC may incorrectly generate debugging
10513information for the variable
10514@end itemize
10515
10516@noindent
10517In general, when an unexpected value appears for a local variable or parameter
10518you should first ascertain if that value was actually computed by
10519your program, as opposed to being incorrectly reported by the debugger.
10520Record fields or
10521array elements in an object designated by an access value
10522are generally less of a problem, once you have ascertained that the access
10523value is sensible.
10524Typically, this means checking variables in the preceding code and in the
10525calling subprogram to verify that the value observed is explainable from other
10526values (one must apply the procedure recursively to those
10527other values); or re-running the code and stopping a little earlier
10528(perhaps before the call) and stepping to better see how the variable obtained
10529the value in question; or continuing to step @emph{from} the point of the
10530strange value to see if code motion had simply moved the variable's
10531assignments later.
10532@end enumerate
10533
10534@noindent
10535In light of such anomalies, a recommended technique is to use @option{-O0}
10536early in the software development cycle, when extensive debugging capabilities
10537are most needed, and then move to @option{-O1} and later @option{-O2} as
10538the debugger becomes less critical.
10539Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10540a release management issue.
10541@ifclear vms
10542Note that if you use @option{-g} you can then use the @command{strip} program
10543on the resulting executable,
10544which removes both debugging information and global symbols.
10545@end ifclear
10546
10547@node Inlining of Subprograms
10548@subsection Inlining of Subprograms
10549
10550@noindent
10551A call to a subprogram in the current unit is inlined if all the
10552following conditions are met:
10553
10554@itemize @bullet
10555@item
10556The optimization level is at least @option{-O1}.
10557
10558@item
10559The called subprogram is suitable for inlining: It must be small enough
10560and not contain something that @command{gcc} cannot support in inlined
10561subprograms.
10562
10563@item
10564@cindex pragma Inline
10565@findex Inline
10566Any one of the following applies: @code{pragma Inline} is applied to the
10567subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10568subprogram is local to the unit and called once from within it; the
10569subprogram is small and optimization level @option{-O2} is specified;
10570optimization level @option{-O3} is specified.
10571@end itemize
10572
10573@noindent
10574Calls to subprograms in @code{with}'ed units are normally not inlined.
10575To achieve actual inlining (that is, replacement of the call by the code
10576in the body of the subprogram), the following conditions must all be true:
10577
10578@itemize @bullet
10579@item
10580The optimization level is at least @option{-O1}.
10581
10582@item
10583The called subprogram is suitable for inlining: It must be small enough
10584and not contain something that @command{gcc} cannot support in inlined
10585subprograms.
10586
10587@item
10588The call appears in a body (not in a package spec).
10589
10590@item
10591There is a @code{pragma Inline} for the subprogram.
10592
10593@item
10594The @option{^-gnatn^/INLINE^} switch is used on the command line.
10595@end itemize
10596
10597Even if all these conditions are met, it may not be possible for
10598the compiler to inline the call, due to the length of the body,
10599or features in the body that make it impossible for the compiler
10600to do the inlining.
10601
10602Note that specifying the @option{-gnatn} switch causes additional
10603compilation dependencies. Consider the following:
10604
10605@smallexample @c ada
10606@cartouche
10607package R is
10608   procedure Q;
10609   pragma Inline (Q);
10610end R;
10611package body R is
10612   @dots{}
10613end R;
10614
10615with R;
10616procedure Main is
10617begin
10618   @dots{}
10619   R.Q;
10620end Main;
10621@end cartouche
10622@end smallexample
10623
10624@noindent
10625With the default behavior (no @option{-gnatn} switch specified), the
10626compilation of the @code{Main} procedure depends only on its own source,
10627@file{main.adb}, and the spec of the package in file @file{r.ads}. This
10628means that editing the body of @code{R} does not require recompiling
10629@code{Main}.
10630
10631On the other hand, the call @code{R.Q} is not inlined under these
10632circumstances. If the @option{-gnatn} switch is present when @code{Main}
10633is compiled, the call will be inlined if the body of @code{Q} is small
10634enough, but now @code{Main} depends on the body of @code{R} in
10635@file{r.adb} as well as on the spec. This means that if this body is edited,
10636the main program must be recompiled. Note that this extra dependency
10637occurs whether or not the call is in fact inlined by @command{gcc}.
10638
10639The use of front end inlining with @option{-gnatN} generates similar
10640additional dependencies.
10641
10642@cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10643Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10644can be used to prevent
10645all inlining. This switch overrides all other conditions and ensures
10646that no inlining occurs. The extra dependences resulting from
10647@option{-gnatn} will still be active, even if
10648this switch is used to suppress the resulting inlining actions.
10649
10650@cindex @option{-fno-inline-functions} (@command{gcc})
10651Note: The @option{-fno-inline-functions} switch can be used to prevent
10652automatic inlining of subprograms if @option{-O3} is used.
10653
10654@cindex @option{-fno-inline-small-functions} (@command{gcc})
10655Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10656automatic inlining of small subprograms if @option{-O2} is used.
10657
10658@cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10659Note: The @option{-fno-inline-functions-called-once} switch
10660can be used to prevent inlining of subprograms local to the unit
10661and called once from within it if @option{-O1} is used.
10662
10663Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10664sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10665specified in lieu of it, @option{-gnatn} being translated into one of them
10666based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10667is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10668moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10669equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10670full 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
10671effect of inlining subprograms you did not think should be inlined. We have
10672found that the use of @option{-O3} may slow down the compilation and increase
10673the code size by performing excessive inlining, leading to increased
10674instruction cache pressure from the increased code size and thus minor
10675performance improvements. So the bottom line here is that you should not
10676automatically assume that @option{-O3} is better than @option{-O2}, and
10677indeed you should use @option{-O3} only if tests show that it actually
10678improves performance for your program.
10679
10680@node Vectorization of loops
10681@subsection Vectorization of loops
10682@cindex Optimization Switches
10683
10684You can take advantage of the auto-vectorizer present in the @command{gcc}
10685back end to vectorize loops with GNAT.  The corresponding command line switch
10686is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10687and other aggressive optimizations helpful for vectorization also are enabled
10688by default at this level, using @option{-O3} directly is recommended.
10689
10690You also need to make sure that the target architecture features a supported
10691SIMD instruction set.  For example, for the x86 architecture, you should at
10692least specify @option{-msse2} to get significant vectorization (but you don't
10693need to specify it for x86-64 as it is part of the base 64-bit architecture).
10694Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10695
10696The preferred loop form for vectorization is the @code{for} iteration scheme.
10697Loops with a @code{while} iteration scheme can also be vectorized if they are
10698very simple, but the vectorizer will quickly give up otherwise.  With either
10699iteration scheme, the flow of control must be straight, in particular no
10700@code{exit} statement may appear in the loop body.  The loop may however
10701contain a single nested loop, if it can be vectorized when considered alone:
10702
10703@smallexample @c ada
10704@cartouche
10705   A : array (1..4, 1..4) of Long_Float;
10706   S : array (1..4) of Long_Float;
10707
10708   procedure Sum is
10709   begin
10710      for I in A'Range(1) loop
10711         for J in A'Range(2) loop
10712            S (I) := S (I) + A (I, J);
10713         end loop;
10714      end loop;
10715   end Sum;
10716@end cartouche
10717@end smallexample
10718
10719The vectorizable operations depend on the targeted SIMD instruction set, but
10720the adding and some of the multiplying operators are generally supported, as
10721well as the logical operators for modular types.  Note that, in the former
10722case, enabling overflow checks, for example with @option{-gnato}, totally
10723disables vectorization.  The other checks are not supposed to have the same
10724definitive effect, although compiling with @option{-gnatp} might well reveal
10725cases where some checks do thwart vectorization.
10726
10727Type conversions may also prevent vectorization if they involve semantics that
10728are not directly supported by the code generator or the SIMD instruction set.
10729A typical example is direct conversion from floating-point to integer types.
10730The solution in this case is to use the following idiom:
10731
10732@smallexample @c ada
10733   Integer (S'Truncation (F))
10734@end smallexample
10735
10736@noindent
10737if @code{S} is the subtype of floating-point object @code{F}.
10738
10739In most cases, the vectorizable loops are loops that iterate over arrays.
10740All kinds of array types are supported, i.e. constrained array types with
10741static bounds:
10742
10743@smallexample @c ada
10744   type Array_Type is array (1 .. 4) of Long_Float;
10745@end smallexample
10746
10747@noindent
10748constrained array types with dynamic bounds:
10749
10750@smallexample @c ada
10751   type Array_Type is array (1 .. Q.N) of Long_Float;
10752
10753   type Array_Type is array (Q.K .. 4) of Long_Float;
10754
10755   type Array_Type is array (Q.K .. Q.N) of Long_Float;
10756@end smallexample
10757
10758@noindent
10759or unconstrained array types:
10760
10761@smallexample @c ada
10762  type Array_Type is array (Positive range <>) of Long_Float;
10763@end smallexample
10764
10765@noindent
10766The quality of the generated code decreases when the dynamic aspect of the
10767array type increases, the worst code being generated for unconstrained array
10768types.  This is so because, the less information the compiler has about the
10769bounds of the array, the more fallback code it needs to generate in order to
10770fix things up at run time.
10771
10772It is possible to specify that a given loop should be subject to vectorization
10773preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10774
10775@smallexample @c ada
10776  pragma Loop_Optimize (Vector);
10777@end smallexample
10778
10779@noindent
10780placed immediately within the loop will convey the appropriate hint to the
10781compiler for this loop.
10782
10783@node Other Optimization Switches
10784@subsection Other Optimization Switches
10785@cindex Optimization Switches
10786
10787Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10788@command{gcc} optimization switches are potentially usable. These switches
10789have not been extensively tested with GNAT but can generally be expected
10790to work. Examples of switches in this category are @option{-funroll-loops}
10791and the various target-specific @option{-m} options (in particular, it has
10792been observed that @option{-march=xxx} can significantly improve performance
10793on appropriate machines). For full details of these switches, see
10794@ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10795the GNU Compiler Collection (GCC)}.
10796
10797@node Optimization and Strict Aliasing
10798@subsection Optimization and Strict Aliasing
10799@cindex Aliasing
10800@cindex Strict Aliasing
10801@cindex No_Strict_Aliasing
10802
10803@noindent
10804The strong typing capabilities of Ada allow an optimizer to generate
10805efficient code in situations where other languages would be forced to
10806make worst case assumptions preventing such optimizations. Consider
10807the following example:
10808
10809@smallexample @c ada
10810@cartouche
10811procedure R is
10812   type Int1 is new Integer;
10813   type Int2 is new Integer;
10814   type Int1A is access Int1;
10815   type Int2A is access Int2;
10816   Int1V : Int1A;
10817   Int2V : Int2A;
10818   @dots{}
10819
10820begin
10821   @dots{}
10822   for J in Data'Range loop
10823      if Data (J) = Int1V.all then
10824         Int2V.all := Int2V.all + 1;
10825      end if;
10826   end loop;
10827   @dots{}
10828end R;
10829@end cartouche
10830@end smallexample
10831
10832@noindent
10833In this example, since the variable @code{Int1V} can only access objects
10834of type @code{Int1}, and @code{Int2V} can only access objects of type
10835@code{Int2}, there is no possibility that the assignment to
10836@code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10837the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10838for all iterations of the loop and avoid the extra memory reference
10839required to dereference it each time through the loop.
10840
10841This kind of optimization, called strict aliasing analysis, is
10842triggered by specifying an optimization level of @option{-O2} or
10843higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10844when access values are involved.
10845
10846However, although this optimization is always correct in terms of
10847the formal semantics of the Ada Reference Manual, difficulties can
10848arise if features like @code{Unchecked_Conversion} are used to break
10849the typing system. Consider the following complete program example:
10850
10851@smallexample @c ada
10852@cartouche
10853package p1 is
10854   type int1 is new integer;
10855   type int2 is new integer;
10856   type a1 is access int1;
10857   type a2 is access int2;
10858end p1;
10859
10860with p1; use p1;
10861package p2 is
10862   function to_a2 (Input : a1) return a2;
10863end p2;
10864
10865with Unchecked_Conversion;
10866package body p2 is
10867   function to_a2 (Input : a1) return a2 is
10868      function to_a2u is
10869        new Unchecked_Conversion (a1, a2);
10870   begin
10871      return to_a2u (Input);
10872   end to_a2;
10873end p2;
10874
10875with p2; use p2;
10876with p1; use p1;
10877with Text_IO; use Text_IO;
10878procedure m is
10879   v1 : a1 := new int1;
10880   v2 : a2 := to_a2 (v1);
10881begin
10882   v1.all := 1;
10883   v2.all := 0;
10884   put_line (int1'image (v1.all));
10885end;
10886@end cartouche
10887@end smallexample
10888
10889@noindent
10890This program prints out 0 in @option{-O0} or @option{-O1}
10891mode, but it prints out 1 in @option{-O2} mode. That's
10892because in strict aliasing mode, the compiler can and
10893does assume that the assignment to @code{v2.all} could not
10894affect the value of @code{v1.all}, since different types
10895are involved.
10896
10897This behavior is not a case of non-conformance with the standard, since
10898the Ada RM specifies that an unchecked conversion where the resulting
10899bit pattern is not a correct value of the target type can result in an
10900abnormal value and attempting to reference an abnormal value makes the
10901execution of a program erroneous.  That's the case here since the result
10902does not point to an object of type @code{int2}.  This means that the
10903effect is entirely unpredictable.
10904
10905However, although that explanation may satisfy a language
10906lawyer, in practice an applications programmer expects an
10907unchecked conversion involving pointers to create true
10908aliases and the behavior of printing 1 seems plain wrong.
10909In this case, the strict aliasing optimization is unwelcome.
10910
10911Indeed the compiler recognizes this possibility, and the
10912unchecked conversion generates a warning:
10913
10914@smallexample
10915p2.adb:5:07: warning: possible aliasing problem with type "a2"
10916p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10917p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10918@end smallexample
10919
10920@noindent
10921Unfortunately the problem is recognized when compiling the body of
10922package @code{p2}, but the actual "bad" code is generated while
10923compiling the body of @code{m} and this latter compilation does not see
10924the suspicious @code{Unchecked_Conversion}.
10925
10926As implied by the warning message, there are approaches you can use to
10927avoid the unwanted strict aliasing optimization in a case like this.
10928
10929One possibility is to simply avoid the use of @option{-O2}, but
10930that is a bit drastic, since it throws away a number of useful
10931optimizations that do not involve strict aliasing assumptions.
10932
10933A less drastic approach is to compile the program using the
10934option @option{-fno-strict-aliasing}. Actually it is only the
10935unit containing the dereferencing of the suspicious pointer
10936that needs to be compiled. So in this case, if we compile
10937unit @code{m} with this switch, then we get the expected
10938value of zero printed. Analyzing which units might need
10939the switch can be painful, so a more reasonable approach
10940is to compile the entire program with options @option{-O2}
10941and @option{-fno-strict-aliasing}. If the performance is
10942satisfactory with this combination of options, then the
10943advantage is that the entire issue of possible "wrong"
10944optimization due to strict aliasing is avoided.
10945
10946To avoid the use of compiler switches, the configuration
10947pragma @code{No_Strict_Aliasing} with no parameters may be
10948used to specify that for all access types, the strict
10949aliasing optimization should be suppressed.
10950
10951However, these approaches are still overkill, in that they causes
10952all manipulations of all access values to be deoptimized. A more
10953refined approach is to concentrate attention on the specific
10954access type identified as problematic.
10955
10956First, if a careful analysis of uses of the pointer shows
10957that there are no possible problematic references, then
10958the warning can be suppressed by bracketing the
10959instantiation of @code{Unchecked_Conversion} to turn
10960the warning off:
10961
10962@smallexample @c ada
10963   pragma Warnings (Off);
10964   function to_a2u is
10965     new Unchecked_Conversion (a1, a2);
10966   pragma Warnings (On);
10967@end smallexample
10968
10969@noindent
10970Of course that approach is not appropriate for this particular
10971example, since indeed there is a problematic reference. In this
10972case we can take one of two other approaches.
10973
10974The first possibility is to move the instantiation of unchecked
10975conversion to the unit in which the type is declared. In
10976this example, we would move the instantiation of
10977@code{Unchecked_Conversion} from the body of package
10978@code{p2} to the spec of package @code{p1}. Now the
10979warning disappears. That's because any use of the
10980access type knows there is a suspicious unchecked
10981conversion, and the strict aliasing optimization
10982is automatically suppressed for the type.
10983
10984If it is not practical to move the unchecked conversion to the same unit
10985in which the destination access type is declared (perhaps because the
10986source type is not visible in that unit), you may use pragma
10987@code{No_Strict_Aliasing} for the type. This pragma must occur in the
10988same declarative sequence as the declaration of the access type:
10989
10990@smallexample @c ada
10991   type a2 is access int2;
10992   pragma No_Strict_Aliasing (a2);
10993@end smallexample
10994
10995@noindent
10996Here again, the compiler now knows that the strict aliasing optimization
10997should be suppressed for any reference to type @code{a2} and the
10998expected behavior is obtained.
10999
11000Finally, note that although the compiler can generate warnings for
11001simple cases of unchecked conversions, there are tricker and more
11002indirect ways of creating type incorrect aliases which the compiler
11003cannot detect. Examples are the use of address overlays and unchecked
11004conversions involving composite types containing access types as
11005components. In such cases, no warnings are generated, but there can
11006still be aliasing problems. One safe coding practice is to forbid the
11007use of address clauses for type overlaying, and to allow unchecked
11008conversion only for primitive types. This is not really a significant
11009restriction since any possible desired effect can be achieved by
11010unchecked conversion of access values.
11011
11012The aliasing analysis done in strict aliasing mode can certainly
11013have significant benefits. We have seen cases of large scale
11014application code where the time is increased by up to 5% by turning
11015this optimization off. If you have code that includes significant
11016usage of unchecked conversion, you might want to just stick with
11017@option{-O1} and avoid the entire issue. If you get adequate
11018performance at this level of optimization level, that's probably
11019the safest approach. If tests show that you really need higher
11020levels of optimization, then you can experiment with @option{-O2}
11021and @option{-O2 -fno-strict-aliasing} to see how much effect this
11022has on size and speed of the code. If you really need to use
11023@option{-O2} with strict aliasing in effect, then you should
11024review any uses of unchecked conversion of access types,
11025particularly if you are getting the warnings described above.
11026
11027@node Aliased Variables and Optimization
11028@subsection Aliased Variables and Optimization
11029@cindex Aliasing
11030There are scenarios in which programs may
11031use low level techniques to modify variables
11032that otherwise might be considered to be unassigned. For example,
11033a variable can be passed to a procedure by reference, which takes
11034the address of the parameter and uses the address to modify the
11035variable's value, even though it is passed as an IN parameter.
11036Consider the following example:
11037
11038@smallexample @c ada
11039procedure P is
11040   Max_Length : constant Natural := 16;
11041   type Char_Ptr is access all Character;
11042
11043   procedure Get_String(Buffer: Char_Ptr; Size : Integer);
11044   pragma Import (C, Get_String, "get_string");
11045
11046   Name : aliased String (1 .. Max_Length) := (others => ' ');
11047   Temp : Char_Ptr;
11048
11049   function Addr (S : String) return Char_Ptr is
11050      function To_Char_Ptr is
11051        new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
11052   begin
11053      return To_Char_Ptr (S (S'First)'Address);
11054   end;
11055
11056begin
11057   Temp := Addr (Name);
11058   Get_String (Temp, Max_Length);
11059end;
11060@end smallexample
11061
11062@noindent
11063where Get_String is a C function that uses the address in Temp to
11064modify the variable @code{Name}. This code is dubious, and arguably
11065erroneous, and the compiler would be entitled to assume that
11066@code{Name} is never modified, and generate code accordingly.
11067
11068However, in practice, this would cause some existing code that
11069seems to work with no optimization to start failing at high
11070levels of optimzization.
11071
11072What the compiler does for such cases is to assume that marking
11073a variable as aliased indicates that some "funny business" may
11074be going on. The optimizer recognizes the aliased keyword and
11075inhibits optimizations that assume the value cannot be assigned.
11076This means that the above example will in fact "work" reliably,
11077that is, it will produce the expected results.
11078
11079@node Atomic Variables and Optimization
11080@subsection Atomic Variables and Optimization
11081@cindex Atomic
11082There are two considerations with regard to performance when
11083atomic variables are used.
11084
11085First, the RM only guarantees that access to atomic variables
11086be atomic, it has nothing to say about how this is achieved,
11087though there is a strong implication that this should not be
11088achieved by explicit locking code. Indeed GNAT will never
11089generate any locking code for atomic variable access (it will
11090simply reject any attempt to make a variable or type atomic
11091if the atomic access cannot be achieved without such locking code).
11092
11093That being said, it is important to understand that you cannot
11094assume that the entire variable will always be accessed. Consider
11095this example:
11096
11097@smallexample @c ada
11098type R is record
11099   A,B,C,D : Character;
11100end record;
11101for R'Size use 32;
11102for R'Alignment use 4;
11103
11104RV : R;
11105pragma Atomic (RV);
11106X : Character;
11107...
11108X := RV.B;
11109@end smallexample
11110
11111@noindent
11112You cannot assume that the reference to @code{RV.B}
11113will read the entire 32-bit
11114variable with a single load instruction. It is perfectly legitimate if
11115the hardware allows it to do a byte read of just the B field. This read
11116is still atomic, which is all the RM requires. GNAT can and does take
11117advantage of this, depending on the architecture and optimization level.
11118Any assumption to the contrary is non-portable and risky. Even if you
11119examine the assembly language and see a full 32-bit load, this might
11120change in a future version of the compiler.
11121
11122If your application requires that all accesses to @code{RV} in this
11123example be full 32-bit loads, you need to make a copy for the access
11124as in:
11125
11126@smallexample @c ada
11127declare
11128   RV_Copy : constant R := RV;
11129begin
11130   X := RV_Copy.B;
11131end;
11132@end smallexample
11133
11134
11135@noindent
11136Now the reference to RV must read the whole variable.
11137Actually one can imagine some compiler which figures
11138out that the whole copy is not required (because only
11139the B field is actually accessed), but GNAT
11140certainly won't do that, and we don't know of any
11141compiler that would not handle this right, and the
11142above code will in practice work portably across
11143all architectures (that permit the Atomic declaration).
11144
11145The second issue with atomic variables has to do with
11146the possible requirement of generating synchronization
11147code. For more details on this, consult the sections on
11148the pragmas Enable/Disable_Atomic_Synchronization in the
11149GNAT Reference Manual. If performance is critical, and
11150such synchronization code is not required, it may be
11151useful to disable it.
11152
11153@node Passive Task Optimization
11154@subsection Passive Task Optimization
11155@cindex Passive Task
11156
11157A passive task is one which is sufficiently simple that
11158in theory a compiler could recognize it an implement it
11159efficiently without creating a new thread. The original design
11160of Ada 83 had in mind this kind of passive task optimization, but
11161only a few Ada 83 compilers attempted it. The problem was that
11162it was difficult to determine the exact conditions under which
11163the optimization was possible. The result is a very fragile
11164optimization where a very minor change in the program can
11165suddenly silently make a task non-optimizable.
11166
11167With the revisiting of this issue in Ada 95, there was general
11168agreement that this approach was fundamentally flawed, and the
11169notion of protected types was introduced. When using protected
11170types, the restrictions are well defined, and you KNOW that the
11171operations will be optimized, and furthermore this optimized
11172performance is fully portable.
11173
11174Although it would theoretically be possible for GNAT to attempt to
11175do this optimization, but it really doesn't make sense in the
11176context of Ada 95, and none of the Ada 95 compilers implement
11177this optimization as far as we know. In particular GNAT never
11178attempts to perform this optimization.
11179
11180In any new Ada 95 code that is written, you should always
11181use protected types in place of tasks that might be able to
11182be optimized in this manner.
11183Of course this does not help if you have legacy Ada 83 code
11184that depends on this optimization, but it is unusual to encounter
11185a case where the performance gains from this optimization
11186are significant.
11187
11188Your program should work correctly without this optimization. If
11189you have performance problems, then the most practical
11190approach is to figure out exactly where these performance problems
11191arise, and update those particular tasks to be protected types. Note
11192that typically clients of the tasks who call entries, will not have
11193to be modified, only the task definition itself.
11194
11195@ifset vms
11196@node Coverage Analysis
11197@subsection Coverage Analysis
11198
11199@noindent
11200GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11201the user to determine the distribution of execution time across a program,
11202@pxref{Profiling} for details of usage.
11203@end ifset
11204
11205
11206@node Text_IO Suggestions
11207@section @code{Text_IO} Suggestions
11208@cindex @code{Text_IO} and performance
11209
11210@noindent
11211The @code{Ada.Text_IO} package has fairly high overheads due in part to
11212the requirement of maintaining page and line counts. If performance
11213is critical, a recommendation is to use @code{Stream_IO} instead of
11214@code{Text_IO} for volume output, since this package has less overhead.
11215
11216If @code{Text_IO} must be used, note that by default output to the standard
11217output and standard error files is unbuffered (this provides better
11218behavior when output statements are used for debugging, or if the
11219progress of a program is observed by tracking the output, e.g. by
11220using the Unix @command{tail -f} command to watch redirected output.
11221
11222If you are generating large volumes of output with @code{Text_IO} and
11223performance is an important factor, use a designated file instead
11224of the standard output file, or change the standard output file to
11225be buffered using @code{Interfaces.C_Streams.setvbuf}.
11226
11227
11228@ifclear FSFEDITION
11229@node Reducing Size of Ada Executables with gnatelim
11230@section Reducing Size of Ada Executables with @code{gnatelim}
11231@findex gnatelim
11232
11233@noindent
11234This section describes @command{gnatelim}, a tool which detects unused
11235subprograms and helps the compiler to create a smaller executable for your
11236program.
11237
11238@menu
11239* About gnatelim::
11240* Running gnatelim::
11241* Processing Precompiled Libraries::
11242* Correcting the List of Eliminate Pragmas::
11243* Making Your Executables Smaller::
11244* Summary of the gnatelim Usage Cycle::
11245@end menu
11246
11247@node About gnatelim
11248@subsection About @code{gnatelim}
11249
11250@noindent
11251When a program shares a set of Ada
11252packages with other programs, it may happen that this program uses
11253only a fraction of the subprograms defined in these packages. The code
11254created for these unused subprograms increases the size of the executable.
11255
11256@code{gnatelim} tracks unused subprograms in an Ada program and
11257outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11258subprograms that are declared but never called. By placing the list of
11259@code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11260recompiling your program, you may decrease the size of its executable,
11261because the compiler will not generate the code for 'eliminated' subprograms.
11262@xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11263information about this pragma.
11264
11265@code{gnatelim} needs as its input data the name of the main subprogram.
11266
11267If a set of source files is specified as @code{gnatelim} arguments, it
11268treats these files as a complete set of sources making up a program to
11269analyse, and analyses only these sources.
11270
11271After a full successful build of the main subprogram @code{gnatelim} can be
11272called without  specifying sources to analyse, in this case it computes
11273the source closure of the main unit from the @file{ALI} files.
11274
11275The following command will create the set of @file{ALI} files needed for
11276@code{gnatelim}:
11277
11278@smallexample
11279$ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11280@end smallexample
11281
11282Note that @code{gnatelim} does not need object files.
11283
11284@node Running gnatelim
11285@subsection Running @code{gnatelim}
11286
11287@noindent
11288@code{gnatelim} has the following command-line interface:
11289
11290@smallexample
11291$ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11292@end smallexample
11293
11294@noindent
11295@var{main_unit_name} should be a name of a source file that contains the main
11296subprogram of a program (partition).
11297
11298Each @var{filename} is the name (including the extension) of a source
11299file to process. ``Wildcards'' are allowed, and
11300the file name may contain path information.
11301
11302@samp{@var{gcc_switches}} is a list of switches for
11303@command{gcc}. They will be passed on to all compiler invocations made by
11304@command{gnatelim} to generate the ASIS trees. Here you can provide
11305@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11306use the @option{-gnatec} switch to set the configuration file,
11307use the @option{-gnat05} switch if sources should be compiled in
11308Ada 2005 mode etc.
11309
11310@code{gnatelim} has the following switches:
11311
11312@table @option
11313@c !sort!
11314@item --version
11315@cindex @option{--version} @command{gnatelim}
11316Display Copyright and version, then exit disregarding all other options.
11317
11318@item --help
11319@cindex @option{--help} @command{gnatelim}
11320Display usage, then exit disregarding all other options.
11321
11322@item -P @var{file}
11323@cindex @option{-P} @command{gnatelim}
11324Indicates the name of the project file that describes the set of sources
11325to be processed.
11326
11327@item -X@var{name}=@var{value}
11328@cindex @option{-X} @command{gnatelim}
11329Indicates that external variable @var{name} in the argument project
11330has the value @var{value}. Has no effect if no project is specified as
11331tool argument.
11332
11333@item ^-files^/FILES^=@var{filename}
11334@cindex @option{^-files^/FILES^} (@code{gnatelim})
11335Take the argument source files from the specified file. This file should be an
11336ordinary text file containing file names separated by spaces or
11337line breaks. You can use this switch more than once in the same call to
11338@command{gnatelim}. You also can combine this switch with
11339an explicit list of files.
11340
11341@item ^-log^/LOG^
11342@cindex @option{^-log^/LOG^} (@command{gnatelim})
11343Duplicate all the output sent to @file{stderr} into a log file. The log file
11344is named @file{gnatelim.log} and is located in the current directory.
11345
11346@ignore
11347@item ^-log^/LOGFILE^=@var{filename}
11348@cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11349Duplicate all the output sent to @file{stderr} into a specified log file.
11350@end ignore
11351
11352@cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11353@item ^--no-elim-dispatch^/NO_DISPATCH^
11354Do not generate pragmas for dispatching operations.
11355
11356@item ^--ignore^/IGNORE^=@var{filename}
11357@cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11358Do not generate pragmas for subprograms declared in the sources
11359listed in a specified file
11360
11361@cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11362@item ^-o^/OUTPUT^=@var{report_file}
11363Put @command{gnatelim} output into a specified file. If this file already exists,
11364it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11365into @file{stderr}
11366
11367@item ^-j^/PROCESSES=^@var{n}
11368@cindex @option{^-j^/PROCESSES^} (@command{gnatelim})
11369Use @var{n} processes to carry out the tree creations (internal representations
11370of the argument sources). On a multiprocessor machine this speeds up processing
11371of big sets of argument sources. If @var{n} is 0, then the maximum number of
11372parallel tree creations is the number of core processors on the platform.
11373
11374@item ^-q^/QUIET^
11375@cindex @option{^-q^/QUIET^} (@command{gnatelim})
11376Quiet mode: by default @code{gnatelim} outputs to the standard error
11377stream the number of program units left to be processed. This option turns
11378this trace off.
11379
11380@cindex @option{^-t^/TIME^} (@command{gnatelim})
11381@item ^-t^/TIME^
11382Print out execution time.
11383
11384@item ^-v^/VERBOSE^
11385@cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11386Verbose mode: @code{gnatelim} version information is printed as Ada
11387comments to the standard output stream. Also, in addition to the number of
11388program units left @code{gnatelim} will output the name of the current unit
11389being processed.
11390
11391@item ^-wq^/WARNINGS=QUIET^
11392@cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11393Quiet warning mode - some warnings are suppressed. In particular warnings that
11394indicate that the analysed set of sources is incomplete to make up a
11395partition and that some subprogram bodies are missing are not generated.
11396@end table
11397
11398@noindent
11399Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11400driver (see @ref{The GNAT Driver and Project Files}).
11401
11402@node Processing Precompiled Libraries
11403@subsection Processing Precompiled Libraries
11404
11405@noindent
11406If some program uses a precompiled Ada library, it can be processed by
11407@code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11408Eliminate pragma for a subprogram if the body of this subprogram has not
11409been analysed, this is a typical case for subprograms from precompiled
11410libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11411warnings about missing source files and non-analyzed subprogram bodies
11412that can be generated when processing precompiled Ada libraries.
11413
11414@node Correcting the List of Eliminate Pragmas
11415@subsection Correcting the List of Eliminate Pragmas
11416
11417@noindent
11418In some rare cases @code{gnatelim} may try to eliminate
11419subprograms that are actually called in the program. In this case, the
11420compiler will generate an error message of the form:
11421
11422@smallexample
11423main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11424@end smallexample
11425
11426@noindent
11427You will need to manually remove the wrong @code{Eliminate} pragmas from
11428the configuration file indicated in the error message. You should recompile
11429your program from scratch after that, because you need a consistent
11430configuration file(s) during the entire compilation.
11431
11432@node Making Your Executables Smaller
11433@subsection Making Your Executables Smaller
11434
11435@noindent
11436In order to get a smaller executable for your program you now have to
11437recompile the program completely with the configuration file containing
11438pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11439@file{gnat.adc} file located in your current directory, just do:
11440
11441@smallexample
11442$ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11443@end smallexample
11444
11445@noindent
11446(Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11447recompile everything
11448with the set of pragmas @code{Eliminate} that you have obtained with
11449@command{gnatelim}).
11450
11451Be aware that the set of @code{Eliminate} pragmas is specific to each
11452program. It is not recommended to merge sets of @code{Eliminate}
11453pragmas created for different programs in one configuration file.
11454
11455@node Summary of the gnatelim Usage Cycle
11456@subsection Summary of the @code{gnatelim} Usage Cycle
11457
11458@noindent
11459Here is a quick summary of the steps to be taken in order to reduce
11460the size of your executables with @code{gnatelim}. You may use
11461other GNAT options to control the optimization level,
11462to produce the debugging information, to set search path, etc.
11463
11464@enumerate
11465@item
11466Create a complete set of @file{ALI} files (if the program has not been
11467built already)
11468
11469@smallexample
11470$ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11471@end smallexample
11472
11473@item
11474Generate a list of @code{Eliminate} pragmas in default configuration file
11475@file{gnat.adc} in the current directory
11476@smallexample
11477@ifset vms
11478$ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11479@end ifset
11480@ifclear vms
11481$ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11482@end ifclear
11483@end smallexample
11484
11485@item
11486Recompile the application
11487
11488@smallexample
11489$ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11490@end smallexample
11491
11492@end enumerate
11493@end ifclear
11494
11495@node Reducing Size of Executables with unused subprogram/data elimination
11496@section Reducing Size of Executables with Unused Subprogram/Data Elimination
11497@findex unused subprogram/data elimination
11498
11499@noindent
11500This section describes how you can eliminate unused subprograms and data from
11501your executable just by setting options at compilation time.
11502
11503@menu
11504* About unused subprogram/data elimination::
11505* Compilation options::
11506* Example of unused subprogram/data elimination::
11507@end menu
11508
11509@node About unused subprogram/data elimination
11510@subsection About unused subprogram/data elimination
11511
11512@noindent
11513By default, an executable contains all code and data of its composing objects
11514(directly linked or coming from statically linked libraries), even data or code
11515never used by this executable.
11516
11517This feature will allow you to eliminate such unused code from your
11518executable, making it smaller (in disk and in memory).
11519
11520This functionality is available on all Linux platforms except for the IA-64
11521architecture and on all cross platforms using the ELF binary file format.
11522In both cases GNU binutils version 2.16 or later are required to enable it.
11523
11524@node Compilation options
11525@subsection Compilation options
11526
11527@noindent
11528The operation of eliminating the unused code and data from the final executable
11529is directly performed by the linker.
11530
11531In order to do this, it has to work with objects compiled with the
11532following options:
11533@option{-ffunction-sections} @option{-fdata-sections}.
11534@cindex @option{-ffunction-sections} (@command{gcc})
11535@cindex @option{-fdata-sections} (@command{gcc})
11536These options are usable with C and Ada files.
11537They will place respectively each
11538function or data in a separate section in the resulting object file.
11539
11540Once the objects and static libraries are created with these options, the
11541linker can perform the dead code elimination. You can do this by setting
11542the @option{-Wl,--gc-sections} option to gcc command or in the
11543@option{-largs} section of @command{gnatmake}. This will perform a
11544garbage collection of code and data never referenced.
11545
11546If the linker performs a partial link (@option{-r} ld linker option), then you
11547will need to provide one or several entry point using the
11548@option{-e} / @option{--entry} ld option.
11549
11550Note that objects compiled without the @option{-ffunction-sections} and
11551@option{-fdata-sections} options can still be linked with the executable.
11552However, no dead code elimination will be performed on those objects (they will
11553be linked as is).
11554
11555The GNAT static library is now compiled with -ffunction-sections and
11556-fdata-sections on some platforms. This allows you to eliminate the unused code
11557and data of the GNAT library from your executable.
11558
11559@node Example of unused subprogram/data elimination
11560@subsection Example of unused subprogram/data elimination
11561
11562@noindent
11563Here is a simple example:
11564
11565@smallexample @c ada
11566with Aux;
11567
11568procedure Test is
11569begin
11570   Aux.Used (10);
11571end Test;
11572
11573package Aux is
11574   Used_Data   : Integer;
11575   Unused_Data : Integer;
11576
11577   procedure Used   (Data : Integer);
11578   procedure Unused (Data : Integer);
11579end Aux;
11580
11581package body Aux is
11582   procedure Used (Data : Integer) is
11583   begin
11584      Used_Data := Data;
11585   end Used;
11586
11587   procedure Unused (Data : Integer) is
11588   begin
11589      Unused_Data := Data;
11590   end Unused;
11591end Aux;
11592@end smallexample
11593
11594@noindent
11595@code{Unused} and @code{Unused_Data} are never referenced in this code
11596excerpt, and hence they may be safely removed from the final executable.
11597
11598@smallexample
11599$ gnatmake test
11600
11601$ nm test | grep used
11602020015f0 T aux__unused
1160302005d88 B aux__unused_data
11604020015cc T aux__used
1160502005d84 B aux__used_data
11606
11607$ gnatmake test -cargs -fdata-sections -ffunction-sections \
11608     -largs -Wl,--gc-sections
11609
11610$ nm test | grep used
1161102005350 T aux__used
116120201ffe0 B aux__used_data
11613@end smallexample
11614
11615@noindent
11616It can be observed that the procedure @code{Unused} and the object
11617@code{Unused_Data} are removed by the linker when using the
11618appropriate options.
11619
11620@c ********************************
11621@node Renaming Files with gnatchop
11622@chapter Renaming Files with @code{gnatchop}
11623@findex gnatchop
11624
11625@noindent
11626This chapter discusses how to handle files with multiple units by using
11627the @code{gnatchop} utility. This utility is also useful in renaming
11628files to meet the standard GNAT default file naming conventions.
11629
11630@menu
11631* Handling Files with Multiple Units::
11632* Operating gnatchop in Compilation Mode::
11633* Command Line for gnatchop::
11634* Switches for gnatchop::
11635* Examples of gnatchop Usage::
11636@end menu
11637
11638@node Handling Files with Multiple Units
11639@section Handling Files with Multiple Units
11640
11641@noindent
11642The basic compilation model of GNAT requires that a file submitted to the
11643compiler have only one unit and there be a strict correspondence
11644between the file name and the unit name.
11645
11646The @code{gnatchop} utility allows both of these rules to be relaxed,
11647allowing GNAT to process files which contain multiple compilation units
11648and files with arbitrary file names. @code{gnatchop}
11649reads the specified file and generates one or more output files,
11650containing one unit per file. The unit and the file name correspond,
11651as required by GNAT.
11652
11653If you want to permanently restructure a set of ``foreign'' files so that
11654they match the GNAT rules, and do the remaining development using the
11655GNAT structure, you can simply use @command{gnatchop} once, generate the
11656new set of files and work with them from that point on.
11657
11658Alternatively, if you want to keep your files in the ``foreign'' format,
11659perhaps to maintain compatibility with some other Ada compilation
11660system, you can set up a procedure where you use @command{gnatchop} each
11661time you compile, regarding the source files that it writes as temporary
11662files that you throw away.
11663
11664Note that if your file containing multiple units starts with a byte order
11665mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11666will each start with a copy of this BOM, meaning that they can be compiled
11667automatically in UTF-8 mode without needing to specify an explicit encoding.
11668
11669@node Operating gnatchop in Compilation Mode
11670@section Operating gnatchop in Compilation Mode
11671
11672@noindent
11673The basic function of @code{gnatchop} is to take a file with multiple units
11674and split it into separate files. The boundary between files is reasonably
11675clear, except for the issue of comments and pragmas. In default mode, the
11676rule is that any pragmas between units belong to the previous unit, except
11677that configuration pragmas always belong to the following unit. Any comments
11678belong to the following unit. These rules
11679almost always result in the right choice of
11680the split point without needing to mark it explicitly and most users will
11681find this default to be what they want. In this default mode it is incorrect to
11682submit a file containing only configuration pragmas, or one that ends in
11683configuration pragmas, to @code{gnatchop}.
11684
11685However, using a special option to activate ``compilation mode'',
11686@code{gnatchop}
11687can perform another function, which is to provide exactly the semantics
11688required by the RM for handling of configuration pragmas in a compilation.
11689In the absence of configuration pragmas (at the main file level), this
11690option has no effect, but it causes such configuration pragmas to be handled
11691in a quite different manner.
11692
11693First, in compilation mode, if @code{gnatchop} is given a file that consists of
11694only configuration pragmas, then this file is appended to the
11695@file{gnat.adc} file in the current directory. This behavior provides
11696the required behavior described in the RM for the actions to be taken
11697on submitting such a file to the compiler, namely that these pragmas
11698should apply to all subsequent compilations in the same compilation
11699environment. Using GNAT, the current directory, possibly containing a
11700@file{gnat.adc} file is the representation
11701of a compilation environment. For more information on the
11702@file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11703
11704Second, in compilation mode, if @code{gnatchop}
11705is given a file that starts with
11706configuration pragmas, and contains one or more units, then these
11707configuration pragmas are prepended to each of the chopped files. This
11708behavior provides the required behavior described in the RM for the
11709actions to be taken on compiling such a file, namely that the pragmas
11710apply to all units in the compilation, but not to subsequently compiled
11711units.
11712
11713Finally, if configuration pragmas appear between units, they are appended
11714to the previous unit. This results in the previous unit being illegal,
11715since the compiler does not accept configuration pragmas that follow
11716a unit. This provides the required RM behavior that forbids configuration
11717pragmas other than those preceding the first compilation unit of a
11718compilation.
11719
11720For most purposes, @code{gnatchop} will be used in default mode. The
11721compilation mode described above is used only if you need exactly
11722accurate behavior with respect to compilations, and you have files
11723that contain multiple units and configuration pragmas. In this
11724circumstance the use of @code{gnatchop} with the compilation mode
11725switch provides the required behavior, and is for example the mode
11726in which GNAT processes the ACVC tests.
11727
11728@node Command Line for gnatchop
11729@section Command Line for @code{gnatchop}
11730
11731@noindent
11732The @code{gnatchop} command has the form:
11733
11734@smallexample
11735@c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11736@c      @ovar{directory}
11737@c Expanding @ovar macro inline (explanation in macro def comments)
11738$ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11739      @r{[}@var{directory}@r{]}
11740@end smallexample
11741
11742@noindent
11743The only required argument is the file name of the file to be chopped.
11744There are no restrictions on the form of this file name. The file itself
11745contains one or more Ada units, in normal GNAT format, concatenated
11746together. As shown, more than one file may be presented to be chopped.
11747
11748When run in default mode, @code{gnatchop} generates one output file in
11749the current directory for each unit in each of the files.
11750
11751@var{directory}, if specified, gives the name of the directory to which
11752the output files will be written. If it is not specified, all files are
11753written to the current directory.
11754
11755For example, given a
11756file called @file{hellofiles} containing
11757
11758@smallexample @c ada
11759@group
11760@cartouche
11761procedure hello;
11762
11763with Text_IO; use Text_IO;
11764procedure hello is
11765begin
11766   Put_Line ("Hello");
11767end hello;
11768@end cartouche
11769@end group
11770@end smallexample
11771
11772@noindent
11773the command
11774
11775@smallexample
11776$ gnatchop ^hellofiles^HELLOFILES.^
11777@end smallexample
11778
11779@noindent
11780generates two files in the current directory, one called
11781@file{hello.ads} containing the single line that is the procedure spec,
11782and the other called @file{hello.adb} containing the remaining text. The
11783original file is not affected. The generated files can be compiled in
11784the normal manner.
11785
11786@noindent
11787When gnatchop is invoked on a file that is empty or that contains only empty
11788lines and/or comments, gnatchop will not fail, but will not produce any
11789new sources.
11790
11791For example, given a
11792file called @file{toto.txt} containing
11793
11794@smallexample @c ada
11795@group
11796@cartouche
11797--  Just a comment
11798@end cartouche
11799@end group
11800@end smallexample
11801
11802@noindent
11803the command
11804
11805@smallexample
11806$ gnatchop ^toto.txt^TOT.TXT^
11807@end smallexample
11808
11809@noindent
11810will not produce any new file and will result in the following warnings:
11811
11812@smallexample
11813toto.txt:1:01: warning: empty file, contains no compilation units
11814no compilation units found
11815no source files written
11816@end smallexample
11817
11818@node Switches for gnatchop
11819@section Switches for @code{gnatchop}
11820
11821@noindent
11822@command{gnatchop} recognizes the following switches:
11823
11824@table @option
11825@c !sort!
11826
11827@item --version
11828@cindex @option{--version} @command{gnatchop}
11829Display Copyright and version, then exit disregarding all other options.
11830
11831@item --help
11832@cindex @option{--help} @command{gnatchop}
11833If @option{--version} was not used, display usage, then exit disregarding
11834all other options.
11835
11836@item ^-c^/COMPILATION^
11837@cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11838Causes @code{gnatchop} to operate in compilation mode, in which
11839configuration pragmas are handled according to strict RM rules. See
11840previous section for a full description of this mode.
11841
11842@ifclear vms
11843@item -gnat@var{xxx}
11844This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11845used to parse the given file. Not all @var{xxx} options make sense,
11846but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11847process a source file that uses Latin-2 coding for identifiers.
11848@end ifclear
11849
11850@item ^-h^/HELP^
11851Causes @code{gnatchop} to generate a brief help summary to the standard
11852output file showing usage information.
11853
11854@item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11855@cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11856Limit generated file names to the specified number @code{mm}
11857of characters.
11858This is useful if the
11859resulting set of files is required to be interoperable with systems
11860which limit the length of file names.
11861@ifset vms
11862If no value is given, or
11863if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11864a default of 39, suitable for OpenVMS Alpha
11865Systems, is assumed
11866@end ifset
11867@ifclear vms
11868No space is allowed between the @option{-k} and the numeric value. The numeric
11869value may be omitted in which case a default of @option{-k8},
11870suitable for use
11871with DOS-like file systems, is used. If no @option{-k} switch
11872is present then
11873there is no limit on the length of file names.
11874@end ifclear
11875
11876@item ^-p^/PRESERVE^
11877@cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11878Causes the file ^modification^creation^ time stamp of the input file to be
11879preserved and used for the time stamp of the output file(s). This may be
11880useful for preserving coherency of time stamps in an environment where
11881@code{gnatchop} is used as part of a standard build process.
11882
11883@item ^-q^/QUIET^
11884@cindex @option{^-q^/QUIET^} (@code{gnatchop})
11885Causes output of informational messages indicating the set of generated
11886files to be suppressed. Warnings and error messages are unaffected.
11887
11888@item ^-r^/REFERENCE^
11889@cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11890@findex Source_Reference
11891Generate @code{Source_Reference} pragmas. Use this switch if the output
11892files are regarded as temporary and development is to be done in terms
11893of the original unchopped file. This switch causes
11894@code{Source_Reference} pragmas to be inserted into each of the
11895generated files to refers back to the original file name and line number.
11896The result is that all error messages refer back to the original
11897unchopped file.
11898In addition, the debugging information placed into the object file (when
11899the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11900specified)
11901also refers back to this original file so that tools like profilers and
11902debuggers will give information in terms of the original unchopped file.
11903
11904If the original file to be chopped itself contains
11905a @code{Source_Reference}
11906pragma referencing a third file, then gnatchop respects
11907this pragma, and the generated @code{Source_Reference} pragmas
11908in the chopped file refer to the original file, with appropriate
11909line numbers. This is particularly useful when @code{gnatchop}
11910is used in conjunction with @code{gnatprep} to compile files that
11911contain preprocessing statements and multiple units.
11912
11913@item ^-v^/VERBOSE^
11914@cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11915Causes @code{gnatchop} to operate in verbose mode. The version
11916number and copyright notice are output, as well as exact copies of
11917the gnat1 commands spawned to obtain the chop control information.
11918
11919@item ^-w^/OVERWRITE^
11920@cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11921Overwrite existing file names. Normally @code{gnatchop} regards it as a
11922fatal error if there is already a file with the same name as a
11923file it would otherwise output, in other words if the files to be
11924chopped contain duplicated units. This switch bypasses this
11925check, and causes all but the last instance of such duplicated
11926units to be skipped.
11927
11928@ifclear vms
11929@item --GCC=@var{xxxx}
11930@cindex @option{--GCC=} (@code{gnatchop})
11931Specify the path of the GNAT parser to be used. When this switch is used,
11932no attempt is made to add the prefix to the GNAT parser executable.
11933@end ifclear
11934@end table
11935
11936@node Examples of gnatchop Usage
11937@section Examples of @code{gnatchop} Usage
11938
11939@table @code
11940@ifset vms
11941@item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11942@end ifset
11943@ifclear vms
11944@item gnatchop -w hello_s.ada prerelease/files
11945@end ifclear
11946
11947Chops the source file @file{hello_s.ada}. The output files will be
11948placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11949overwriting any
11950files with matching names in that directory (no files in the current
11951directory are modified).
11952
11953@item gnatchop ^archive^ARCHIVE.^
11954Chops the source file @file{^archive^ARCHIVE.^}
11955into the current directory. One
11956useful application of @code{gnatchop} is in sending sets of sources
11957around, for example in email messages. The required sources are simply
11958concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11959command), and then
11960@command{gnatchop} is used at the other end to reconstitute the original
11961file names.
11962
11963@item gnatchop file1 file2 file3 direc
11964Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11965the resulting files in the directory @file{direc}. Note that if any units
11966occur more than once anywhere within this set of files, an error message
11967is generated, and no files are written. To override this check, use the
11968@option{^-w^/OVERWRITE^} switch,
11969in which case the last occurrence in the last file will
11970be the one that is output, and earlier duplicate occurrences for a given
11971unit will be skipped.
11972@end table
11973
11974@node Configuration Pragmas
11975@chapter Configuration Pragmas
11976@cindex Configuration pragmas
11977@cindex Pragmas, configuration
11978
11979@menu
11980* Handling of Configuration Pragmas::
11981* The Configuration Pragmas Files::
11982@end menu
11983
11984@noindent
11985Configuration pragmas include those pragmas described as
11986such in the Ada Reference Manual, as well as
11987implementation-dependent pragmas that are configuration pragmas.
11988@xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11989for details on these additional GNAT-specific configuration pragmas.
11990Most notably, the pragma @code{Source_File_Name}, which allows
11991specifying non-default names for source files, is a configuration
11992pragma. The following is a complete list of configuration pragmas
11993recognized by GNAT:
11994
11995@smallexample
11996   Ada_83
11997   Ada_95
11998   Ada_05
11999   Ada_2005
12000   Ada_12
12001   Ada_2012
12002   Allow_Integer_Address
12003   Annotate
12004   Assertion_Policy
12005   Assume_No_Invalid_Values
12006   C_Pass_By_Copy
12007   Check_Name
12008   Check_Policy
12009   Compile_Time_Error
12010   Compile_Time_Warning
12011   Compiler_Unit
12012   Component_Alignment
12013   Convention_Identifier
12014   Debug_Policy
12015   Detect_Blocking
12016   Default_Storage_Pool
12017   Discard_Names
12018   Elaboration_Checks
12019   Eliminate
12020   Extend_System
12021   Extensions_Allowed
12022   External_Name_Casing
12023   Fast_Math
12024   Favor_Top_Level
12025   Float_Representation
12026   Implicit_Packing
12027   Initialize_Scalars
12028   Interrupt_State
12029   License
12030   Locking_Policy
12031   Long_Float
12032   No_Run_Time
12033   No_Strict_Aliasing
12034   Normalize_Scalars
12035   Optimize_Alignment
12036   Persistent_BSS
12037   Polling
12038   Priority_Specific_Dispatching
12039   Profile
12040   Profile_Warnings
12041   Propagate_Exceptions
12042   Queuing_Policy
12043   Ravenscar
12044   Restricted_Run_Time
12045   Restrictions
12046   Restrictions_Warnings
12047   Reviewable
12048   Short_Circuit_And_Or
12049   Source_File_Name
12050   Source_File_Name_Project
12051   SPARK_Mode
12052   Style_Checks
12053   Suppress
12054   Suppress_Exception_Locations
12055   Task_Dispatching_Policy
12056   Universal_Data
12057   Unsuppress
12058   Use_VADS_Size
12059   Validity_Checks
12060   Warnings
12061   Wide_Character_Encoding
12062@end smallexample
12063
12064@node Handling of Configuration Pragmas
12065@section Handling of Configuration Pragmas
12066
12067Configuration pragmas may either appear at the start of a compilation
12068unit, or they can appear in a configuration pragma file to apply to
12069all compilations performed in a given compilation environment.
12070
12071GNAT also provides the @code{gnatchop} utility to provide an automatic
12072way to handle configuration pragmas following the semantics for
12073compilations (that is, files with multiple units), described in the RM.
12074See @ref{Operating gnatchop in Compilation Mode} for details.
12075However, for most purposes, it will be more convenient to edit the
12076@file{gnat.adc} file that contains configuration pragmas directly,
12077as described in the following section.
12078
12079In the case of @code{Restrictions} pragmas appearing as configuration
12080pragmas in individual compilation units, the exact handling depends on
12081the type of restriction.
12082
12083Restrictions that require partition-wide consistency (like
12084@code{No_Tasking}) are
12085recognized wherever they appear
12086and can be freely inherited, e.g. from a with'ed unit to the with'ing
12087unit. This makes sense since the binder will in any case insist on seeing
12088consistent use, so any unit not conforming to any restrictions that are
12089anywhere in the partition will be rejected, and you might as well find
12090that out at compile time rather than at bind time.
12091
12092For restrictions that do not require partition-wide consistency, e.g.
12093SPARK or No_Implementation_Attributes, in general the restriction applies
12094only to the unit in which the pragma appears, and not to any other units.
12095
12096The exception is No_Elaboration_Code which always applies to the entire
12097object file from a compilation, i.e. to the body, spec, and all subunits.
12098This restriction can be specified in a configuration pragma file, or it
12099can be on the body and/or the spec (in eithe case it applies to all the
12100relevant units). It can appear on a subunit only if it has previously
12101appeared in the body of spec.
12102
12103@node The Configuration Pragmas Files
12104@section The Configuration Pragmas Files
12105@cindex @file{gnat.adc}
12106
12107@noindent
12108In GNAT a compilation environment is defined by the current
12109directory at the time that a compile command is given. This current
12110directory is searched for a file whose name is @file{gnat.adc}. If
12111this file is present, it is expected to contain one or more
12112configuration pragmas that will be applied to the current compilation.
12113However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12114considered.
12115
12116Configuration pragmas may be entered into the @file{gnat.adc} file
12117either by running @code{gnatchop} on a source file that consists only of
12118configuration pragmas, or more conveniently  by
12119direct editing of the @file{gnat.adc} file, which is a standard format
12120source file.
12121
12122In addition to @file{gnat.adc}, additional files containing configuration
12123pragmas may be applied to the current compilation using the switch
12124@option{-gnatec}@var{path}. @var{path} must designate an existing file that
12125contains only configuration pragmas. These configuration pragmas are
12126in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12127is present and switch @option{-gnatA} is not used).
12128
12129It is allowed to specify several switches @option{-gnatec}, all of which
12130will be taken into account.
12131
12132If you are using project file, a separate mechanism is provided using
12133project attributes, see @ref{Specifying Configuration Pragmas} for more
12134details.
12135
12136@ifset vms
12137Of special interest to GNAT OpenVMS Alpha is the following
12138configuration pragma:
12139
12140@smallexample @c ada
12141@cartouche
12142pragma Extend_System (Aux_DEC);
12143@end cartouche
12144@end smallexample
12145
12146@noindent
12147In the presence of this pragma, GNAT adds to the definition of the
12148predefined package SYSTEM all the additional types and subprograms that are
12149defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12150@end ifset
12151
12152@node Handling Arbitrary File Naming Conventions with gnatname
12153@chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
12154@cindex Arbitrary File Naming Conventions
12155
12156@menu
12157* Arbitrary File Naming Conventions::
12158* Running gnatname::
12159* Switches for gnatname::
12160* Examples of gnatname Usage::
12161@end menu
12162
12163@node Arbitrary File Naming Conventions
12164@section Arbitrary File Naming Conventions
12165
12166@noindent
12167The GNAT compiler must be able to know the source file name of a compilation
12168unit.  When using the standard GNAT default file naming conventions
12169(@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12170does not need additional information.
12171
12172@noindent
12173When the source file names do not follow the standard GNAT default file naming
12174conventions, the GNAT compiler must be given additional information through
12175a configuration pragmas file (@pxref{Configuration Pragmas})
12176or a project file.
12177When the non-standard file naming conventions are well-defined,
12178a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12179(@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12180if the file naming conventions are irregular or arbitrary, a number
12181of pragma @code{Source_File_Name} for individual compilation units
12182must be defined.
12183To help maintain the correspondence between compilation unit names and
12184source file names within the compiler,
12185GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12186set of files.
12187
12188@node Running gnatname
12189@section Running @code{gnatname}
12190
12191@noindent
12192The usual form of the @code{gnatname} command is
12193
12194@smallexample
12195@c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12196@c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12197@c Expanding @ovar macro inline (explanation in macro def comments)
12198$ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12199      @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12200@end smallexample
12201
12202@noindent
12203All of the arguments are optional. If invoked without any argument,
12204@code{gnatname} will display its usage.
12205
12206@noindent
12207When used with at least one naming pattern, @code{gnatname} will attempt to
12208find all the compilation units in files that follow at least one of the
12209naming patterns. To find these compilation units,
12210@code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12211regular files.
12212
12213@noindent
12214One or several Naming Patterns may be given as arguments to @code{gnatname}.
12215Each Naming Pattern is enclosed between double quotes (or single
12216quotes on Windows).
12217A Naming Pattern is a regular expression similar to the wildcard patterns
12218used in file names by the Unix shells or the DOS prompt.
12219
12220@noindent
12221@code{gnatname} may be called with several sections of directories/patterns.
12222Sections are separated by switch @code{--and}. In each section, there must be
12223at least one pattern. If no directory is specified in a section, the current
12224directory (or the project directory is @code{-P} is used) is implied.
12225The options other that the directory switches and the patterns apply globally
12226even if they are in different sections.
12227
12228@noindent
12229Examples of Naming Patterns are
12230
12231@smallexample
12232   "*.[12].ada"
12233   "*.ad[sb]*"
12234   "body_*"    "spec_*"
12235@end smallexample
12236
12237@noindent
12238For a more complete description of the syntax of Naming Patterns,
12239see the second kind of regular expressions described in @file{g-regexp.ads}
12240(the ``Glob'' regular expressions).
12241
12242@noindent
12243When invoked with no switch @code{-P}, @code{gnatname} will create a
12244configuration pragmas file @file{gnat.adc} in the current working directory,
12245with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12246unit.
12247
12248@node Switches for gnatname
12249@section Switches for @code{gnatname}
12250
12251@noindent
12252Switches for @code{gnatname} must precede any specified Naming Pattern.
12253
12254@noindent
12255You may specify any of the following switches to @code{gnatname}:
12256
12257@table @option
12258@c !sort!
12259
12260@item --version
12261@cindex @option{--version} @command{gnatname}
12262Display Copyright and version, then exit disregarding all other options.
12263
12264@item --help
12265@cindex @option{--help} @command{gnatname}
12266If @option{--version} was not used, display usage, then exit disregarding
12267all other options.
12268
12269@item --subdirs=<dir>
12270Real object, library or exec directories are subdirectories <dir> of the
12271specified ones.
12272
12273@item --no-backup
12274Do not create a backup copy of an existing project file.
12275
12276@item --and
12277Start another section of directories/patterns.
12278
12279@item ^-c^/CONFIG_FILE=^@file{file}
12280@cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12281Create a configuration pragmas file @file{file} (instead of the default
12282@file{gnat.adc}).
12283@ifclear vms
12284There may be zero, one or more space between @option{-c} and
12285@file{file}.
12286@end ifclear
12287@file{file} may include directory information. @file{file} must be
12288writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12289When a switch @option{^-c^/CONFIG_FILE^} is
12290specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12291
12292@item ^-d^/SOURCE_DIRS=^@file{dir}
12293@cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12294Look for source files in directory @file{dir}. There may be zero, one or more
12295spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12296@file{dir} may end with @code{/**}, that is it may be of the form
12297@code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12298subdirectories, recursively, have to be searched for sources.
12299When a switch @option{^-d^/SOURCE_DIRS^}
12300is specified, the current working directory will not be searched for source
12301files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12302or @option{^-D^/DIR_FILES^} switch.
12303Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12304If @file{dir} is a relative path, it is relative to the directory of
12305the configuration pragmas file specified with switch
12306@option{^-c^/CONFIG_FILE^},
12307or to the directory of the project file specified with switch
12308@option{^-P^/PROJECT_FILE^} or,
12309if neither switch @option{^-c^/CONFIG_FILE^}
12310nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12311current working directory. The directory
12312specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12313
12314@item ^-D^/DIRS_FILE=^@file{file}
12315@cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12316Look for source files in all directories listed in text file @file{file}.
12317There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12318and @file{file}.
12319@file{file} must be an existing, readable text file.
12320Each nonempty line in @file{file} must be a directory.
12321Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12322switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12323@file{file}.
12324
12325@item -eL
12326Follow symbolic links when processing project files.
12327
12328@item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12329@cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12330Foreign patterns. Using this switch, it is possible to add sources of languages
12331other than Ada to the list of sources of a project file.
12332It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12333For example,
12334@smallexample
12335gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12336@end smallexample
12337@noindent
12338will look for Ada units in all files with the @file{.ada} extension,
12339and will add to the list of file for project @file{prj.gpr} the C files
12340with extension @file{.^c^C^}.
12341
12342@item ^-h^/HELP^
12343@cindex @option{^-h^/HELP^} (@code{gnatname})
12344Output usage (help) information. The output is written to @file{stdout}.
12345
12346@item ^-P^/PROJECT_FILE=^@file{proj}
12347@cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12348Create or update project file @file{proj}. There may be zero, one or more space
12349between @option{-P} and @file{proj}. @file{proj} may include directory
12350information. @file{proj} must be writable.
12351There may be only one switch @option{^-P^/PROJECT_FILE^}.
12352When a switch @option{^-P^/PROJECT_FILE^} is specified,
12353no switch @option{^-c^/CONFIG_FILE^} may be specified.
12354On all platforms, except on VMS, when @code{gnatname} is invoked for an
12355existing project file <proj>.gpr, a backup copy of the project file is created
12356in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12357non negative number that makes this backup copy a new file.
12358
12359@item ^-v^/VERBOSE^
12360@cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12361Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12362This includes name of the file written, the name of the directories to search
12363and, for each file in those directories whose name matches at least one of
12364the Naming Patterns, an indication of whether the file contains a unit,
12365and if so the name of the unit.
12366
12367@item ^-v -v^/VERBOSE /VERBOSE^
12368@cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12369Very Verbose mode. In addition to the output produced in verbose mode,
12370for each file in the searched directories whose name matches none of
12371the Naming Patterns, an indication is given that there is no match.
12372
12373@item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12374@cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12375Excluded patterns. Using this switch, it is possible to exclude some files
12376that would match the name patterns. For example,
12377@smallexample
12378gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12379@end smallexample
12380@noindent
12381will look for Ada units in all files with the @file{.ada} extension,
12382except those whose names end with @file{_nt.ada}.
12383
12384@end table
12385
12386@node Examples of gnatname Usage
12387@section Examples of @code{gnatname} Usage
12388
12389@ifset vms
12390@smallexample
12391$ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12392@end smallexample
12393@end ifset
12394
12395@ifclear vms
12396@smallexample
12397$ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12398@end smallexample
12399@end ifclear
12400
12401@noindent
12402In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12403and be writable. In addition, the directory
12404@file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12405@option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12406
12407@ifclear vms
12408Note the optional spaces after @option{-c} and @option{-d}.
12409@end ifclear
12410
12411@smallexample
12412@ifclear vms
12413$ gnatname -P/home/me/proj -x "*_nt_body.ada"
12414  -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12415@end ifclear
12416@ifset vms
12417$ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12418  /EXCLUDED_PATTERN=*_nt_body.ada
12419  /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12420  /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12421@end ifset
12422@end smallexample
12423
12424Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12425even in conjunction with one or several switches
12426@option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12427are used in this example.
12428
12429@c *****************************************
12430@c * G N A T  P r o j e c t  M a n a g e r *
12431@c *****************************************
12432
12433@c ------ macros for projects.texi
12434@c These macros are needed when building the gprbuild documentation, but
12435@c should have no effect in the gnat user's guide
12436
12437@macro CODESAMPLE{TXT}
12438@smallexample
12439@group
12440\TXT\
12441@end group
12442@end smallexample
12443@end macro
12444
12445@macro PROJECTFILE{TXT}
12446@CODESAMPLE{\TXT\}
12447@end macro
12448
12449@c simulates a newline when in a @CODESAMPLE
12450@macro NL{}
12451@end macro
12452
12453@macro TIP{TXT}
12454@quotation
12455@noindent
12456\TXT\
12457@end quotation
12458@end macro
12459
12460@macro TIPHTML{TXT}
12461\TXT\
12462@end macro
12463
12464@macro IMPORTANT{TXT}
12465@quotation
12466@noindent
12467\TXT\
12468@end quotation
12469
12470@end macro
12471
12472@macro NOTE{TXT}
12473@quotation
12474@noindent
12475\TXT\
12476@end quotation
12477@end macro
12478
12479@include projects.texi
12480
12481@c ---------------------------------------------
12482@c Tools Supporting Project Files
12483@c ---------------------------------------------
12484
12485@node Tools Supporting Project Files
12486@chapter Tools Supporting Project Files
12487
12488@noindent
12489
12490@menu
12491* gnatmake and Project Files::
12492* The GNAT Driver and Project Files::
12493@end menu
12494
12495@c ---------------------------------------------
12496@node gnatmake and Project Files
12497@section gnatmake and Project Files
12498@c ---------------------------------------------
12499
12500@noindent
12501This section covers several topics related to @command{gnatmake} and
12502project files: defining ^switches^switches^ for @command{gnatmake}
12503and for the tools that it invokes; specifying configuration pragmas;
12504the use of the @code{Main} attribute; building and rebuilding library project
12505files.
12506
12507@menu
12508* Switches Related to Project Files::
12509* Switches and Project Files::
12510* Specifying Configuration Pragmas::
12511* Project Files and Main Subprograms::
12512* Library Project Files::
12513@end menu
12514
12515@c ---------------------------------------------
12516@node Switches Related to Project Files
12517@subsection Switches Related to Project Files
12518@c ---------------------------------------------
12519
12520@noindent
12521The following switches are used by GNAT tools that support project files:
12522
12523@table @option
12524
12525@item ^-P^/PROJECT_FILE=^@var{project}
12526@cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12527Indicates the name of a project file. This project file will be parsed with
12528the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12529if any, and using the external references indicated
12530by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12531@ifclear vms
12532There may zero, one or more spaces between @option{-P} and @var{project}.
12533@end ifclear
12534
12535There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12536
12537Since the Project Manager parses the project file only after all the switches
12538on the command line are checked, the order of the switches
12539@option{^-P^/PROJECT_FILE^},
12540@option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12541or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12542
12543@item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12544@cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12545Indicates that external variable @var{name} has the value @var{value}.
12546The Project Manager will use this value for occurrences of
12547@code{external(name)} when parsing the project file.
12548
12549@ifclear vms
12550If @var{name} or @var{value} includes a space, then @var{name=value} should be
12551put between quotes.
12552@smallexample
12553  -XOS=NT
12554  -X"user=John Doe"
12555@end smallexample
12556@end ifclear
12557
12558Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12559If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12560@var{name}, only the last one is used.
12561
12562An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12563takes precedence over the value of the same name in the environment.
12564
12565@item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12566@cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12567Indicates the verbosity of the parsing of GNAT project files.
12568
12569@ifclear vms
12570@option{-vP0} means Default;
12571@option{-vP1} means Medium;
12572@option{-vP2} means High.
12573@end ifclear
12574
12575@ifset vms
12576There are three possible options for this qualifier: DEFAULT, MEDIUM and
12577HIGH.
12578@end ifset
12579
12580The default is ^Default^DEFAULT^: no output for syntactically correct
12581project files.
12582If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12583only the last one is used.
12584
12585@item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12586@cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12587Add directory <dir> at the beginning of the project search path, in order,
12588after the current working directory.
12589
12590@ifclear vms
12591@item -eL
12592@cindex @option{-eL} (any project-aware tool)
12593Follow all symbolic links when processing project files.
12594@end ifclear
12595
12596@item ^--subdirs^/SUBDIRS^=<subdir>
12597@cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12598This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12599indicate that the real directories (except the source directories) are the
12600subdirectories <subdir> of the directories specified in the project files.
12601This applies in particular to object directories, library directories and
12602exec directories. If the subdirectories do not exist, they are created
12603automatically.
12604
12605@end table
12606
12607@c ---------------------------------------------
12608@node Switches and Project Files
12609@subsection Switches and Project Files
12610@c ---------------------------------------------
12611
12612@noindent
12613@ifset vms
12614It is not currently possible to specify VMS style qualifiers in the project
12615files; only Unix style ^switches^switches^ may be specified.
12616@end ifset
12617
12618For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12619@code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12620attribute, a @code{Switches} attribute, or both;
12621as their names imply, these ^switch^switch^-related
12622attributes affect the ^switches^switches^ that are used for each of these GNAT
12623components when
12624@command{gnatmake} is invoked.  As will be explained below, these
12625component-specific ^switches^switches^ precede
12626the ^switches^switches^ provided on the @command{gnatmake} command line.
12627
12628The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12629indexed by language name (case insensitive) whose value is a string list.
12630For example:
12631
12632@smallexample @c projectfile
12633@group
12634package Compiler is
12635  for ^Default_Switches^Default_Switches^ ("Ada")
12636      use ("^-gnaty^-gnaty^",
12637           "^-v^-v^");
12638end Compiler;
12639@end group
12640@end smallexample
12641
12642@noindent
12643The @code{Switches} attribute is indexed on a file name (which may or may
12644not be case sensitive, depending
12645on the operating system) whose value is a string list.  For example:
12646
12647@smallexample @c projectfile
12648@group
12649package Builder is
12650   for Switches ("main1.adb")
12651       use ("^-O2^-O2^");
12652   for Switches ("main2.adb")
12653       use ("^-g^-g^");
12654end Builder;
12655@end group
12656@end smallexample
12657
12658@noindent
12659For the @code{Builder} package, the file names must designate source files
12660for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12661file names must designate @file{ALI} or source files for main subprograms.
12662In each case just the file name without an explicit extension is acceptable.
12663
12664For each tool used in a program build (@command{gnatmake}, the compiler, the
12665binder, and the linker), the corresponding package @dfn{contributes} a set of
12666^switches^switches^ for each file on which the tool is invoked, based on the
12667^switch^switch^-related attributes defined in the package.
12668In particular, the ^switches^switches^
12669that each of these packages contributes for a given file @var{f} comprise:
12670
12671@itemize @bullet
12672@item the value of attribute @code{Switches (@var{f})},
12673  if it is specified in the package for the given file,
12674@item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12675  if it is specified in the package.
12676
12677@end itemize
12678
12679@noindent
12680If neither of these attributes is defined in the package, then the package does
12681not contribute any ^switches^switches^ for the given file.
12682
12683When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12684two sets, in the following order: those contributed for the file
12685by the @code{Builder} package;
12686and the switches passed on the command line.
12687
12688When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12689the ^switches^switches^ passed to the tool comprise three sets,
12690in the following order:
12691
12692@enumerate
12693@item
12694the applicable ^switches^switches^ contributed for the file
12695by the @code{Builder} package in the project file supplied on the command line;
12696
12697@item
12698those contributed for the file by the package (in the relevant project file --
12699see below) corresponding to the tool; and
12700
12701@item
12702the applicable switches passed on the command line.
12703@end enumerate
12704
12705The term @emph{applicable ^switches^switches^} reflects the fact that
12706@command{gnatmake} ^switches^switches^ may or may not be passed to individual
12707tools, depending on the individual ^switch^switch^.
12708
12709@command{gnatmake} may invoke the compiler on source files from different
12710projects. The Project Manager will use the appropriate project file to
12711determine the @code{Compiler} package for each source file being compiled.
12712Likewise for the @code{Binder} and @code{Linker} packages.
12713
12714As an example, consider the following package in a project file:
12715
12716@smallexample @c projectfile
12717@group
12718project Proj1 is
12719   package Compiler is
12720      for ^Default_Switches^Default_Switches^ ("Ada")
12721          use ("^-g^-g^");
12722      for Switches ("a.adb")
12723          use ("^-O1^-O1^");
12724      for Switches ("b.adb")
12725          use ("^-O2^-O2^",
12726               "^-gnaty^-gnaty^");
12727   end Compiler;
12728end Proj1;
12729@end group
12730@end smallexample
12731
12732@noindent
12733If @command{gnatmake} is invoked with this project file, and it needs to
12734compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12735@file{a.adb} will be compiled with the ^switch^switch^
12736@option{^-O1^-O1^},
12737@file{b.adb} with ^switches^switches^
12738@option{^-O2^-O2^}
12739and @option{^-gnaty^-gnaty^},
12740and @file{c.adb} with @option{^-g^-g^}.
12741
12742The following example illustrates the ordering of the ^switches^switches^
12743contributed by different packages:
12744
12745@smallexample @c projectfile
12746@group
12747project Proj2 is
12748   package Builder is
12749      for Switches ("main.adb")
12750          use ("^-g^-g^",
12751               "^-O1^-)1^",
12752               "^-f^-f^");
12753   end Builder;
12754@end group
12755
12756@group
12757   package Compiler is
12758      for Switches ("main.adb")
12759          use ("^-O2^-O2^");
12760   end Compiler;
12761end Proj2;
12762@end group
12763@end smallexample
12764
12765@noindent
12766If you issue the command:
12767
12768@smallexample
12769    gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12770@end smallexample
12771
12772@noindent
12773then the compiler will be invoked on @file{main.adb} with the following
12774sequence of ^switches^switches^
12775
12776@smallexample
12777   ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12778@end smallexample
12779
12780@noindent
12781with the last @option{^-O^-O^}
12782^switch^switch^ having precedence over the earlier ones;
12783several other ^switches^switches^
12784(such as @option{^-c^-c^}) are added implicitly.
12785
12786The ^switches^switches^
12787@option{^-g^-g^}
12788and @option{^-O1^-O1^} are contributed by package
12789@code{Builder},  @option{^-O2^-O2^} is contributed
12790by the package @code{Compiler}
12791and @option{^-O0^-O0^} comes from the command line.
12792
12793The @option{^-g^-g^}
12794^switch^switch^ will also be passed in the invocation of
12795@command{Gnatlink.}
12796
12797A final example illustrates switch contributions from packages in different
12798project files:
12799
12800@smallexample @c projectfile
12801@group
12802project Proj3 is
12803   for Source_Files use ("pack.ads", "pack.adb");
12804   package Compiler is
12805      for ^Default_Switches^Default_Switches^ ("Ada")
12806          use ("^-gnata^-gnata^");
12807   end Compiler;
12808end Proj3;
12809@end group
12810
12811@group
12812with "Proj3";
12813project Proj4 is
12814   for Source_Files use ("foo_main.adb", "bar_main.adb");
12815   package Builder is
12816      for Switches ("foo_main.adb")
12817          use ("^-s^-s^",
12818               "^-g^-g^");
12819   end Builder;
12820end Proj4;
12821@end group
12822
12823@group
12824-- Ada source file:
12825with Pack;
12826procedure Foo_Main is
12827   @dots{}
12828end Foo_Main;
12829@end group
12830@end smallexample
12831
12832@noindent
12833If the command is
12834@smallexample
12835gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12836@end smallexample
12837
12838@noindent
12839then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12840@option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12841@option{^-gnato^-gnato^} (passed on the command line).
12842When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12843are @option{^-g^-g^} from @code{Proj4.Builder},
12844@option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12845and @option{^-gnato^-gnato^} from the command line.
12846
12847When using @command{gnatmake} with project files, some ^switches^switches^ or
12848arguments may be expressed as relative paths. As the working directory where
12849compilation occurs may change, these relative paths are converted to absolute
12850paths. For the ^switches^switches^ found in a project file, the relative paths
12851are relative to the project file directory, for the switches on the command
12852line, they are relative to the directory where @command{gnatmake} is invoked.
12853The ^switches^switches^ for which this occurs are:
12854^-I^-I^,
12855^-A^-A^,
12856^-L^-L^,
12857^-aO^-aO^,
12858^-aL^-aL^,
12859^-aI^-aI^, as well as all arguments that are not switches (arguments to
12860^switch^switch^
12861^-o^-o^, object files specified in package @code{Linker} or after
12862-largs on the command line). The exception to this rule is the ^switch^switch^
12863^--RTS=^--RTS=^ for which a relative path argument is never converted.
12864
12865@c ---------------------------------------------
12866@node Specifying Configuration Pragmas
12867@subsection Specifying Configuration Pragmas
12868@c ---------------------------------------------
12869
12870@noindent
12871When using @command{gnatmake} with project files, if there exists a file
12872@file{gnat.adc} that contains configuration pragmas, this file will be
12873ignored.
12874
12875Configuration pragmas can be defined by means of the following attributes in
12876project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12877and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12878
12879Both these attributes are single string attributes. Their values is the path
12880name of a file containing configuration pragmas. If a path name is relative,
12881then it is relative to the project directory of the project file where the
12882attribute is defined.
12883
12884When compiling a source, the configuration pragmas used are, in order,
12885those listed in the file designated by attribute
12886@code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12887project file, if it is specified, and those listed in the file designated by
12888attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12889the project file of the source, if it exists.
12890
12891@c ---------------------------------------------
12892@node Project Files and Main Subprograms
12893@subsection Project Files and Main Subprograms
12894@c ---------------------------------------------
12895
12896@noindent
12897When using a project file, you can invoke @command{gnatmake}
12898with one or several main subprograms, by specifying their source files on the
12899command line.
12900
12901@smallexample
12902    gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12903@end smallexample
12904
12905@noindent
12906Each of these needs to be a source file of the same project, except
12907when the switch ^-u^/UNIQUE^ is used.
12908
12909When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12910same project, one of the project in the tree rooted at the project specified
12911on the command line. The package @code{Builder} of this common project, the
12912"main project" is the one that is considered by @command{gnatmake}.
12913
12914When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12915imported directly or indirectly by the project specified on the command line.
12916Note that if such a source file is not part of the project specified on the
12917command line, the ^switches^switches^ found in package @code{Builder} of the
12918project specified on the command line, if any, that are transmitted
12919to the compiler will still be used, not those found in the project file of
12920the source file.
12921
12922When using a project file, you can also invoke @command{gnatmake} without
12923explicitly specifying any main, and the effect depends on whether you have
12924defined the @code{Main} attribute.  This attribute has a string list value,
12925where each element in the list is the name of a source file (the file
12926extension is optional) that contains a unit that can be a main subprogram.
12927
12928If the @code{Main} attribute is defined in a project file as a non-empty
12929string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12930line, then invoking @command{gnatmake} with this project file but without any
12931main on the command line is equivalent to invoking @command{gnatmake} with all
12932the file names in the @code{Main} attribute on the command line.
12933
12934Example:
12935@smallexample @c projectfile
12936@group
12937   project Prj is
12938      for Main use ("main1.adb", "main2.adb", "main3.adb");
12939   end Prj;
12940@end group
12941@end smallexample
12942
12943@noindent
12944With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12945is equivalent to
12946@code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
12947
12948When the project attribute @code{Main} is not specified, or is specified
12949as an empty string list, or when the switch @option{-u} is used on the command
12950line, then invoking @command{gnatmake} with no main on the command line will
12951result in all immediate sources of the project file being checked, and
12952potentially recompiled. Depending on the presence of the switch @option{-u},
12953sources from other project files on which the immediate sources of the main
12954project file depend are also checked and potentially recompiled. In other
12955words, the @option{-u} switch is applied to all of the immediate sources of the
12956main project file.
12957
12958When no main is specified on the command line and attribute @code{Main} exists
12959and includes several mains, or when several mains are specified on the
12960command line, the default ^switches^switches^ in package @code{Builder} will
12961be used for all mains, even if there are specific ^switches^switches^
12962specified for one or several mains.
12963
12964But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12965the specific ^switches^switches^ for each main, if they are specified.
12966
12967@c ---------------------------------------------
12968@node Library Project Files
12969@subsection Library Project Files
12970@c ---------------------------------------------
12971
12972@noindent
12973When @command{gnatmake} is invoked with a main project file that is a library
12974project file, it is not allowed to specify one or more mains on the command
12975line.
12976
12977When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12978^-l^/ACTION=LINK^ have special meanings.
12979
12980@itemize @bullet
12981@item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
12982  to @command{gnatmake} that @command{gnatbind} should be invoked for the
12983  library.
12984
12985@item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
12986  to @command{gnatmake} that the binder generated file should be compiled
12987  (in the case of a stand-alone library) and that the library should be built.
12988@end itemize
12989
12990@c ---------------------------------------------
12991@node The GNAT Driver and Project Files
12992@section The GNAT Driver and Project Files
12993@c ---------------------------------------------
12994
12995@noindent
12996A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
12997can benefit from project files:
12998(@command{^gnatbind^gnatbind^},
12999@ifclear FSFEDITION
13000@command{^gnatcheck^gnatcheck^},
13001@end ifclear
13002@command{^gnatclean^gnatclean^},
13003@ifclear FSFEDITION
13004@command{^gnatelim^gnatelim^},
13005@end ifclear
13006@command{^gnatfind^gnatfind^},
13007@command{^gnatlink^gnatlink^},
13008@command{^gnatls^gnatls^},
13009@ifclear FSFEDITION
13010@command{^gnatmetric^gnatmetric^},
13011@command{^gnatpp^gnatpp^},
13012@command{^gnatstub^gnatstub^},
13013@end ifclear
13014and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
13015directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13016They must be invoked through the @command{gnat} driver.
13017
13018The @command{gnat} driver is a wrapper that accepts a number of commands and
13019calls the corresponding tool. It was designed initially for VMS platforms (to
13020convert VMS qualifiers to Unix-style switches), but it is now available on all
13021GNAT platforms.
13022
13023On non-VMS platforms, the @command{gnat} driver accepts the following commands
13024(case insensitive):
13025
13026@itemize @bullet
13027@item BIND to invoke @command{^gnatbind^gnatbind^}
13028@item CHOP to invoke @command{^gnatchop^gnatchop^}
13029@item CLEAN to invoke @command{^gnatclean^gnatclean^}
13030@item COMP or COMPILE to invoke the compiler
13031@ifclear FSFEDITION
13032@item ELIM to invoke @command{^gnatelim^gnatelim^}
13033@end ifclear
13034@item FIND to invoke @command{^gnatfind^gnatfind^}
13035@item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13036@item LINK to invoke @command{^gnatlink^gnatlink^}
13037@item LS or LIST to invoke @command{^gnatls^gnatls^}
13038@item MAKE to invoke @command{^gnatmake^gnatmake^}
13039@item NAME to invoke @command{^gnatname^gnatname^}
13040@item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13041@ifclear FSFEDITION
13042@item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13043@item METRIC to invoke @command{^gnatmetric^gnatmetric^}
13044@item STUB to invoke @command{^gnatstub^gnatstub^}
13045@end ifclear
13046@item XREF to invoke @command{^gnatxref^gnatxref^}
13047
13048@end itemize
13049
13050@noindent
13051(note that the compiler is invoked using the command
13052@command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13053
13054On non-VMS platforms, between @command{gnat} and the command, two
13055special switches may be used:
13056
13057@itemize @bullet
13058@item @command{-v} to display the invocation of the tool.
13059@item @command{-dn} to prevent the @command{gnat} driver from removing
13060  the temporary files it has created. These temporary files are
13061  configuration files and temporary file list files.
13062
13063@end itemize
13064
13065@noindent
13066The command may be followed by switches and arguments for the invoked
13067tool.
13068
13069@smallexample
13070  gnat bind -C main.ali
13071  gnat ls -a main
13072  gnat chop foo.txt
13073@end smallexample
13074
13075@noindent
13076Switches may also be put in text files, one switch per line, and the text
13077files may be specified with their path name preceded by '@@'.
13078
13079@smallexample
13080   gnat bind @@args.txt main.ali
13081@end smallexample
13082
13083@noindent
13084In addition, for commands BIND, COMP or COMPILE, FIND,
13085@ifclear FSFEDITION
13086ELIM,
13087@end ifclear
13088LS or LIST, LINK,
13089@ifclear FSFEDITION
13090METRIC,
13091PP or PRETTY,
13092STUB,
13093@end ifclear
13094and XREF, the project file related switches
13095(@option{^-P^/PROJECT_FILE^},
13096@option{^-X^/EXTERNAL_REFERENCE^} and
13097@option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13098the switches of the invoking tool.
13099
13100@ifclear FSFEDITION
13101When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13102specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13103the immediate sources of the specified project file.
13104@end ifclear
13105
13106@ifclear FSFEDITION
13107When GNAT METRIC is used with a project file, but with no source
13108specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13109with all the immediate sources of the specified project file and with
13110@option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13111of the project.
13112@end ifclear
13113
13114@ifclear FSFEDITION
13115In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13116a project file, no source is specified on the command line and
13117switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13118the underlying tool (^gnatpp^gnatpp^ or
13119^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13120not only for the immediate sources of the main project.
13121@ifclear vms
13122(-U stands for Universal or Union of the project files of the project tree)
13123@end ifclear
13124@end ifclear
13125
13126For each of the following commands, there is optionally a corresponding
13127package in the main project.
13128
13129@itemize @bullet
13130@item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13131
13132@ifclear FSFEDITION
13133@item package @code{Check} for command CHECK (invoking
13134  @code{^gnatcheck^gnatcheck^})
13135@end ifclear
13136
13137@item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13138
13139@item package @code{Cross_Reference} for command XREF (invoking
13140  @code{^gnatxref^gnatxref^})
13141
13142@ifclear FSFEDITION
13143@item package @code{Eliminate} for command ELIM (invoking
13144  @code{^gnatelim^gnatelim^})
13145@end ifclear
13146
13147@item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13148
13149@item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13150
13151@ifclear FSFEDITION
13152@item package @code{Gnatstub} for command STUB
13153  (invoking @code{^gnatstub^gnatstub^})
13154@end ifclear
13155
13156@item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13157
13158@ifclear FSFEDITION
13159@item package @code{Check} for command CHECK
13160  (invoking @code{^gnatcheck^gnatcheck^})
13161@end ifclear
13162
13163@ifclear FSFEDITION
13164@item package @code{Metrics} for command METRIC
13165  (invoking @code{^gnatmetric^gnatmetric^})
13166@end ifclear
13167
13168@ifclear FSFEDITION
13169@item package @code{Pretty_Printer} for command PP or PRETTY
13170  (invoking @code{^gnatpp^gnatpp^})
13171@end ifclear
13172
13173@end itemize
13174
13175@noindent
13176Package @code{Gnatls} has a unique attribute @code{Switches},
13177a simple variable with a string list value. It contains ^switches^switches^
13178for the invocation of @code{^gnatls^gnatls^}.
13179
13180@smallexample @c projectfile
13181@group
13182project Proj1 is
13183   package gnatls is
13184      for Switches
13185          use ("^-a^-a^",
13186               "^-v^-v^");
13187   end gnatls;
13188end Proj1;
13189@end group
13190@end smallexample
13191
13192@noindent
13193All other packages have two attribute @code{Switches} and
13194@code{^Default_Switches^Default_Switches^}.
13195
13196@code{Switches} is an indexed attribute, indexed by the
13197source file name, that has a string list value: the ^switches^switches^ to be
13198used when the tool corresponding to the package is invoked for the specific
13199source file.
13200
13201@code{^Default_Switches^Default_Switches^} is an attribute,
13202indexed by  the programming language that has a string list value.
13203@code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13204^switches^switches^ for the invocation of the tool corresponding
13205to the package, except if a specific @code{Switches} attribute
13206is specified for the source file.
13207
13208@smallexample @c projectfile
13209@group
13210project Proj is
13211
13212   for Source_Dirs use ("**");
13213
13214   package gnatls is
13215      for Switches use
13216          ("^-a^-a^",
13217           "^-v^-v^");
13218   end gnatls;
13219@end group
13220@group
13221
13222   package Compiler is
13223      for ^Default_Switches^Default_Switches^ ("Ada")
13224          use ("^-gnatv^-gnatv^",
13225               "^-gnatwa^-gnatwa^");
13226   end Binder;
13227@end group
13228@group
13229
13230   package Binder is
13231      for ^Default_Switches^Default_Switches^ ("Ada")
13232          use ("^-C^-C^",
13233               "^-e^-e^");
13234   end Binder;
13235@end group
13236@group
13237
13238   package Linker is
13239      for ^Default_Switches^Default_Switches^ ("Ada")
13240          use ("^-C^-C^");
13241      for Switches ("main.adb")
13242          use ("^-C^-C^",
13243               "^-v^-v^",
13244               "^-v^-v^");
13245   end Linker;
13246@end group
13247@group
13248
13249   package Finder is
13250      for ^Default_Switches^Default_Switches^ ("Ada")
13251           use ("^-a^-a^",
13252                "^-f^-f^");
13253   end Finder;
13254@end group
13255@group
13256
13257   package Cross_Reference is
13258      for ^Default_Switches^Default_Switches^ ("Ada")
13259          use ("^-a^-a^",
13260               "^-f^-f^",
13261               "^-d^-d^",
13262               "^-u^-u^");
13263   end Cross_Reference;
13264end Proj;
13265@end group
13266@end smallexample
13267
13268@noindent
13269With the above project file, commands such as
13270
13271@smallexample
13272   ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13273   ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13274   ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13275   ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13276   ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13277@end smallexample
13278
13279@noindent
13280will set up the environment properly and invoke the tool with the switches
13281found in the package corresponding to the tool:
13282@code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13283except @code{Switches ("main.adb")}
13284for @code{^gnatlink^gnatlink^}.
13285@ifclear FSFEDITION
13286It is also possible to invoke some of the tools,
13287(@code{^gnatcheck^gnatcheck^},
13288@code{^gnatmetric^gnatmetric^},
13289and @code{^gnatpp^gnatpp^})
13290on a set of project units thanks to the combination of the switches
13291@option{-P}, @option{-U} and possibly the main unit when one is interested
13292in its closure. For instance,
13293@smallexample
13294gnat metric -Pproj
13295@end smallexample
13296
13297@noindent
13298will compute the metrics for all the immediate units of project
13299@code{proj}.
13300@smallexample
13301gnat metric -Pproj -U
13302@end smallexample
13303
13304@noindent
13305will compute the metrics for all the units of the closure of projects
13306rooted at @code{proj}.
13307@smallexample
13308gnat metric -Pproj -U main_unit
13309@end smallexample
13310
13311@noindent
13312will compute the metrics for the closure of units rooted at
13313@code{main_unit}. This last possibility relies implicitly
13314on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13315tool invoked by the @command{gnat} driver are explicitly  specified
13316either directly or through the tool @option{-files} option, then the tool
13317is called only for these explicitly specified files.
13318@end ifclear
13319
13320@c *****************************************
13321@c * Cross-referencing tools
13322@c *****************************************
13323
13324@node The Cross-Referencing Tools gnatxref and gnatfind
13325@chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13326@findex gnatxref
13327@findex gnatfind
13328
13329@noindent
13330The compiler generates cross-referencing information (unless
13331you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13332This information indicates where in the source each entity is declared and
13333referenced. Note that entities in package Standard are not included, but
13334entities in all other predefined units are included in the output.
13335
13336Before using any of these two tools, you need to compile successfully your
13337application, so that GNAT gets a chance to generate the cross-referencing
13338information.
13339
13340The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13341information to provide the user with the capability to easily locate the
13342declaration and references to an entity. These tools are quite similar,
13343the difference being that @code{gnatfind} is intended for locating
13344definitions and/or references to a specified entity or entities, whereas
13345@code{gnatxref} is oriented to generating a full report of all
13346cross-references.
13347
13348To use these tools, you must not compile your application using the
13349@option{-gnatx} switch on the @command{gnatmake} command line
13350(@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13351information will not be generated.
13352
13353Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13354use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13355
13356@menu
13357* Switches for gnatxref::
13358* Switches for gnatfind::
13359* Project Files for gnatxref and gnatfind::
13360* Regular Expressions in gnatfind and gnatxref::
13361* Examples of gnatxref Usage::
13362* Examples of gnatfind Usage::
13363@end menu
13364
13365@node Switches for gnatxref
13366@section @code{gnatxref} Switches
13367
13368@noindent
13369The command invocation for @code{gnatxref} is:
13370@smallexample
13371@c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13372@c Expanding @ovar macro inline (explanation in macro def comments)
13373$ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13374@end smallexample
13375
13376@noindent
13377where
13378
13379@table @var
13380@item sourcefile1
13381@itemx sourcefile2
13382identifies the source files for which a report is to be generated. The
13383``with''ed units will be processed too. You must provide at least one file.
13384
13385These file names are considered to be regular expressions, so for instance
13386specifying @file{source*.adb} is the same as giving every file in the current
13387directory whose name starts with @file{source} and whose extension is
13388@file{adb}.
13389
13390You shouldn't specify any directory name, just base names. @command{gnatxref}
13391and @command{gnatfind} will be able to locate these files by themselves using
13392the source path. If you specify directories, no result is produced.
13393
13394@end table
13395
13396@noindent
13397The switches can be:
13398@table @option
13399@c !sort!
13400@item --version
13401@cindex @option{--version} @command{gnatxref}
13402Display Copyright and version, then exit disregarding all other options.
13403
13404@item --help
13405@cindex @option{--help} @command{gnatxref}
13406If @option{--version} was not used, display usage, then exit disregarding
13407all other options.
13408
13409@item ^-a^/ALL_FILES^
13410@cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13411If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13412the read-only files found in the library search path. Otherwise, these files
13413will be ignored. This option can be used to protect Gnat sources or your own
13414libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13415much faster, and their output much smaller. Read-only here refers to access
13416or permissions status in the file system for the current user.
13417
13418@item -aIDIR
13419@cindex @option{-aIDIR} (@command{gnatxref})
13420When looking for source files also look in directory DIR. The order in which
13421source file search is undertaken is the same as for @command{gnatmake}.
13422
13423@item -aODIR
13424@cindex @option{-aODIR} (@command{gnatxref})
13425When searching for library and object files, look in directory
13426DIR. The order in which library files are searched is the same as for
13427@command{gnatmake}.
13428
13429@item -nostdinc
13430@cindex @option{-nostdinc} (@command{gnatxref})
13431Do not look for sources in the system default directory.
13432
13433@item -nostdlib
13434@cindex @option{-nostdlib} (@command{gnatxref})
13435Do not look for library files in the system default directory.
13436
13437@item --ext=@var{extension}
13438@cindex @option{--ext} (@command{gnatxref})
13439Specify an alternate ali file extension. The default is @code{ali} and other
13440extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13441may be specified via this switch. Note that if this switch overrides the
13442default, which means that only the new extension will be considered.
13443
13444@item --RTS=@var{rts-path}
13445@cindex @option{--RTS} (@command{gnatxref})
13446Specifies the default location of the runtime library. Same meaning as the
13447equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13448
13449@item ^-d^/DERIVED_TYPES^
13450@cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13451If this switch is set @code{gnatxref} will output the parent type
13452reference for each matching derived types.
13453
13454@item ^-f^/FULL_PATHNAME^
13455@cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13456If this switch is set, the output file names will be preceded by their
13457directory (if the file was found in the search path). If this switch is
13458not set, the directory will not be printed.
13459
13460@item ^-g^/IGNORE_LOCALS^
13461@cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13462If this switch is set, information is output only for library-level
13463entities, ignoring local entities. The use of this switch may accelerate
13464@code{gnatfind} and @code{gnatxref}.
13465
13466@item -IDIR
13467@cindex @option{-IDIR} (@command{gnatxref})
13468Equivalent to @samp{-aODIR -aIDIR}.
13469
13470@item -pFILE
13471@cindex @option{-pFILE} (@command{gnatxref})
13472Specify a project file to use @xref{GNAT Project Manager}.
13473If you need to use the @file{.gpr}
13474project files, you should use gnatxref through the GNAT driver
13475(@command{gnat xref -Pproject}).
13476
13477By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13478project file in the current directory.
13479
13480If a project file is either specified or found by the tools, then the content
13481of the source directory and object directory lines are added as if they
13482had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13483and @samp{^-aO^OBJECT_SEARCH^}.
13484@item ^-u^/UNUSED^
13485Output only unused symbols. This may be really useful if you give your
13486main compilation unit on the command line, as @code{gnatxref} will then
13487display every unused entity and 'with'ed package.
13488
13489@ifclear vms
13490@item -v
13491Instead of producing the default output, @code{gnatxref} will generate a
13492@file{tags} file that can be used by vi. For examples how to use this
13493feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13494to the standard output, thus you will have to redirect it to a file.
13495@end ifclear
13496
13497@end table
13498
13499@noindent
13500All these switches may be in any order on the command line, and may even
13501appear after the file names. They need not be separated by spaces, thus
13502you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13503@samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13504
13505@node Switches for gnatfind
13506@section @code{gnatfind} Switches
13507
13508@noindent
13509The command line for @code{gnatfind} is:
13510
13511@smallexample
13512@c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13513@c       @r{[}@var{file1} @var{file2} @dots{}]
13514@c Expanding @ovar macro inline (explanation in macro def comments)
13515$ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13516      @r{[}@var{file1} @var{file2} @dots{}@r{]}
13517@end smallexample
13518
13519@noindent
13520where
13521
13522@table @var
13523@item pattern
13524An entity will be output only if it matches the regular expression found
13525in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13526
13527Omitting the pattern is equivalent to specifying @samp{*}, which
13528will match any entity. Note that if you do not provide a pattern, you
13529have to provide both a sourcefile and a line.
13530
13531Entity names are given in Latin-1, with uppercase/lowercase equivalence
13532for matching purposes. At the current time there is no support for
135338-bit codes other than Latin-1, or for wide characters in identifiers.
13534
13535@item sourcefile
13536@code{gnatfind} will look for references, bodies or declarations
13537of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13538and column @var{column}. See @ref{Examples of gnatfind Usage}
13539for syntax examples.
13540
13541@item line
13542is a decimal integer identifying the line number containing
13543the reference to the entity (or entities) to be located.
13544
13545@item column
13546is a decimal integer identifying the exact location on the
13547line of the first character of the identifier for the
13548entity reference. Columns are numbered from 1.
13549
13550@item file1 file2 @dots{}
13551The search will be restricted to these source files. If none are given, then
13552the search will be done for every library file in the search path.
13553These file must appear only after the pattern or sourcefile.
13554
13555These file names are considered to be regular expressions, so for instance
13556specifying @file{source*.adb} is the same as giving every file in the current
13557directory whose name starts with @file{source} and whose extension is
13558@file{adb}.
13559
13560The location of the spec of the entity will always be displayed, even if it
13561isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
13562occurrences of the entity in the separate units of the ones given on the
13563command line will also be displayed.
13564
13565Note that if you specify at least one file in this part, @code{gnatfind} may
13566sometimes not be able to find the body of the subprograms.
13567
13568@end table
13569
13570@noindent
13571At least one of 'sourcefile' or 'pattern' has to be present on
13572the command line.
13573
13574The following switches are available:
13575@table @option
13576@c !sort!
13577
13578@cindex @option{--version} @command{gnatfind}
13579Display Copyright and version, then exit disregarding all other options.
13580
13581@item --help
13582@cindex @option{--help} @command{gnatfind}
13583If @option{--version} was not used, display usage, then exit disregarding
13584all other options.
13585
13586@item ^-a^/ALL_FILES^
13587@cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13588If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13589the read-only files found in the library search path. Otherwise, these files
13590will be ignored. This option can be used to protect Gnat sources or your own
13591libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13592much faster, and their output much smaller. Read-only here refers to access
13593or permission status in the file system for the current user.
13594
13595@item -aIDIR
13596@cindex @option{-aIDIR} (@command{gnatfind})
13597When looking for source files also look in directory DIR. The order in which
13598source file search is undertaken is the same as for @command{gnatmake}.
13599
13600@item -aODIR
13601@cindex @option{-aODIR} (@command{gnatfind})
13602When searching for library and object files, look in directory
13603DIR. The order in which library files are searched is the same as for
13604@command{gnatmake}.
13605
13606@item -nostdinc
13607@cindex @option{-nostdinc} (@command{gnatfind})
13608Do not look for sources in the system default directory.
13609
13610@item -nostdlib
13611@cindex @option{-nostdlib} (@command{gnatfind})
13612Do not look for library files in the system default directory.
13613
13614@item --ext=@var{extension}
13615@cindex @option{--ext} (@command{gnatfind})
13616Specify an alternate ali file extension. The default is @code{ali} and other
13617extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13618may be specified via this switch. Note that if this switch overrides the
13619default, which means that only the new extension will be considered.
13620
13621@item --RTS=@var{rts-path}
13622@cindex @option{--RTS} (@command{gnatfind})
13623Specifies the default location of the runtime library. Same meaning as the
13624equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13625
13626@item ^-d^/DERIVED_TYPE_INFORMATION^
13627@cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13628If this switch is set, then @code{gnatfind} will output the parent type
13629reference for each matching derived types.
13630
13631@item ^-e^/EXPRESSIONS^
13632@cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13633By default, @code{gnatfind} accept the simple regular expression set for
13634@samp{pattern}. If this switch is set, then the pattern will be
13635considered as full Unix-style regular expression.
13636
13637@item ^-f^/FULL_PATHNAME^
13638@cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13639If this switch is set, the output file names will be preceded by their
13640directory (if the file was found in the search path). If this switch is
13641not set, the directory will not be printed.
13642
13643@item ^-g^/IGNORE_LOCALS^
13644@cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13645If this switch is set, information is output only for library-level
13646entities, ignoring local entities. The use of this switch may accelerate
13647@code{gnatfind} and @code{gnatxref}.
13648
13649@item -IDIR
13650@cindex @option{-IDIR} (@command{gnatfind})
13651Equivalent to @samp{-aODIR -aIDIR}.
13652
13653@item -pFILE
13654@cindex @option{-pFILE} (@command{gnatfind})
13655Specify a project file (@pxref{GNAT Project Manager}) to use.
13656By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13657project file in the current directory.
13658
13659If a project file is either specified or found by the tools, then the content
13660of the source directory and object directory lines are added as if they
13661had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13662@samp{^-aO^/OBJECT_SEARCH^}.
13663
13664@item ^-r^/REFERENCES^
13665@cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13666By default, @code{gnatfind} will output only the information about the
13667declaration, body or type completion of the entities. If this switch is
13668set, the @code{gnatfind} will locate every reference to the entities in
13669the files specified on the command line (or in every file in the search
13670path if no file is given on the command line).
13671
13672@item ^-s^/PRINT_LINES^
13673@cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13674If this switch is set, then @code{gnatfind} will output the content
13675of the Ada source file lines were the entity was found.
13676
13677@item ^-t^/TYPE_HIERARCHY^
13678@cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13679If this switch is set, then @code{gnatfind} will output the type hierarchy for
13680the specified type. It act like -d option but recursively from parent
13681type to parent type. When this switch is set it is not possible to
13682specify more than one file.
13683
13684@end table
13685
13686@noindent
13687All these switches may be in any order on the command line, and may even
13688appear after the file names. They need not be separated by spaces, thus
13689you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13690@samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13691
13692As stated previously, gnatfind will search in every directory in the
13693search path. You can force it to look only in the current directory if
13694you specify @code{*} at the end of the command line.
13695
13696@node Project Files for gnatxref and gnatfind
13697@section Project Files for @command{gnatxref} and @command{gnatfind}
13698
13699@noindent
13700Project files allow a programmer to specify how to compile its
13701application, where to find sources, etc.  These files are used
13702@ifclear vms
13703primarily by GPS, but they can also be used
13704@end ifclear
13705by the two tools
13706@code{gnatxref} and @code{gnatfind}.
13707
13708A project file name must end with @file{.gpr}. If a single one is
13709present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13710extract the information from it. If multiple project files are found, none of
13711them is read, and you have to use the @samp{-p} switch to specify the one
13712you want to use.
13713
13714The following lines can be included, even though most of them have default
13715values which can be used in most cases.
13716The lines can be entered in any order in the file.
13717Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13718each line. If you have multiple instances, only the last one is taken into
13719account.
13720
13721@table @code
13722@item src_dir=DIR
13723[default: @code{"^./^[]^"}]
13724specifies a directory where to look for source files. Multiple @code{src_dir}
13725lines can be specified and they will be searched in the order they
13726are specified.
13727
13728@item obj_dir=DIR
13729[default: @code{"^./^[]^"}]
13730specifies a directory where to look for object and library files. Multiple
13731@code{obj_dir} lines can be specified, and they will be searched in the order
13732they are specified
13733
13734@item comp_opt=SWITCHES
13735[default: @code{""}]
13736creates a variable which can be referred to subsequently by using
13737the @code{$@{comp_opt@}} notation. This is intended to store the default
13738switches given to @command{gnatmake} and @command{gcc}.
13739
13740@item bind_opt=SWITCHES
13741[default: @code{""}]
13742creates a variable which can be referred to subsequently by using
13743the @samp{$@{bind_opt@}} notation. This is intended to store the default
13744switches given to @command{gnatbind}.
13745
13746@item link_opt=SWITCHES
13747[default: @code{""}]
13748creates a variable which can be referred to subsequently by using
13749the @samp{$@{link_opt@}} notation. This is intended to store the default
13750switches given to @command{gnatlink}.
13751
13752@item main=EXECUTABLE
13753[default: @code{""}]
13754specifies the name of the executable for the application. This variable can
13755be referred to in the following lines by using the @samp{$@{main@}} notation.
13756
13757@ifset vms
13758@item comp_cmd=COMMAND
13759[default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13760@end ifset
13761@ifclear vms
13762@item comp_cmd=COMMAND
13763[default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13764@end ifclear
13765specifies the command used to compile a single file in the application.
13766
13767@ifset vms
13768@item make_cmd=COMMAND
13769[default: @code{"GNAT MAKE $@{main@}
13770/SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13771/DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13772/BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13773@end ifset
13774@ifclear vms
13775@item make_cmd=COMMAND
13776[default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13777-aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13778-bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13779@end ifclear
13780specifies the command used to recompile the whole application.
13781
13782@item run_cmd=COMMAND
13783[default: @code{"$@{main@}"}]
13784specifies the command used to run the application.
13785
13786@item debug_cmd=COMMAND
13787[default: @code{"gdb $@{main@}"}]
13788specifies the command used to debug the application
13789
13790@end table
13791
13792@noindent
13793@command{gnatxref} and @command{gnatfind} only take into account the
13794@code{src_dir} and @code{obj_dir} lines, and ignore the others.
13795
13796@node Regular Expressions in gnatfind and gnatxref
13797@section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13798
13799@noindent
13800As specified in the section about @command{gnatfind}, the pattern can be a
13801regular expression. Actually, there are to set of regular expressions
13802which are recognized by the program:
13803
13804@table @code
13805@item globbing patterns
13806These are the most usual regular expression. They are the same that you
13807generally used in a Unix shell command line, or in a DOS session.
13808
13809Here is a more formal grammar:
13810@smallexample
13811@group
13812@iftex
13813@leftskip=.5cm
13814@end iftex
13815regexp ::= term
13816term   ::= elmt            -- matches elmt
13817term   ::= elmt elmt       -- concatenation (elmt then elmt)
13818term   ::= *               -- any string of 0 or more characters
13819term   ::= ?               -- matches any character
13820term   ::= [char @{char@}]   -- matches any character listed
13821term   ::= [char - char]   -- matches any character in range
13822@end group
13823@end smallexample
13824
13825@item full regular expression
13826The second set of regular expressions is much more powerful. This is the
13827type of regular expressions recognized by utilities such a @file{grep}.
13828
13829The following is the form of a regular expression, expressed in Ada
13830reference manual style BNF is as follows
13831
13832@smallexample
13833@iftex
13834@leftskip=.5cm
13835@end iftex
13836@group
13837regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13838
13839term ::= item @{item@}       -- concatenation (item then item)
13840
13841item ::= elmt              -- match elmt
13842item ::= elmt *            -- zero or more elmt's
13843item ::= elmt +            -- one or more elmt's
13844item ::= elmt ?            -- matches elmt or nothing
13845@end group
13846@group
13847elmt ::= nschar            -- matches given character
13848elmt ::= [nschar @{nschar@}]   -- matches any character listed
13849elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13850elmt ::= [char - char]     -- matches chars in given range
13851elmt ::= \ char            -- matches given character
13852elmt ::= .                 -- matches any single character
13853elmt ::= ( regexp )        -- parens used for grouping
13854
13855char ::= any character, including special characters
13856nschar ::= any character except ()[].*+?^^^
13857@end group
13858@end smallexample
13859
13860Following are a few examples:
13861
13862@table @samp
13863@item abcde|fghi
13864will match any of the two strings @samp{abcde} and @samp{fghi},
13865
13866@item abc*d
13867will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13868@samp{abcccd}, and so on,
13869
13870@item [a-z]+
13871will match any string which has only lowercase characters in it (and at
13872least one character.
13873
13874@end table
13875@end table
13876
13877@node Examples of gnatxref Usage
13878@section Examples of @code{gnatxref} Usage
13879
13880@subsection General Usage
13881
13882@noindent
13883For the following examples, we will consider the following units:
13884
13885@smallexample @c ada
13886@group
13887@cartouche
13888main.ads:
138891: with Bar;
138902: package Main is
138913:     procedure Foo (B : in Integer);
138924:     C : Integer;
138935: private
138946:     D : Integer;
138957: end Main;
13896
13897main.adb:
138981: package body Main is
138992:     procedure Foo (B : in Integer) is
139003:     begin
139014:        C := B;
139025:        D := B;
139036:        Bar.Print (B);
139047:        Bar.Print (C);
139058:     end Foo;
139069: end Main;
13907
13908bar.ads:
139091: package Bar is
139102:     procedure Print (B : Integer);
139113: end bar;
13912@end cartouche
13913@end group
13914@end smallexample
13915
13916@table @code
13917
13918@noindent
13919The first thing to do is to recompile your application (for instance, in
13920that case just by doing a @samp{gnatmake main}, so that GNAT generates
13921the cross-referencing information.
13922You can then issue any of the following commands:
13923
13924@item gnatxref main.adb
13925@code{gnatxref} generates cross-reference information for main.adb
13926and every unit 'with'ed by main.adb.
13927
13928The output would be:
13929@smallexample
13930@iftex
13931@leftskip=0cm
13932@end iftex
13933B                                                      Type: Integer
13934  Decl: bar.ads           2:22
13935B                                                      Type: Integer
13936  Decl: main.ads          3:20
13937  Body: main.adb          2:20
13938  Ref:  main.adb          4:13     5:13     6:19
13939Bar                                                    Type: Unit
13940  Decl: bar.ads           1:9
13941  Ref:  main.adb          6:8      7:8
13942       main.ads           1:6
13943C                                                      Type: Integer
13944  Decl: main.ads          4:5
13945  Modi: main.adb          4:8
13946  Ref:  main.adb          7:19
13947D                                                      Type: Integer
13948  Decl: main.ads          6:5
13949  Modi: main.adb          5:8
13950Foo                                                    Type: Unit
13951  Decl: main.ads          3:15
13952  Body: main.adb          2:15
13953Main                                                    Type: Unit
13954  Decl: main.ads          2:9
13955  Body: main.adb          1:14
13956Print                                                   Type: Unit
13957  Decl: bar.ads           2:15
13958  Ref:  main.adb          6:12     7:12
13959@end smallexample
13960
13961@noindent
13962that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13963its body is in main.adb, line 1, column 14 and is not referenced any where.
13964
13965The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13966is referenced in main.adb, line 6 column 12 and line 7 column 12.
13967
13968@item gnatxref package1.adb package2.ads
13969@code{gnatxref} will generates cross-reference information for
13970package1.adb, package2.ads and any other package 'with'ed by any
13971of these.
13972
13973@end table
13974
13975@ifclear vms
13976@subsection Using gnatxref with vi
13977
13978@code{gnatxref} can generate a tags file output, which can be used
13979directly from @command{vi}. Note that the standard version of @command{vi}
13980will not work properly with overloaded symbols. Consider using another
13981free implementation of @command{vi}, such as @command{vim}.
13982
13983@smallexample
13984$ gnatxref -v gnatfind.adb > tags
13985@end smallexample
13986
13987@noindent
13988will generate the tags file for @code{gnatfind} itself (if the sources
13989are in the search path!).
13990
13991From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13992(replacing @var{entity} by whatever you are looking for), and vi will
13993display a new file with the corresponding declaration of entity.
13994@end ifclear
13995
13996@node Examples of gnatfind Usage
13997@section Examples of @code{gnatfind} Usage
13998
13999@table @code
14000
14001@item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14002Find declarations for all entities xyz referenced at least once in
14003main.adb. The references are search in every library file in the search
14004path.
14005
14006The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14007switch is set)
14008
14009The output will look like:
14010@smallexample
14011^directory/^[directory]^main.ads:106:14: xyz <= declaration
14012^directory/^[directory]^main.adb:24:10: xyz <= body
14013^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14014@end smallexample
14015
14016@noindent
14017that is to say, one of the entities xyz found in main.adb is declared at
14018line 12 of main.ads (and its body is in main.adb), and another one is
14019declared at line 45 of foo.ads
14020
14021@item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14022This is the same command as the previous one, instead @code{gnatfind} will
14023display the content of the Ada source file lines.
14024
14025The output will look like:
14026
14027@smallexample
14028^directory/^[directory]^main.ads:106:14: xyz <= declaration
14029   procedure xyz;
14030^directory/^[directory]^main.adb:24:10: xyz <= body
14031   procedure xyz is
14032^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14033   xyz : Integer;
14034@end smallexample
14035
14036@noindent
14037This can make it easier to find exactly the location your are looking
14038for.
14039
14040@item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14041Find references to all entities containing an x that are
14042referenced on line 123 of main.ads.
14043The references will be searched only in main.ads and foo.adb.
14044
14045@item gnatfind main.ads:123
14046Find declarations and bodies for all entities that are referenced on
14047line 123 of main.ads.
14048
14049This is the same as @code{gnatfind "*":main.adb:123}.
14050
14051@item gnatfind ^mydir/^[mydir]^main.adb:123:45
14052Find the declaration for the entity referenced at column 45 in
14053line 123 of file main.adb in directory mydir. Note that it
14054is usual to omit the identifier name when the column is given,
14055since the column position identifies a unique reference.
14056
14057The column has to be the beginning of the identifier, and should not
14058point to any character in the middle of the identifier.
14059
14060@end table
14061
14062@ifclear FSFEDITION
14063@c *********************************
14064@node The GNAT Pretty-Printer gnatpp
14065@chapter The GNAT Pretty-Printer @command{gnatpp}
14066@findex gnatpp
14067@cindex Pretty-Printer
14068
14069@menu
14070* Switches for gnatpp::
14071* Formatting Rules::
14072@end menu
14073
14074@noindent
14075^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14076for source reformatting / pretty-printing.
14077It takes an Ada source file as input and generates a reformatted
14078version as output.
14079You can specify various style directives via switches; e.g.,
14080identifier case conventions, rules of indentation, and comment layout.
14081
14082Note: A newly-redesigned set of formatting algorithms used by gnatpp
14083is now available.
14084To invoke the old formatting algorithms, use the @option{--pp-old} switch.
14085Support for @option{--pp-old} will be removed in some future version.
14086
14087To produce a reformatted file, @command{gnatpp} invokes the Ada
14088compiler and generates and uses the ASIS tree for the input source;
14089thus the input must be legal Ada code.
14090
14091@command{gnatpp} cannot process sources that contain
14092preprocessing directives.
14093
14094If the compilation unit contained in the input source depends
14095semantically upon units located outside the current directory, you
14096have to provide the source search path when invoking
14097@command{gnatpp}. If these units are contained in files with names
14098that do not follow the GNAT file naming rules, you have to provide a
14099configuration file describing the corresponding naming scheme; see the
14100description of the @command{gnatpp} switches below. Another
14101possibility is to use a project file and to call @command{gnatpp}
14102through the @command{gnat} driver (see @ref{The GNAT Driver and
14103Project Files}).
14104
14105The @command{gnatpp} command has the form
14106
14107@smallexample
14108@c $ gnatpp @ovar{switches} @var{filename}
14109@c Expanding @ovar macro inline (explanation in macro def comments)
14110$ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
14111@end smallexample
14112
14113@noindent
14114where
14115@itemize @bullet
14116@item
14117@var{switches} is an optional sequence of switches defining such properties as
14118the formatting rules, the source search path, and the destination for the
14119output source file
14120
14121@item
14122@var{filename} is the name (including the extension) of the source file to
14123reformat; wildcards or several file names on the same gnatpp command are
14124allowed. The file name may contain path information; it does not have to
14125follow the GNAT file naming rules
14126
14127@item
14128@samp{@var{gcc_switches}} is a list of switches for
14129@command{gcc}. They will be passed on to all compiler invocations made by
14130@command{gnatpp} to generate the ASIS trees. Here you can provide
14131@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14132use the @option{-gnatec} switch to set the configuration file, etc.
14133@end itemize
14134
14135@node Switches for gnatpp
14136@section Switches for @command{gnatpp}
14137
14138@noindent
14139The following subsections describe the various switches accepted by
14140@command{gnatpp}, organized by category.
14141
14142@ifclear vms
14143You specify a switch by supplying a name and generally also a value.
14144In many cases the values for a switch with a given name are incompatible with
14145each other
14146(for example the switch that controls the casing of a reserved word may have
14147exactly one value: upper case, lower case, or
14148mixed case) and thus exactly one such switch can be in effect for an
14149invocation of @command{gnatpp}.
14150If more than one is supplied, the last one is used.
14151However, some values for the same switch are mutually compatible.
14152You may supply several such switches to @command{gnatpp}, but then
14153each must be specified in full, with both the name and the value.
14154Abbreviated forms (the name appearing once, followed by each value) are
14155not permitted.
14156@end ifclear
14157
14158@ifset vms
14159In many cases the set of options for a given qualifier are incompatible with
14160each other (for example the qualifier that controls the casing of a reserved
14161word may have exactly one option, which specifies either upper case, lower
14162case, or mixed case), and thus exactly one such option can be in effect for
14163an invocation of @command{gnatpp}.
14164If more than one is supplied, the last one is used.
14165@end ifset
14166
14167@menu
14168* Alignment Control::
14169* Casing Control::
14170* General Text Layout Control::
14171* Other Formatting Options::
14172* Setting the Source Search Path::
14173* Output File Control::
14174* Other gnatpp Switches::
14175@end menu
14176
14177@node Alignment Control
14178@subsection Alignment Control
14179@cindex Alignment control in @command{gnatpp}
14180
14181@noindent
14182Programs can be easier to read if certain constructs are vertically aligned.
14183By default alignment of the following constructs is set ON:
14184@code{:} in declarations, @code{:=} in initializations in declarations
14185@code{:=} in assignment statements, @code{=>} in associations, and
14186@code{at} keywords in the component clauses in record
14187representation clauses.
14188
14189@table @option
14190@cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14191
14192@item ^-A0^/ALIGN=OFF^
14193Set alignment to OFF
14194
14195@item ^-A1^/ALIGN=ON^
14196Set alignment to ON
14197@end table
14198
14199@node Casing Control
14200@subsection Casing Control
14201@cindex Casing control in @command{gnatpp}
14202
14203@noindent
14204@command{gnatpp} allows you to specify the casing for reserved words,
14205pragma names, attribute designators and identifiers.
14206For identifiers you may define a
14207general rule for name casing but also override this rule
14208via a set of dictionary files.
14209
14210Three types of casing are supported: lower case, upper case, and mixed case.
14211``Mixed case'' means that the first letter, and also each letter immediately
14212following an underscore, are converted to their uppercase forms;
14213all the other letters are converted to their lowercase forms.
14214
14215@table @option
14216@cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14217@item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14218Attribute designators are lower case
14219
14220@item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14221Attribute designators are upper case
14222
14223@item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14224Attribute designators are mixed case (this is the default)
14225
14226@cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14227@item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14228Keywords (technically, these are known in Ada as @emph{reserved words}) are
14229lower case (this is the default)
14230
14231@item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14232Keywords are upper case
14233
14234@cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14235@item ^-nD^/NAME_CASING=AS_DECLARED^
14236Name casing for defining occurrences are as they appear in the source file
14237(this is the default)
14238
14239@item ^-nU^/NAME_CASING=UPPER_CASE^
14240Names are in upper case
14241
14242@item ^-nL^/NAME_CASING=LOWER_CASE^
14243Names are in lower case
14244
14245@item ^-nM^/NAME_CASING=MIXED_CASE^
14246Names are in mixed case
14247
14248@cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14249@item ^-neD^/ENUM_CASING=AS_DECLARED^
14250Enumeration literal casing for defining occurrences are as they appear in the
14251source file. Overrides ^-n^/NAME_CASING^ casing setting.
14252
14253@item ^-neU^/ENUM_CASING=UPPER_CASE^
14254Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
14255setting.
14256
14257@item ^-neL^/ENUM_CASING=LOWER_CASE^
14258Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14259setting.
14260
14261@item ^-neM^/ENUM_CASING=MIXED_CASE^
14262Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14263setting.
14264
14265@cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14266@item ^-neD^/TYPE_CASING=AS_DECLARED^
14267Names introduced by type and subtype declarations are always
14268cased as they appear in the declaration in the source file.
14269Overrides ^-n^/NAME_CASING^ casing setting.
14270
14271@item ^-ntU^/TYPE_CASING=UPPER_CASE^
14272Names introduced by type and subtype declarations are always in
14273upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14274
14275@item ^-ntL^/TYPE_CASING=LOWER_CASE^
14276Names introduced by type and subtype declarations are always in
14277lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14278
14279@item ^-ntM^/TYPE_CASING=MIXED_CASE^
14280Names introduced by type and subtype declarations are always in
14281mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14282
14283@item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14284Names introduced by number declarations are always in
14285upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14286
14287@item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14288Names introduced by number declarations are always in
14289lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14290
14291@item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14292Names introduced by number declarations are always in
14293mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14294
14295@cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14296@item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14297Pragma names are lower case
14298
14299@item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14300Pragma names are upper case
14301
14302@item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14303Pragma names are mixed case (this is the default)
14304
14305@item ^-D@var{file}^/DICTIONARY=@var{file}^
14306@cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14307Use @var{file} as a @emph{dictionary file} that defines
14308the casing for a set of specified names,
14309thereby overriding the effect on these names by
14310any explicit or implicit
14311^-n^/NAME_CASING^ switch.
14312To supply more than one dictionary file,
14313use ^several @option{-D} switches^a list of files as options^.
14314
14315@noindent
14316@option{gnatpp} implicitly uses a @emph{default dictionary file}
14317to define the casing for the Ada predefined names and
14318the names declared in the GNAT libraries.
14319
14320@item ^-D-^/SPECIFIC_CASING^
14321@cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14322Do not use the default dictionary file;
14323instead, use the casing
14324defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14325dictionary file(s)
14326@end table
14327
14328@noindent
14329The structure of a dictionary file, and details on the conventions
14330used in the default dictionary file, are defined in @ref{Name Casing}.
14331
14332The @option{^-D-^/SPECIFIC_CASING^} and
14333@option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14334compatible.
14335
14336@noindent
14337This group of @command{gnatpp} switches controls the layout of comments and
14338complex syntactic constructs.  See @ref{Formatting Comments} for details
14339on their effect.
14340
14341@table @option
14342@cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14343@item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14344All comments remain unchanged.
14345
14346@item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14347GNAT-style comment line indentation.
14348This is the default.
14349
14350@item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14351GNAT-style comment beginning.
14352
14353@item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14354Fill comment blocks.
14355
14356@item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14357Keep unchanged special form comments.
14358This is the default.
14359
14360@item --comments-only
14361@cindex @option{--comments-only} @command{gnatpp}
14362Format just the comments.
14363
14364@cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14365@item ^--no-separate-is^/NO_SEPARATE_IS^
14366Do not place the keyword @code{is} on a separate line in a subprogram body in
14367case if the spec occupies more than one line.
14368
14369@cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14370@item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14371Place the keyword @code{loop} in FOR and WHILE loop statements and the
14372keyword @code{then} in IF statements on a separate line.
14373
14374@cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14375@item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14376Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14377keyword @code{then} in IF statements on a separate line. This option is
14378incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14379
14380@cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14381@item ^--use-on-new-line^/USE_ON_NEW_LINE^
14382Start each USE clause in a context clause from a separate line.
14383
14384@cindex @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} (@command{gnatpp})
14385@item ^--insert-blank-lines^/INSERT_BLANK_LINES^
14386Insert blank lines where appropriate (between bodies and other large
14387constructs).
14388
14389@cindex @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} (@command{gnatpp})
14390@item ^--preserve-blank-lines^/PRESERVE_BLANK_LINES^
14391Preserve blank lines in the input. By default, gnatpp will squeeze
14392multiple blank lines down to one.
14393
14394@end table
14395
14396@ifclear vms
14397@noindent
14398The @option{-c} switches are compatible with one another, except that
14399the @option{-c0} switch disables all other comment formatting
14400switches.
14401@end ifclear
14402
14403@ifset vms
14404@noindent
14405For the @option{/COMMENTS_LAYOUT} qualifier,
14406The @option{GNAT_BEGINNING}, @option{REFORMAT}, and @option{DEFAULT}
14407options are compatible with one another.
14408@end ifset
14409
14410@node General Text Layout Control
14411@subsection General Text Layout Control
14412
14413@noindent
14414These switches allow control over line length and indentation.
14415
14416@table @option
14417@item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14418@cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14419Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14420
14421@item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14422@cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14423Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14424
14425@item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14426@cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14427Indentation level for continuation lines (relative to the line being
14428continued), @var{nnn} from 1@dots{}9.
14429The default
14430value is one less than the (normal) indentation level, unless the
14431indentation is set to 1 (in which case the default value for continuation
14432line indentation is also 1)
14433@end table
14434
14435@node Other Formatting Options
14436@subsection Other Formatting Options
14437
14438@noindent
14439These switches control other formatting not listed above.
14440
14441@table @option
14442@item --decimal-grouping=@var{n}
14443@cindex @option{--decimal-grouping} @command{gnatpp}
14444Put underscores in decimal literals (numeric literals without a base)
14445every @var{n} characters. If a literal already has one or more
14446underscores, it is not modified. For example, with
14447@code{--decimal-grouping=3}, @code{1000000} will be changed to
14448@code{1_000_000}.
14449
14450@item --based-grouping=@var{n}
14451@cindex @option{--based-grouping} @command{gnatpp}
14452Same as @code{--decimal-grouping}, but for based literals. For
14453example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
14454changed to @code{16#0001_FFFE#}.
14455
14456@item ^--RM-style-spacing^/RM_STYLE_SPACING^
14457@cindex @option{^--RM-style-spacing^/RM_STYLE_SPACING^} (@command{gnatpp})
14458Do not insert an extra blank before various occurrences of
14459`(' and `:'. This also turns off alignment.
14460
14461@item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14462@cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14463Insert a Form Feed character after a pragma Page.
14464
14465@item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14466@cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14467If the number of parameter associations is greater than @var{nnn} and if at
14468least one association uses named notation, start each association from
14469a new line. If @var{nnn} is 0, no check for the number of associations
14470is made; this is the default.
14471
14472@item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14473@cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14474If the number of parameter specifications is greater than @var{nnn}
14475(or equal to @var{nnn} in case of a function), start each specification from
14476a new line. The default for @var{nnn} is 3.
14477@end table
14478
14479@node Setting the Source Search Path
14480@subsection Setting the Source Search Path
14481
14482@noindent
14483To define the search path for the input source file, @command{gnatpp}
14484uses the same switches as the GNAT compiler, with the same effects:
14485
14486@table @option
14487@item ^-I^/SEARCH=^@var{dir}
14488@cindex @option{^-I^/SEARCH^} (@command{gnatpp})
14489
14490@item ^-I-^/NOCURRENT_DIRECTORY^
14491@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatpp})
14492
14493@item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14494@cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatpp})
14495
14496@item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14497@cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@command{gnatpp})
14498
14499@end table
14500
14501@node Output File Control
14502@subsection Output File Control
14503
14504@noindent
14505By default the output is sent to a file whose name is obtained by appending
14506the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file.
14507If the file with this name already exists, it is overwritten.
14508Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14509@command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14510as output file.
14511The output may be redirected by the following switches:
14512
14513@table @option
14514@item ^-pipe^/STANDARD_OUTPUT^
14515@cindex @option{^-pipe^/STANDARD_OUTPUT^} (@command{gnatpp})
14516Send the output to @code{Standard_Output}
14517
14518@item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14519@cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14520Write the output into @var{output_file}.
14521If @var{output_file} already exists, @command{gnatpp} terminates without
14522reading or processing the input file.
14523
14524@item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14525@cindex @option{^-of^/FORCED_OUTPUT^} (@command{gnatpp})
14526Write the output into @var{output_file}, overwriting the existing file
14527(if one is present).
14528
14529@item ^-r^/REPLACE^
14530@cindex @option{^-r^/REPLACE^} (@command{gnatpp})
14531Replace the input source file with the reformatted output, and copy the
14532original input source into the file whose name is obtained by appending the
14533^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14534If a file with this name already exists, @command{gnatpp} terminates without
14535reading or processing the input file.
14536
14537@item ^-rf^/OVERRIDING_REPLACE^
14538@cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14539Like @option{^-r^/REPLACE^} except that if the file with the specified name
14540already exists, it is overwritten.
14541
14542@item ^-rnb^/REPLACE_NO_BACKUP^
14543@cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@command{gnatpp})
14544Replace the input source file with the reformatted output without
14545creating any backup copy of the input source.
14546
14547@item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14548@cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14549Specifies the line-ending style of the reformatted output file. The @var{xxx}
14550^string specified with the switch^option^ may be:
14551@itemize @bullet
14552@item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14553@item ``@option{^crlf^CRLF^}''
14554the same as @option{^dos^DOS^}
14555@item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14556@item ``@option{^lf^LF^}''
14557the same as @option{^unix^UNIX^}
14558@end itemize
14559
14560@item ^-W^/RESULT_ENCODING=^@var{e}
14561@cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14562Specify the wide character encoding method for the input and output files.
14563@var{e} is one of the following:
14564
14565@itemize @bullet
14566
14567@item ^h^HEX^
14568Hex encoding
14569
14570@item ^u^UPPER^
14571Upper half encoding
14572
14573@item ^s^SHIFT_JIS^
14574Shift/JIS encoding
14575
14576@item ^e^EUC^
14577EUC encoding
14578
14579@item ^8^UTF8^
14580UTF-8 encoding
14581
14582@item ^b^BRACKETS^
14583Brackets encoding (default value)
14584@end itemize
14585
14586@end table
14587
14588@noindent
14589Options @option{^-o^/OUTPUT^} and
14590@option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14591contains only one file to reformat.
14592Option
14593@option{^--eol^/END_OF_LINE^}
14594and
14595@option{^-W^/RESULT_ENCODING^}
14596cannot be used together
14597with @option{^-pipe^/STANDARD_OUTPUT^} option.
14598
14599@node Other gnatpp Switches
14600@subsection Other @code{gnatpp} Switches
14601
14602@noindent
14603The additional @command{gnatpp} switches are defined in this subsection.
14604
14605@table @option
14606@item --version
14607@cindex @option{--version} @command{gnatpp}
14608Display copyright and version, then exit disregarding all other options.
14609
14610@item --help
14611@cindex @option{--help} @command{gnatpp}
14612Display usage, then exit disregarding all other options.
14613
14614@item -P @var{file}
14615@cindex @option{-P} @command{gnatpp}
14616Indicates the name of the project file that describes the set of sources
14617to be processed. The exact set of argument sources depends on other options
14618specified; see below.
14619
14620@item -U
14621@cindex @option{-U} @command{gnatpp}
14622If a project file is specified and no argument source is explicitly
14623specified (either directly or by means of @option{-files} option), process
14624all the units of the closure of the argument project. Otherwise this option
14625has no effect.
14626
14627@item -U @var{main_unit}
14628If a project file is specified and no argument source is explicitly
14629specified (either directly or by means of @option{-files} option), process
14630the closure of units rooted at @var{main_unit}. Otherwise this option
14631has no effect.
14632
14633@item -X@var{name}=@var{value}
14634@cindex @option{-X} @command{gnatpp}
14635Indicates that external variable @var{name} in the argument project
14636has the value @var{value}. Has no effect if no project is specified as
14637tool argument.
14638
14639@item --pp-off=@var{xxx}
14640@cindex @option{--pp-off} @command{gnatpp}
14641Use @code{--xxx} as the command to turn off pretty printing, instead
14642of the default @code{--!pp off}.
14643
14644@item --pp-on=@var{xxx}
14645@cindex @option{--pp-on} @command{gnatpp}
14646Use @code{--xxx} as the command to turn pretty printing back on, instead
14647of the default @code{--!pp on}.
14648
14649@item --pp-old
14650@cindex @option{--pp-old} @command{gnatpp}
14651Use the old formatting algorithms.
14652
14653@item ^-files @var{filename}^/FILES=@var{filename}^
14654@cindex @option{^-files^/FILES^} (@code{gnatpp})
14655Take the argument source files from the specified file. This file should be an
14656ordinary text file containing file names separated by spaces or
14657line breaks. You can use this switch more than once in the same call to
14658@command{gnatpp}. You also can combine this switch with an explicit list of
14659files.
14660
14661@item ^-j^/PROCESSES=^@var{n}
14662@cindex @option{^-j^/PROCESSES^} (@command{gnatpp})
14663Use @var{n} processes to carry out the tree creations (internal representations
14664of the argument sources). On a multiprocessor machine this speeds up processing
14665of big sets of argument sources. If @var{n} is 0, then the maximum number of
14666parallel tree creations is the number of core processors on the platform.
14667This option cannot be used together with @option{^-r^/REPLACE^},
14668@option{^-rf^/OVERRIDING_REPLACE^} or
14669@option{^-rnb^/REPLACE_NO_BACKUP^} option.
14670
14671@cindex @option{^-t^/TIME^} (@command{gnatpp})
14672@item ^-t^/TIME^
14673Print out execution time.
14674
14675@item ^-v^/VERBOSE^
14676@cindex @option{^-v^/VERBOSE^} (@command{gnatpp})
14677Verbose mode
14678
14679@item ^-q^/QUIET^
14680@cindex @option{^-q^/QUIET^} (@command{gnatpp})
14681Quiet mode
14682@end table
14683
14684@noindent
14685If a project file is specified and no argument source is explicitly
14686specified (either directly or by means of @option{-files} option), and no
14687@option{-U} is specified, then the set of processed sources is
14688all the immediate units of the argument project.
14689
14690
14691@node Formatting Rules
14692@section Formatting Rules
14693
14694@noindent
14695The following subsections show how @command{gnatpp} treats white space,
14696comments, program layout, and name casing.
14697They provide detailed descriptions of the switches shown above.
14698
14699@menu
14700* Disabling Pretty Printing::
14701* White Space and Empty Lines::
14702* Formatting Comments::
14703* Name Casing::
14704@end menu
14705
14706@node Disabling Pretty Printing
14707@subsection Disabling Pretty Printing
14708
14709@noindent
14710Pretty printing is highly heuristic in nature, and sometimes doesn't
14711do exactly what you want. If you wish to format a certain region of
14712code by hand, you can turn off pretty printing in that region by
14713surrounding it with special comments that start with @code{--!pp off}
14714and @code{--!pp on}. The text in that region will then be reproduced
14715verbatim in the output with no formatting.
14716
14717To disable pretty printing for the whole file, put @code{--!pp off} at
14718the top, with no following @code{--!pp on}.
14719
14720The comments must appear on a line by themselves, with nothing
14721preceding except spaces. The initial text of the comment must be
14722exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14723be followed by arbitrary additional text. For example:
14724
14725@smallexample @c ada
14726@cartouche
14727package Interrupts is
14728   --!pp off -- turn off pretty printing so "Interrupt_Kind" lines up
14729   type            Interrupt_Kind is
14730     (Asynchronous_Interrupt_Kind,
14731       Synchronous_Interrupt_Kind,
14732             Green_Interrupt_Kind);
14733   --!pp on -- reenable pretty printing
14734
14735   ...
14736@end cartouche
14737@end smallexample
14738
14739You can specify different comment strings using the @code{--pp-off}
14740and @code{--pp-on} switches. For example, if you say @code{gnatpp
14741--pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14742@code{-- pp-} instead of @code{--!pp off} for disabling pretty
14743printing. Note that the leading @code{--} of the comment is not
14744included in the argument to these switches.
14745
14746@node White Space and Empty Lines
14747@subsection White Space and Empty Lines
14748
14749@noindent
14750@command{gnatpp} does not have an option to control space characters.
14751It will add or remove spaces according to the style illustrated by the
14752examples in the @cite{Ada Reference Manual}.
14753The output file will contain no lines with trailing white space.
14754
14755By default, a sequence of one or more blank lines in the input is
14756converted to a single blank line in the output; multiple blank lines
14757are squeezed down to one.
14758The @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} option
14759turns off the squeezing; each blank line in the input is copied
14760to the output.
14761The @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} option
14762causes additional blank lines to be inserted if not already
14763present in the input (e.g. between bodies).
14764
14765@node Formatting Comments
14766@subsection Formatting Comments
14767
14768@noindent
14769Comments in Ada code are of two kinds:
14770@itemize @bullet
14771@item
14772a @emph{whole-line comment}, which appears by itself (possibly preceded by
14773white space) on a line
14774
14775@item
14776an @emph{end-of-line comment}, which follows some other Ada code on
14777the same line.
14778@end itemize
14779
14780@noindent
14781A whole-line comment is indented according to the surrounding code,
14782with some exceptions.
14783Comments that start in column 1 are kept there.
14784If possible, comments are not moved so far to the right that the maximum
14785line length is exceeded.
14786The @option{^-c0^/COMMENTS_LAYOUT=UNTOUCHED^} option
14787turns off comment formatting.
14788Special-form comments such as SPARK-style @code{--#...} are left alone.
14789
14790For an end-of-line comment, @command{gnatpp} tries to leave the same
14791number of spaces between the end of the preceding Ada code and the
14792beginning of the comment as appear in the original source.
14793
14794@noindent
14795The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14796(GNAT style comment beginning) has the following
14797effect:
14798
14799@itemize @bullet
14800@item
14801For each whole-line comment that does not end with two hyphens,
14802@command{gnatpp} inserts spaces if necessary after the starting two hyphens
14803to ensure that there are at least two spaces between these hyphens and the
14804first non-blank character of the comment.
14805@end itemize
14806
14807@noindent
14808The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that
14809whole-line comments that form a paragraph will be filled in typical
14810word processor style (that is, moving words between lines to make the
14811lines other than the last similar in length ).
14812
14813@noindent
14814The @option{--comments-only} switch specifies that only the comments
14815are formatted; the rest of the program text is left alone. The
14816comments are formatted according to the -c3 and -c4 switches; other
14817formatting switches are ignored. For example, @option{--comments-only
14818-c4} means to fill comment paragraphs, and do nothing else. Likewise,
14819@option{--comments-only -c3} ensures comments start with at least two
14820spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14821both. If @option{--comments-only} is given without @option{-c3} or
14822@option{-c4}, then gnatpp doesn't format anything.
14823
14824@node Name Casing
14825@subsection Name Casing
14826
14827@noindent
14828@command{gnatpp} always converts the usage occurrence of a (simple) name to
14829the same casing as the corresponding defining identifier.
14830
14831You control the casing for defining occurrences via the
14832@option{^-n^/NAME_CASING^} switch.
14833@ifclear vms
14834With @option{-nD} (``as declared'', which is the default),
14835@end ifclear
14836@ifset vms
14837With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14838@end ifset
14839defining occurrences appear exactly as in the source file
14840where they are declared.
14841The other ^values for this switch^options for this qualifier^ ---
14842@option{^-nU^UPPER_CASE^},
14843@option{^-nL^LOWER_CASE^},
14844@option{^-nM^MIXED_CASE^} ---
14845result in
14846^upper, lower, or mixed case, respectively^the corresponding casing^.
14847If @command{gnatpp} changes the casing of a defining
14848occurrence, it analogously changes the casing of all the
14849usage occurrences of this name.
14850
14851If the defining occurrence of a name is not in the source compilation unit
14852currently being processed by @command{gnatpp}, the casing of each reference to
14853this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14854switch (subject to the dictionary file mechanism described below).
14855Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14856had affected the
14857casing for the defining occurrence of the name.
14858
14859The options
14860@option{^-a@var{x}^/ATTRIBUTE^},
14861@option{^-k@var{x}^/KEYWORD_CASING^},
14862@option{^-ne@var{x}^/ENUM_CASING^},
14863@option{^-nt@var{x}^/TYPE_CASING^},
14864@option{^-nn@var{x}^/NUMBER_CASING^}, and
14865@option{^-p@var{x}^/PRAGMA_CASING^}
14866allow finer-grained control over casing for
14867attributes, keywords, enumeration literals,
14868types, named numbers and pragmas, respectively.
14869@option{^-nt@var{x}^/TYPE_CASING^} covers subtypes and
14870task and protected bodies as well.
14871
14872Some names may need to be spelled with casing conventions that are not
14873covered by the upper-, lower-, and mixed-case transformations.
14874You can arrange correct casing by placing such names in a
14875@emph{dictionary file},
14876and then supplying a @option{^-D^/DICTIONARY^} switch.
14877The casing of names from dictionary files overrides
14878any @option{^-n^/NAME_CASING^} switch.
14879
14880To handle the casing of Ada predefined names and the names from GNAT libraries,
14881@command{gnatpp} assumes a default dictionary file.
14882The name of each predefined entity is spelled with the same casing as is used
14883for the entity in the @cite{Ada Reference Manual} (usually mixed case).
14884The name of each entity in the GNAT libraries is spelled with the same casing
14885as is used in the declaration of that entity.
14886
14887The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of
14888the default dictionary file. Instead, the casing for predefined and
14889GNAT-defined names will be established by the
14890@option{^-n^/NAME_CASING^} switch or explicit dictionary files. For
14891example, by default the names @code{Ada.Text_IO} and
14892@code{GNAT.OS_Lib} will appear as just shown, even in the presence of
14893a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.  To ensure that even
14894such names are rendered in uppercase, additionally supply the
14895@w{@option{^-D-^/SPECIFIC_CASING^}} switch (or else place these names
14896in upper case in a dictionary file).
14897
14898A dictionary file is a plain text file; each line in this file can be
14899either a blank line (containing only space characters), an Ada comment
14900line, or the specification of exactly one @emph{casing schema}.
14901
14902A casing schema is a string that has the following syntax:
14903
14904@smallexample
14905@cartouche
14906  @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14907
14908  @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14909@end cartouche
14910@end smallexample
14911
14912@noindent
14913(See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14914@var{identifier} lexical element and the @var{letter_or_digit} category.)
14915
14916The casing schema string can be followed by white space and/or an Ada-style
14917comment; any amount of white space is allowed before the string.
14918
14919If a dictionary file is passed as
14920@ifclear vms
14921the value of a @option{-D@var{file}} switch
14922@end ifclear
14923@ifset vms
14924an option to the @option{/DICTIONARY} qualifier
14925@end ifset
14926then for every
14927simple name and every identifier, @command{gnatpp} checks if the dictionary
14928defines the casing for the name or for some of its parts (the term ``subword''
14929is used below to denote the part of a name which is delimited by ``_'' or by
14930the beginning or end of the word and which does not contain any ``_'' inside):
14931
14932@itemize @bullet
14933@item
14934if the whole name is in the dictionary, @command{gnatpp} uses for this name
14935the casing defined by the dictionary; no subwords are checked for this word
14936
14937@item
14938for every subword @command{gnatpp} checks if the dictionary contains the
14939corresponding string of the form @code{*@var{simple_identifier}*},
14940and if it does, the casing of this @var{simple_identifier} is used
14941for this subword
14942
14943@item
14944if the whole name does not contain any ``_'' inside, and if for this name
14945the dictionary contains two entries - one of the form @var{identifier},
14946and another - of the form *@var{simple_identifier}*, then the first one
14947is applied to define the casing of this name
14948
14949@item
14950if more than one dictionary file is passed as @command{gnatpp} switches, each
14951dictionary adds new casing exceptions and overrides all the existing casing
14952exceptions set by the previous dictionaries
14953
14954@item
14955when @command{gnatpp} checks if the word or subword is in the dictionary,
14956this check is not case sensitive
14957@end itemize
14958
14959@noindent
14960For example, suppose we have the following source to reformat:
14961
14962@smallexample @c ada
14963@cartouche
14964procedure test is
14965   name1 : integer := 1;
14966   name4_name3_name2 : integer := 2;
14967   name2_name3_name4 : Boolean;
14968   name1_var : Float;
14969begin
14970   name2_name3_name4 := name4_name3_name2 > name1;
14971end;
14972@end cartouche
14973@end smallexample
14974
14975@noindent
14976And suppose we have two dictionaries:
14977
14978@smallexample
14979@cartouche
14980@i{dict1:}
14981   NAME1
14982   *NaMe3*
14983   *Name1*
14984@end cartouche
14985
14986@cartouche
14987@i{dict2:}
14988  *NAME3*
14989@end cartouche
14990@end smallexample
14991
14992@noindent
14993If @command{gnatpp} is called with the following switches:
14994
14995@smallexample
14996@ifclear vms
14997@command{gnatpp -nM -D dict1 -D dict2 test.adb}
14998@end ifclear
14999@ifset vms
15000@command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15001@end ifset
15002@end smallexample
15003
15004@noindent
15005then we will get the following name casing in the @command{gnatpp} output:
15006
15007@smallexample @c ada
15008@cartouche
15009procedure Test is
15010   NAME1             : Integer := 1;
15011   Name4_NAME3_Name2 : Integer := 2;
15012   Name2_NAME3_Name4 : Boolean;
15013   Name1_Var         : Float;
15014begin
15015   Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15016end Test;
15017@end cartouche
15018@end smallexample
15019@end ifclear
15020
15021@ifclear FSFEDITION
15022@ifclear vms
15023@c *********************************
15024@node The Ada-to-XML converter gnat2xml
15025@chapter The Ada-to-XML converter @command{gnat2xml}
15026@findex gnat2xml
15027@cindex XML generation
15028
15029@noindent
15030The @command{gnat2xml} tool is an ASIS-based utility that converts
15031Ada source code into XML.
15032
15033@menu
15034* Switches for gnat2xml::
15035* Driving gnat2xml with gnatmake or gprbuild::
15036* Other Programs::
15037* Structure of the XML::
15038@end menu
15039
15040@node Switches for gnat2xml
15041@section Switches for @command{gnat2xml}
15042
15043@noindent
15044@command{gnat2xml} takes Ada source code as input, and produces XML
15045that conforms to the schema.
15046
15047Usage:
15048
15049@smallexample
15050gnat2xml [options] files
15051@end smallexample
15052
15053``files'' are the Ada source file names.
15054
15055@noindent
15056Options:
15057@smallexample
15058-h
15059--help -- generate usage information and quit, ignoring all other options
15060
15061-P @file{file} -- indicates the name of the project file that describes
15062      the set of sources to be processed. The exact set of argument
15063      sources depends on other options specified, see below.
15064
15065-U -- if a project file is specified and no argument source is explicitly
15066      specified, process all the units of the closure of the argument project.
15067      Otherwise this option has no effect.
15068
15069-U @var{main_unit} -- if a project file is specified and no argument source
15070      is explicitly specified (either directly or by means of @option{-files}
15071      option), process the closure of units rooted at @var{main_unit}.
15072      Otherwise this option has no effect.
15073
15074-X@var{name}=@var{value} -- indicates that external variable @var{name} in
15075      the argument project has the value @var{value}. Has no effect if no
15076      project is specified as tool argument.
15077
15078-mdir -- generate one .xml file for each Ada source file, in directory
15079         @file{dir}. (Default is to generate the XML to standard output.)
15080
15081--compact -- debugging version, with interspersed source, and a more
15082      compact representation of "sloc". This version does not conform
15083      to any schema.
15084
15085-I <include-dir>
15086    directories to search for dependencies
15087    You can also set the ADA_INCLUDE_PATH environment variable for this.
15088
15089-q -- quiet
15090
15091-v -- verbose (print out the command line options, and the names of
15092      output files as they are generated).
15093
15094-t -- do not delete tree files when done (they are deleted by default).
15095
15096-cargs ... -- options to pass to gcc
15097@end smallexample
15098
15099@noindent
15100If a project file is specified and no argument source is explicitly
15101specified, and no @option{-U} is specified, then the set of processed
15102sources is all the immediate units of the argument project.
15103
15104
15105You can generate the ``tree files'' ahead of time using the -gnatct switch:
15106
15107@smallexample
15108gnatmake -gnat2012 -gnatct *.ad[sb]
15109@end smallexample
15110
15111@noindent
15112If tree files do not exist, @command{gnat2xml} will create them by running gcc.
15113See the ASIS documentation for more information on tree files.
15114
15115Example:
15116
15117@smallexample
15118mkdir xml-files
15119gnat2xml -v -mxml-files *.ad[sb] -cargs -gnat2012
15120@end smallexample
15121
15122@noindent
15123The above will create *.xml files in the @file{xml-files} subdirectory.
15124For example, if there is an Ada package Mumble.Dumble, whose spec and
15125body source code lives in mumble-dumble.ads and mumble-dumble.adb,
15126the above will produce xml-files/mumble-dumble.ads.xml and
15127xml-files/mumble-dumble.adb.xml.
15128
15129@node Driving gnat2xml with gnatmake or gprbuild
15130@section Driving @command{gnat2xml} with @command{gnatmake} or @command{gprbuild}
15131
15132@noindent
15133You can use gnatmake or gprbuild to drive @command{gnat2xml} to get
15134incremental updates of the XML files on a per-source-file basis. For
15135example, if you already have a bunch of XML files, and then you change
15136one source file, it will regenerate XML files only for that source
15137file, and other source files that depend on it. Gnatmake and gprbuild
15138take care of tracking inter-file dependencies. For example, if
15139this.adb says @code{with That;}, then this.adb depends on that.ads.
15140
15141To do this, you tell gnatmake/gprbuild to pretend that
15142@command{gnat2xml} is the Ada compiler (instead of using gcc as the
15143Ada compiler, as is normal).
15144
15145To tell gnatmake to use @command{gnat2xml} instead of gcc as the
15146``compiler'', for example:
15147
15148@smallexample
15149gnatmake -gnatc *.adb --GCC="gnat2xml -t -mxml"
15150@end smallexample
15151
15152@noindent
15153The @option{--GCC=} switch tells gnatmake that the ``compiler'' to run
15154is @command{gnat2xml -t -mxml}. The @option{-t} switch means to keep the tree
15155files, so they can be reused on the next run. (@command{gnat2xml}
15156deletes them by default.) As usual, @option{-mxml} means to put the
15157XML files in the @file{xml} subdirectory.
15158
15159You must give the @option{-gnatc} switch to gnatmake, which means
15160``compile only; do not generate object code''. Otherwise, gnatmake will
15161complain about missing object (*.o) files; @command{gnat2xml} of
15162course does not generate *.o files.
15163
15164Using gprbuild is similar: you tell it to use @command{gnat2xml}
15165instead of gcc. First write a project file, such as my_project.gpr:
15166
15167@smallexample @c projectfile
15168project My_Project is
15169
15170   package Compiler is
15171      for Driver ("ada") use "gnat2xml";
15172      --  Use gnat2xml instead of the usual gcc.
15173
15174      for Default_Switches ("ada") use ("-t", "-mxml");
15175      --  Same switches as in the gnatmake case.
15176   end Compiler;
15177
15178end My_Project;
15179@end smallexample
15180
15181@noindent
15182Then:
15183
15184@smallexample @c projectfile
15185gprbuild --no-object-check -P my_project.gpr
15186@end smallexample
15187
15188@noindent
15189The @option{--no-object-check} switch serves the same purpose as
15190@option{-gnatc} in the gnatmake case --- it tells gprbuild not to
15191expect that the ``compiler'' (really @command{gnat2xml}) will produce
15192*.o files.
15193
15194See the gprbuild documentation for information on many other things
15195you can put in the project file, such as telling it where to find
15196the source files.
15197
15198@node Other Programs
15199@section Other Programs
15200
15201@noindent
15202The distribution includes two other programs that are related to
15203@command{gnat2xml}:
15204
15205@command{gnat2xsd} is the schema generator, which generates the schema
15206to standard output, based on the structure of Ada as encoded by
15207ASIS. You don't need to run @command{gnat2xsd} in order to use
15208@command{gnat2xml}. To generate the schema, type:
15209
15210@smallexample
15211gnat2xsd > ada-schema.xsd
15212@end smallexample
15213
15214@noindent
15215@command{gnat2xml} generates XML files that will validate against
15216@file{ada-schema.xsd}.
15217
15218@command{xml2gnat} is a back-translator that translates the XML back
15219into Ada source code. The Ada generated by @command{xml2gnat} has
15220identical semantics to the original Ada code passed to
15221@command{gnat2xml}. It is not textually identical, however --- for
15222example, no attempt is made to preserve the original indentation.
15223
15224@node Structure of the XML
15225@section Structure of the XML
15226
15227@noindent
15228The primary documentation for the structure of the XML generated by
15229@command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15230following documentation gives additional details needed to understand
15231the schema and therefore the XML.
15232
15233The elements listed under Defining Occurrences, Usage Occurrences, and
15234Other Elements represent the syntactic structure of the Ada program.
15235Element names are given in lower case, with the corresponding element
15236type Capitalized_Like_This. The element and element type names are
15237derived directly from the ASIS enumeration type Flat_Element_Kinds,
15238declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15239removed. For example, the ASIS enumeration literal
15240An_Assignment_Statement corresponds to the XML element
15241assignment_statement of XML type Assignment_Statement.
15242
15243To understand the details of the schema and the corresponding XML, it is
15244necessary to understand the ASIS standard, as well as the GNAT-specific
15245extension to ASIS.
15246
15247A defining occurrence is an identifier (or character literal or operator
15248symbol) declared by a declaration. A usage occurrence is an identifier
15249(or ...) that references such a declared entity. For example, in:
15250
15251@smallexample
15252type T is range 1..10;
15253X, Y : constant T := 1;
15254@end smallexample
15255
15256@noindent
15257The first ``T'' is the defining occurrence of a type. The ``X'' is the
15258defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15259a usage occurrence referring to the defining occurrence of T.
15260
15261Each element has a 'sloc' (source location), and subelements for each
15262syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15263The types of subelements are as defined in the ASIS standard. For
15264example, for the right-hand side of an assignment_statement we have
15265the following comment in asis-statements.ads:
15266
15267@smallexample
15268------------------------------------------------------------------------------
15269--  18.3  function Assignment_Expression
15270------------------------------------------------------------------------------
15271
15272   function Assignment_Expression
15273     (Statement : Asis.Statement)
15274      return      Asis.Expression;
15275
15276------------------------------------------------------------------------------
15277...
15278--  Returns the expression from the right hand side of the assignment.
15279...
15280--  Returns Element_Kinds:
15281--       An_Expression
15282@end smallexample
15283
15284@noindent
15285The corresponding sub-element of type Assignment_Statement is:
15286
15287@smallexample
15288<xsd:element name="assignment_expression_q" type="Expression_Class"/>
15289@end smallexample
15290
15291@noindent
15292where Expression_Class is defined by an xsd:choice of all the
15293various kinds of expression.
15294
15295The 'sloc' of each element indicates the starting and ending line and
15296column numbers. Column numbers are character counts; that is, a tab
15297counts as 1, not as however many spaces it might expand to.
15298
15299Subelements of type Element have names ending in ``_q'' (for ASIS
15300``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15301List'').
15302
15303Some subelements are ``Boolean''. For example, Private_Type_Definition
15304has has_abstract_q and has_limited_q, to indicate whether those
15305keywords are present, as in @code{type T is abstract limited
15306private;}. False is represented by a Nil_Element. True is represented
15307by an element type specific to that query (for example, Abstract and
15308Limited).
15309
15310The root of the tree is a Compilation_Unit, with attributes:
15311
15312@itemize @bullet
15313@item
15314unit_kind, unit_class, and unit_origin. These are strings that match the
15315enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15316in package Asis.
15317
15318@item
15319unit_full_name is the full expanded name of the unit, starting from a
15320root library unit. So for @code{package P.Q.R is ...},
15321@code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15322
15323@item
15324def_name is the same as unit_full_name for library units; for subunits,
15325it is just the simple name.
15326
15327@item
15328source_file is the name of the Ada source file. For example, for
15329the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15330interpret the source locations --- the ``sloc'' of all elements
15331within this Compilation_Unit refers to line and column numbers
15332within the named file.
15333@end itemize
15334
15335@noindent
15336Defining occurrences have these attributes:
15337
15338@itemize @bullet
15339@item
15340def_name is the simple name of the declared entity, as written in the Ada
15341source code.
15342
15343@item
15344def is a unique URI of the form:
15345
15346 ada://kind/fully/qualified/name
15347
15348where:
15349
15350 kind indicates the kind of Ada entity being declared (see below), and
15351
15352 fully/qualified/name, is the fully qualified name of the Ada
15353 entity, with each of ``fully'', ``qualified'', and ``name'' being
15354 mangled for uniqueness. We do not document the mangling
15355 algorithm, which is subject to change; we just guarantee that the
15356 names are unique in the face of overloading.
15357
15358@item
15359type is the type of the declared object, or @code{null} for
15360declarations of things other than objects.
15361@end itemize
15362
15363@noindent
15364Usage occurrences have these attributes:
15365
15366@itemize @bullet
15367@item
15368ref_name is the same as the def_name of the corresponding defining
15369occurrence. This attribute is not of much use, because of
15370overloading; use ref for lookups, instead.
15371
15372@item
15373ref is the same as the def of the corresponding defining
15374occurrence.
15375@end itemize
15376
15377@noindent
15378In summary, @code{def_name} and @code{ref_name} are as in the source
15379code of the declaration, possibly overloaded, whereas @code{def} and
15380@code{ref} are unique-ified.
15381
15382Literal elements have this attribute:
15383
15384@itemize @bullet
15385@item
15386lit_val is the value of the literal as written in the source text,
15387appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
15388only to numeric and string literals. Enumeration literals in Ada are
15389not really "literals" in the usual sense; they are usage occurrences,
15390and have ref_name and ref as described above. Note also that string
15391literals used as operator symbols are treated as defining or usage
15392occurrences, not as literals.
15393@end itemize
15394
15395@noindent
15396Elements that can syntactically represent names and expressions (which
15397includes usage occurrences, plus function calls and so forth) have this
15398attribute:
15399
15400@itemize @bullet
15401@item
15402type. If the element represents an expression or the name of an object,
15403'type' is the 'def' for the defining occurrence of the type of that
15404expression or name. Names of other kinds of entities, such as package
15405names and type names, do not have a type in Ada; these have type="null"
15406in the XML.
15407@end itemize
15408
15409@noindent
15410Pragma elements have this attribute:
15411
15412@itemize @bullet
15413@item
15414pragma_name is the name of the pragma. For language-defined pragmas, the
15415pragma name is redundant with the element kind (for example, an
15416assert_pragma element necessarily has pragma_name="Assert"). However, all
15417implementation-defined pragmas are lumped together in ASIS as a single
15418element kind (for example, the GNAT-specific pragma Unreferenced is
15419represented by an implementation_defined_pragma element with
15420pragma_name="Unreferenced").
15421@end itemize
15422
15423@noindent
15424Defining occurrences of formal parameters and generic formal objects have this
15425attribute:
15426
15427@itemize @bullet
15428@item
15429mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15430@end itemize
15431
15432@noindent
15433All elements other than Not_An_Element have this attribute:
15434
15435@itemize @bullet
15436@item
15437checks is a comma-separated list of run-time checks that are needed
15438for that element. The possible checks are: do_accessibility_check,
15439do_discriminant_check,do_division_check,do_length_check,
15440do_overflow_check,do_range_check,do_storage_check,do_tag_check.
15441@end itemize
15442
15443@noindent
15444The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15445enumeration type Flat_Declaration_Kinds, declared in
15446Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15447any trailing "_Declaration" or "_Specification" removed. Thus, the
15448possible kinds are as follows:
15449
15450@smallexample
15451ordinary_type
15452task_type
15453protected_type
15454incomplete_type
15455tagged_incomplete_type
15456private_type
15457private_extension
15458subtype
15459variable
15460constant
15461deferred_constant
15462single_task
15463single_protected
15464integer_number
15465real_number
15466enumeration_literal
15467discriminant
15468component
15469loop_parameter
15470generalized_iterator
15471element_iterator
15472procedure
15473function
15474parameter
15475procedure_body
15476function_body
15477return_variable
15478return_constant
15479null_procedure
15480expression_function
15481package
15482package_body
15483object_renaming
15484exception_renaming
15485package_renaming
15486procedure_renaming
15487function_renaming
15488generic_package_renaming
15489generic_procedure_renaming
15490generic_function_renaming
15491task_body
15492protected_body
15493entry
15494entry_body
15495entry_index
15496procedure_body_stub
15497function_body_stub
15498package_body_stub
15499task_body_stub
15500protected_body_stub
15501exception
15502choice_parameter
15503generic_procedure
15504generic_function
15505generic_package
15506package_instantiation
15507procedure_instantiation
15508function_instantiation
15509formal_object
15510formal_type
15511formal_incomplete_type
15512formal_procedure
15513formal_function
15514formal_package
15515formal_package_declaration_with_box
15516@end smallexample
15517@end ifclear
15518@end ifclear
15519
15520
15521@ifclear FSFEDITION
15522@c *********************************
15523@node The GNAT Metrics Tool gnatmetric
15524@chapter The GNAT Metrics Tool @command{gnatmetric}
15525@findex gnatmetric
15526@cindex Metric tool
15527
15528@noindent
15529^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15530for computing various program metrics.
15531It takes an Ada source file as input and generates a file containing the
15532metrics data as output. Various switches control which
15533metrics are computed and output.
15534
15535@menu
15536* Switches for gnatmetric::
15537@end menu
15538
15539@command{gnatmetric} generates and uses the ASIS
15540tree for the input source and thus requires the input to be syntactically and
15541semantically legal.
15542If this condition is not met, @command{gnatmetric} will generate
15543an error message; no metric information for this file will be
15544computed and reported.
15545
15546If the compilation unit contained in the input source depends semantically
15547upon units in files located outside the current directory, you have to provide
15548the source search path when invoking @command{gnatmetric}.
15549If it depends semantically upon units that are contained
15550in files with names that do not follow the GNAT file naming rules, you have to
15551provide the configuration file describing the corresponding naming scheme (see
15552the description of the @command{gnatmetric} switches below.)
15553Alternatively, you may use a project file and invoke @command{gnatmetric}
15554through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}),
15555or you can directly specify a project file as a @command{gnatmetric} parameter.
15556
15557The @command{gnatmetric} command has the form
15558
15559@smallexample
15560@c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15561@c Expanding @ovar macro inline (explanation in macro def comments)
15562$ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15563@end smallexample
15564
15565@noindent
15566where
15567@itemize @bullet
15568@item
15569@var{switches} specify the metrics to compute and define the destination for
15570the output
15571
15572@item
15573Each @var{filename} is the name (including the extension) of a source
15574file to process. ``Wildcards'' are allowed, and
15575the file name may contain path information.
15576If no @var{filename} is supplied, then the @var{switches} list must contain
15577at least one
15578@option{-files} switch (@pxref{Other gnatmetric Switches}).
15579Including both a @option{-files} switch and one or more
15580@var{filename} arguments is permitted.
15581
15582@item
15583@samp{@var{gcc_switches}} is a list of switches for
15584@command{gcc}. They will be passed on to all compiler invocations made by
15585@command{gnatmetric} to generate the ASIS trees. Here you can provide
15586@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15587and use the @option{-gnatec} switch to set the configuration file,
15588use the @option{-gnat05} switch if sources should be compiled in
15589Ada 2005 mode etc.
15590@end itemize
15591
15592@node Switches for gnatmetric
15593@section Switches for @command{gnatmetric}
15594
15595@noindent
15596The following subsections describe the various switches accepted by
15597@command{gnatmetric}, organized by category.
15598
15599@menu
15600* Output Files Control::
15601* Disable Metrics For Local Units::
15602* Specifying a set of metrics to compute::
15603* Other gnatmetric Switches::
15604@ignore
15605* Generate project-wide metrics::
15606@end ignore
15607@end menu
15608
15609@node Output Files Control
15610@subsection Output File Control
15611@cindex Output file control in @command{gnatmetric}
15612
15613@noindent
15614@command{gnatmetric} has two output formats. It can generate a
15615textual (human-readable) form, and also XML. By default only textual
15616output is generated.
15617
15618When generating the output in textual form, @command{gnatmetric} creates
15619for each Ada source file a corresponding text file
15620containing the computed metrics, except for the case when the set of metrics
15621specified by gnatmetric parameters consists only of metrics that are computed
15622for the whole set of analyzed sources, but not for each Ada source.
15623By default, the name of the file containing metric information for a source
15624is obtained by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the
15625name of the input source file. If not otherwise specified and no project file
15626is specified as @command{gnatmetric} option this file is placed in the same
15627directory as where the source file is located. If @command{gnatmetric} has a
15628project  file as its parameter, it places all the generated files in the
15629object directory of the project (or in the project source directory if the
15630project does not define an objects directory), if @option{--subdirs} option
15631is specified, the files are placed in the subrirectory of this directory
15632specified by this option.
15633
15634All the output information generated in XML format is placed in a single
15635file. By default the name of this file is ^@file{metrix.xml}^@file{METRIX$XML}^.
15636If not otherwise specified and if no project file is specified
15637as @command{gnatmetric} option  this file is placed in the
15638current directory.
15639
15640Some of the computed metrics are summed over the units passed to
15641@command{gnatmetric}; for example, the total number of lines of code.
15642By default this information is sent to @file{stdout}, but a file
15643can be specified with the @option{-og} switch.
15644
15645The following switches control the @command{gnatmetric} output:
15646
15647@table @option
15648@cindex @option{^-x^/XML^} (@command{gnatmetric})
15649@item ^-x^/XML^
15650Generate the XML output
15651
15652@cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15653@item ^-xs^/XSD^
15654Generate the XML output and the XML schema file that describes the structure
15655of the XML metric report, this schema is assigned to the XML file. The schema
15656file has the same name as the XML output file with @file{.xml} suffix replaced
15657with @file{.xsd}
15658
15659@cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15660@item ^-nt^/NO_TEXT^
15661Do not generate the output in text form (implies @option{^-x^/XML^})
15662
15663@cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15664@item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15665Put text files with detailed metrics into @var{output_dir}
15666
15667@cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15668@item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15669Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15670in the name of the output file.
15671
15672@cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15673@item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15674Put global metrics into @var{file_name}
15675
15676@cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15677@item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15678Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15679
15680@cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15681@item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15682Use ``short'' source file names in the output.  (The @command{gnatmetric}
15683output includes the name(s) of the Ada source file(s) from which the metrics
15684are computed.  By default each name includes the absolute path. The
15685@option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15686to exclude all directory information from the file names that are output.)
15687
15688@end table
15689
15690@node Disable Metrics For Local Units
15691@subsection Disable Metrics For Local Units
15692@cindex Disable Metrics For Local Units in @command{gnatmetric}
15693
15694@noindent
15695@command{gnatmetric} relies on the GNAT compilation model @minus{}
15696one compilation
15697unit per one source file. It computes line metrics for the whole source
15698file, and it also computes syntax
15699and complexity metrics for the file's outermost unit.
15700
15701By default, @command{gnatmetric} will also compute all metrics for certain
15702kinds of locally declared program units:
15703
15704@itemize @bullet
15705@item
15706subprogram (and generic subprogram) bodies;
15707
15708@item
15709package (and generic package) specs and bodies;
15710
15711@item
15712task object and type specifications and bodies;
15713
15714@item
15715protected object and type specifications and bodies.
15716@end itemize
15717
15718@noindent
15719These kinds of entities will be referred to as
15720@emph{eligible local program units}, or simply @emph{eligible local units},
15721@cindex Eligible local unit (for @command{gnatmetric})
15722in the discussion below.
15723
15724Note that a subprogram declaration, generic instantiation,
15725or renaming declaration only receives metrics
15726computation when it appear as the outermost entity
15727in a source file.
15728
15729Suppression of metrics computation for eligible local units can be
15730obtained via the following switch:
15731
15732@table @option
15733@cindex @option{^-nolocal^/SUPPRESS^} (@command{gnatmetric})
15734@item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15735Do not compute detailed metrics for eligible local program units
15736
15737@end table
15738
15739@node Specifying a set of metrics to compute
15740@subsection Specifying a set of metrics to compute
15741
15742@noindent
15743By default all the metrics are computed and reported. The switches
15744described in this subsection allow you to control, on an individual
15745basis, whether metrics are computed and
15746reported. If at least one positive metric
15747switch is specified (that is, a switch that defines that a given
15748metric or set of metrics is to be computed), then only
15749explicitly specified metrics are reported.
15750
15751@menu
15752* Line Metrics Control::
15753* Syntax Metrics Control::
15754* Complexity Metrics Control::
15755* Coupling Metrics Control::
15756@end menu
15757
15758@node Line Metrics Control
15759@subsubsection Line Metrics Control
15760@cindex Line metrics control in @command{gnatmetric}
15761
15762@noindent
15763For any (legal) source file, and for each of its
15764eligible local program units, @command{gnatmetric} computes the following
15765metrics:
15766
15767@itemize @bullet
15768@item
15769the total number of lines;
15770
15771@item
15772the total number of code lines (i.e., non-blank lines that are not comments)
15773
15774@item
15775the number of comment lines
15776
15777@item
15778the number of code lines containing end-of-line comments;
15779
15780@item
15781the comment percentage: the ratio between the number of lines that contain
15782comments and the number of all non-blank lines, expressed as a percentage;
15783
15784@item
15785the number of empty lines and lines containing only space characters and/or
15786format effectors (blank lines)
15787
15788@item
15789the average number of code lines in subprogram bodies, task bodies, entry
15790bodies and statement sequences in package bodies (this metric is only computed
15791across the whole set of the analyzed units)
15792
15793@end itemize
15794
15795@noindent
15796@command{gnatmetric} sums the values of the line metrics for all the
15797files being processed and then generates the cumulative results. The tool
15798also computes for all the files being processed the average number of code
15799lines in bodies.
15800
15801You can use the following switches to select the specific line metrics
15802to be computed and reported.
15803
15804@table @option
15805@cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15806
15807@ifclear vms
15808@cindex @option{--no-lines@var{x}}
15809@end ifclear
15810
15811@item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15812Report all the line metrics
15813
15814@item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15815Do not report any of line metrics
15816
15817@item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15818Report the number of all lines
15819
15820@item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15821Do not report the number of all lines
15822
15823@item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15824Report the number of code lines
15825
15826@item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15827Do not report the number of code lines
15828
15829@item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15830Report the number of comment lines
15831
15832@item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15833Do not report the number of comment lines
15834
15835@item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15836Report the number of code lines containing
15837end-of-line comments
15838
15839@item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15840Do not report the number of code lines containing
15841end-of-line comments
15842
15843@item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15844Report the comment percentage in the program text
15845
15846@item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15847Do not report the comment percentage in the program text
15848
15849@item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15850Report the number of blank lines
15851
15852@item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15853Do not report the number of blank lines
15854
15855@item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15856Report the average number of code lines in subprogram bodies, task bodies,
15857entry bodies and statement sequences in package bodies. The metric is computed
15858and reported for the whole set of processed Ada sources only.
15859
15860@item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15861Do not report the average number of code lines in subprogram bodies,
15862task bodies, entry bodies and statement sequences in package bodies.
15863
15864@end table
15865
15866@node Syntax Metrics Control
15867@subsubsection Syntax Metrics Control
15868@cindex Syntax metrics control in @command{gnatmetric}
15869
15870@noindent
15871@command{gnatmetric} computes various syntactic metrics for the
15872outermost unit and for each eligible local unit:
15873
15874@table @emph
15875@item LSLOC (``Logical Source Lines Of Code'')
15876The total number of declarations and the total number of statements. Note
15877that the definition of declarations is the one given in the reference
15878manual:
15879
15880@noindent
15881``Each of the following is defined to be a declaration: any basic_declaration;
15882an enumeration_literal_specification; a discriminant_specification;
15883a component_declaration; a loop_parameter_specification; a
15884parameter_specification; a subprogram_body; an entry_declaration;
15885an entry_index_specification; a choice_parameter_specification;
15886a generic_formal_parameter_declaration.''
15887
15888This means for example that each enumeration literal adds one to the count,
15889as well as each subprogram parameter.
15890
15891Thus the results from this metric will be significantly greater than might
15892be expected from a naive view of counting semicolons.
15893
15894@item Maximal static nesting level of inner program units
15895According to
15896@cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15897package, a task unit, a protected unit, a
15898protected entry, a generic unit, or an explicitly declared subprogram other
15899than an enumeration literal.''
15900
15901@item Maximal nesting level of composite syntactic constructs
15902This corresponds to the notion of the
15903maximum nesting level in the GNAT built-in style checks
15904(@pxref{Style Checking})
15905@end table
15906
15907@noindent
15908For the outermost unit in the file, @command{gnatmetric} additionally computes
15909the following metrics:
15910
15911@table @emph
15912@item Public subprograms
15913This metric is computed for package specs. It is the
15914number of subprograms and generic subprograms declared in the visible
15915part (including the visible part of nested packages, protected objects, and
15916protected types).
15917
15918@item All subprograms
15919This metric is computed for bodies and subunits. The
15920metric is equal to a total number of subprogram bodies in the compilation
15921unit.
15922Neither generic instantiations nor renamings-as-a-body nor body stubs
15923are counted. Any subprogram body is counted, independently of its nesting
15924level and enclosing constructs. Generic bodies and bodies of protected
15925subprograms are counted in the same way as ``usual'' subprogram bodies.
15926
15927@item Public types
15928This metric is computed for package specs and
15929generic package declarations. It is the total number of types
15930that can be referenced from outside this compilation unit, plus the
15931number of types from all the visible parts of all the visible generic
15932packages. Generic formal types are not counted.  Only types, not subtypes,
15933are included.
15934
15935@noindent
15936Along with the total number of public types, the following
15937types are counted and reported separately:
15938
15939@itemize @bullet
15940@item
15941Abstract types
15942
15943@item
15944Root tagged types (abstract, non-abstract, private, non-private). Type
15945extensions are @emph{not} counted
15946
15947@item
15948Private types (including private extensions)
15949
15950@item
15951Task types
15952
15953@item
15954Protected types
15955
15956@end itemize
15957
15958@item All types
15959This metric is computed for any compilation unit. It is equal to the total
15960number of the declarations of different types given in the compilation unit.
15961The private and the corresponding full type declaration are counted as one
15962type declaration. Incomplete type declarations and generic formal types
15963are not counted.
15964No distinction is made among different kinds of types (abstract,
15965private etc.); the total number of types is computed and reported.
15966
15967@end table
15968
15969@noindent
15970By default, all the syntax metrics are computed and reported. You can use the
15971following switches to select specific syntax metrics.
15972
15973@table @option
15974
15975@cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
15976
15977@ifclear vms
15978@cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15979@end ifclear
15980
15981@item ^--syntax-all^/SYNTAX_METRICS=ALL^
15982Report all the syntax metrics
15983
15984@item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
15985Do not report any of syntax metrics
15986
15987@item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
15988Report the total number of declarations
15989
15990@item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
15991Do not report the total number of declarations
15992
15993@item ^--statements^/SYNTAX_METRICS=STATEMENTS^
15994Report the total number of statements
15995
15996@item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
15997Do not report the total number of statements
15998
15999@item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
16000Report the number of public subprograms in a compilation unit
16001
16002@item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
16003Do not report the number of public subprograms in a compilation unit
16004
16005@item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
16006Report the number of all the subprograms in a compilation unit
16007
16008@item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
16009Do not report the number of all the subprograms in a compilation unit
16010
16011@item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
16012Report the number of public types in a compilation unit
16013
16014@item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
16015Do not report the number of public types in a compilation unit
16016
16017@item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
16018Report the number of all the types in a compilation unit
16019
16020@item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
16021Do not report the number of all the types in a compilation unit
16022
16023@item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
16024Report the maximal program unit nesting level
16025
16026@item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16027Do not report the maximal program unit nesting level
16028
16029@item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
16030Report the maximal construct nesting level
16031
16032@item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
16033Do not report the maximal construct nesting level
16034
16035@end table
16036
16037@node Complexity Metrics Control
16038@subsubsection Complexity Metrics Control
16039@cindex Complexity metrics control in @command{gnatmetric}
16040
16041@noindent
16042For a program unit that is an executable body (a subprogram body (including
16043generic bodies), task body, entry body or a package body containing
16044its own statement sequence) @command{gnatmetric} computes the following
16045complexity metrics:
16046
16047@itemize @bullet
16048@item
16049McCabe cyclomatic complexity;
16050
16051@item
16052McCabe essential complexity;
16053
16054@item
16055maximal loop nesting level;
16056
16057@item
16058extra exit points (for subprograms);
16059@end itemize
16060
16061@noindent
16062The McCabe cyclomatic complexity metric is defined
16063in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
16064
16065According to McCabe, both control statements and short-circuit control forms
16066should be taken into account when computing cyclomatic complexity.
16067For Ada 2012 we have also take into account conditional expressions
16068and quantified expressions. For each body, we compute three metric values:
16069
16070@itemize @bullet
16071@item
16072the complexity introduced by control
16073statements only, without taking into account short-circuit forms,
16074
16075@item
16076the complexity introduced by short-circuit control forms only, and
16077
16078@item
16079the total
16080cyclomatic complexity, which is the sum of these two values.
16081@end itemize
16082
16083@noindent
16084
16085The cyclomatic complexity is also computed for Ada 2012 expression functions.
16086An expression function cannot have statements as its components, so only one
16087metric value is computed as a cyclomatic complexity of an expression function.
16088
16089The origin of cyclomatic complexity metric is the need to estimate the number
16090of independent paths in the control flow graph that in turn gives the number
16091of tests needed to satisfy paths coverage testing completeness criterion.
16092Considered from the testing point of view, a static Ada @code{loop} (that is,
16093the @code{loop} statement having static subtype in loop parameter
16094specification) does not add to cyclomatic complexity. By providing
16095@option{^--no-static-loop^NO_STATIC_LOOP^} option a user
16096may specify that such loops should not be counted when computing the
16097cyclomatic complexity metric
16098
16099The Ada essential complexity metric is a McCabe cyclomatic complexity metric
16100counted for the code that is reduced by excluding all the pure structural Ada
16101control statements. An compound statement is considered as a non-structural
16102if it contains a @code{raise} or @code{return} statement as it subcomponent,
16103or if it contains a @code{goto} statement that transfers the control outside
16104the operator. A selective accept statement with @code{terminate} alternative
16105is considered as non-structural statement. When computing this metric,
16106@code{exit} statements are treated in the same way as @code{goto}
16107statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
16108
16109The Ada essential complexity metric defined here is intended to quantify
16110the extent to which the software is unstructured. It is adapted from
16111the McCabe essential complexity metric defined in
16112@url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
16113suitable for typical Ada usage. For example, short circuit forms
16114are not penalized as unstructured in the Ada essential complexity metric.
16115
16116When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16117the code in the exception handlers and in all the nested program units. The
16118code of assertions and predicates (that is, subprogram preconditions and
16119postconditions, subtype predicates and type invariants) is also skipped.
16120
16121By default, all the complexity metrics are computed and reported.
16122For more fine-grained control you can use
16123the following switches:
16124
16125@table @option
16126@cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16127
16128@ifclear vms
16129@cindex @option{--no-complexity@var{x}}
16130@end ifclear
16131
16132@item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
16133Report all the complexity metrics
16134
16135@item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
16136Do not report any of complexity metrics
16137
16138@item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
16139Report the McCabe Cyclomatic Complexity
16140
16141@item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
16142Do not report the McCabe Cyclomatic Complexity
16143
16144@item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
16145Report the Essential Complexity
16146
16147@item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
16148Do not report the Essential Complexity
16149
16150@item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16151Report maximal loop nesting level
16152
16153@item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
16154Do not report maximal loop nesting level
16155
16156@item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
16157Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16158task bodies, entry bodies and statement sequences in package bodies.
16159The metric is computed and reported for whole set of processed Ada sources
16160only.
16161
16162@item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
16163Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16164bodies, task bodies, entry bodies and statement sequences in package bodies
16165
16166@cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16167@item ^-ne^/NO_EXITS_AS_GOTOS^
16168Do not consider @code{exit} statements as @code{goto}s when
16169computing Essential Complexity
16170
16171@cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
16172@item ^--no-static-loop^/NO_STATIC_LOOP^
16173Do not consider static loops when computing cyclomatic complexity
16174
16175@item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
16176Report the extra exit points for subprogram bodies. As an exit point, this
16177metric counts @code{return} statements and raise statements in case when the
16178raised exception is not handled in the same body. In case of a function this
16179metric subtracts 1 from the number of exit points, because a function body
16180must contain at least one @code{return} statement.
16181
16182@item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
16183Do not report the extra exit points for subprogram bodies
16184@end table
16185
16186
16187@node Coupling Metrics Control
16188@subsubsection Coupling Metrics Control
16189@cindex Coupling metrics control in @command{gnatmetric}
16190
16191@noindent
16192@cindex Coupling metrics (in in @command{gnatmetric})
16193Coupling metrics measure the dependencies between a given entity and other
16194entities the program consists of. The goal of these metrics is to estimate the
16195stability of the whole program considered as the collection of entities
16196(modules, classes etc.).
16197
16198Gnatmetric computes the following coupling metrics:
16199
16200@itemize @bullet
16201
16202@item
16203@emph{object-oriented coupling} - for classes in traditional object-oriented
16204sense;
16205
16206@item
16207@emph{unit coupling} - for all the program units making up a program;
16208
16209@item
16210@emph{control coupling} - this metric counts dependencies between a unit and
16211only those units that define subprograms;
16212@end itemize
16213
16214@noindent
16215Two kinds of coupling metrics are computed:
16216
16217@table @asis
16218@item fan-out coupling (efferent coupling)
16219@cindex fan-out coupling
16220@cindex efferent coupling
16221the number of entities the given entity depends upon. It
16222estimates in what extent the given entity depends on the changes in
16223``external world''
16224
16225@item fan-in coupling (afferent coupling)
16226@cindex fan-in coupling
16227@cindex afferent coupling
16228the number of entities that depend on a given entity.
16229It estimates in what extent the ``external world'' depends on the changes in a
16230given entity
16231@end table
16232
16233@noindent
16234
16235Object-oriented coupling metrics are metrics that measure the dependencies
16236between a given class (or a group of classes) and the other classes in the
16237program. In this subsection the term ``class'' is used in its traditional
16238object-oriented programming sense (an instantiable module that contains data
16239and/or method members). A @emph{category} (of classes) is a group of closely
16240related classes that are reused and/or modified together.
16241
16242A class @code{K}'s fan-out coupling is the number of classes
16243that @code{K} depends upon.
16244A category's fan-out coupling is the number of classes outside the
16245category that the classes inside the category depend upon.
16246
16247A class @code{K}'s fan-in coupling is the number of classes
16248that depend upon @code{K}.
16249A category's fan-in coupling is the number of classes outside the
16250category that depend on classes belonging to the category.
16251
16252Ada's implementation of the object-oriented paradigm does not use the
16253traditional class notion, so the definition of the coupling
16254metrics for Ada maps the class and class category notions
16255onto Ada constructs.
16256
16257For the coupling metrics, several kinds of modules -- a library package,
16258a library generic package, and a library generic package instantiation --
16259that define a tagged type or an interface type are
16260considered to be a class. A category consists of a library package (or
16261a library generic package) that defines a tagged or an interface type,
16262together with all its descendant (generic) packages that define tagged
16263or interface types. That is a
16264category is an Ada hierarchy of library-level program units. So class coupling
16265in case of Ada is called as tagged coupling, and category coupling - as
16266hierarchy coupling.
16267
16268For any package counted as a class, its body and subunits (if any) are
16269considered together with its spec when counting the dependencies, and coupling
16270metrics are reported for spec units only. For dependencies between classes,
16271the Ada semantic dependencies are considered. For object-oriented coupling
16272metrics, only dependencies on units that are considered as classes, are
16273considered.
16274
16275For unit and control coupling also not compilation units but program units are
16276counted. That is, for a package, its spec, its body and its subunits (if any)
16277are considered as making up one unit, and the dependencies that are counted
16278are the dependencies of all these compilation units collected together as
16279the dependencies as a (whole) unit. And metrics are reported for spec
16280compilation units only (or for a subprogram body unit in case if there is no
16281separate spec for the given subprogram).
16282
16283For unit coupling, dependencies between all kinds of program units are
16284considered. For control coupling, for each unit the dependencies of this unit
16285upon units that define subprograms are counted, so control fan-out coupling
16286is reported for all units, but control fan-in coupling - only for the units
16287that define subprograms.
16288
16289The following simple example illustrates the difference between unit coupling
16290and control coupling metrics:
16291
16292@smallexample @c ada
16293package Lib_1 is
16294    function F_1 (I : Integer) return Integer;
16295end Lib_1;
16296
16297package Lib_2 is
16298    type T_2 is new Integer;
16299end Lib_2;
16300
16301package body Lib_1 is
16302    function F_1 (I : Integer) return Integer is
16303    begin
16304       return I + 1;
16305    end F_1;
16306end Lib_1;
16307
16308with Lib_2; use Lib_2;
16309package Pack is
16310    Var : T_2;
16311    function Fun (I : Integer) return Integer;
16312end Pack;
16313
16314with Lib_1; use Lib_1;
16315package body Pack is
16316    function Fun (I : Integer) return Integer is
16317    begin
16318       return F_1 (I);
16319    end Fun;
16320end Pack;
16321@end smallexample
16322
16323@noindent
16324if we apply @command{gnatmetric} with @code{--coupling-all} option to these
16325units, the result will be:
16326
16327@smallexample
16328Coupling metrics:
16329=================
16330    Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16331       control fan-out coupling  : 0
16332       control fan-in coupling   : 1
16333       unit fan-out coupling     : 0
16334       unit fan-in coupling      : 1
16335
16336    Unit Pack (C:\customers\662\L406-007\pack.ads)
16337       control fan-out coupling  : 1
16338       control fan-in coupling   : 0
16339       unit fan-out coupling     : 2
16340       unit fan-in coupling      : 0
16341
16342    Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16343       control fan-out coupling  : 0
16344       unit fan-out coupling     : 0
16345       unit fan-in coupling      : 1
16346@end smallexample
16347
16348@noindent
16349The result does not contain values for object-oriented
16350coupling because none of the argument unit contains a tagged type and
16351therefore none of these units can be treated as a class.
16352
16353@code{Pack} (considered as a program unit, that is spec+body) depends on two
16354units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
16355equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
16356well as control fan-in coupling. Only one of the units @code{Pack} depends
16357upon defines a subprogram, so its control fan-out coupling is 1.
16358
16359@code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
16360not define a subprogram, so control fan-in metric cannot be applied to it,
16361and there is one unit that depends on it (@code{Pack}), so it has
16362unit fan-in coupling equals to 1.
16363
16364@code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16365So it has control fan-in coupling equals to 1 (because there is a unit
16366depending on it).
16367
16368When computing coupling metrics, @command{gnatmetric} counts only
16369dependencies between units that are arguments of the @command{gnatmetric}
16370call. Coupling metrics are program-wide (or project-wide) metrics, so to
16371get a valid result, you should call @command{gnatmetric} for
16372the whole set of sources that make up your program. It can be done
16373by calling @command{gnatmetric} from the GNAT driver with @option{-U}
16374option (see @ref{The GNAT Driver and Project Files} for details).
16375
16376By default, all the coupling metrics are disabled. You can use the following
16377switches to specify the coupling metrics to be computed and reported:
16378
16379@table @option
16380
16381@ifclear vms
16382@cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16383@cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16384@cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16385@cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16386@end ifclear
16387
16388@ifset vms
16389@cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16390@end ifset
16391
16392@item ^--coupling-all^/COUPLING_METRICS=ALL^
16393Report all the coupling metrics
16394
16395@item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16396Report tagged (class) fan-out coupling
16397
16398@item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16399Report tagged (class) fan-in coupling
16400
16401@item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16402Report hierarchy (category) fan-out coupling
16403
16404@item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16405Report hierarchy (category) fan-in coupling
16406
16407@item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16408Report unit fan-out coupling
16409
16410@item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16411Report unit fan-in coupling
16412
16413@item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16414Report control fan-out coupling
16415
16416@item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16417Report control fan-in coupling
16418@end table
16419
16420@node Other gnatmetric Switches
16421@subsection Other @code{gnatmetric} Switches
16422
16423@noindent
16424Additional @command{gnatmetric} switches are as follows:
16425
16426@table @option
16427@item --version
16428@cindex @option{--version} @command{gnatmetric}
16429Display Copyright and version, then exit disregarding all other options.
16430
16431@item --help
16432@cindex @option{--help} @command{gnatmetric}
16433Display usage, then exit disregarding all other options.
16434
16435@item -P @var{file}
16436@cindex @option{-P} @command{gnatmetric}
16437Indicates the name of the project file that describes the set of sources
16438to be processed. The exact set of argument sources depends on other options
16439specified, see below.
16440
16441@item -U
16442@cindex @option{-U} @command{gnatmetric}
16443If a project file is specified and no argument source is explicitly
16444specified (either directly or by means of @option{-files} option), process
16445all the units of the closure of the argument project. Otherwise this option
16446has no effect.
16447
16448@item -U @var{main_unit}
16449If a project file is specified and no argument source is explicitly
16450specified (either directly or by means of @option{-files} option), process
16451the closure of units rooted at @var{main_unit}. Otherwise this option
16452has no effect.
16453
16454@item -X@var{name}=@var{value}
16455@cindex @option{-X} @command{gnatmetric}
16456Indicates that external variable @var{name} in the argument project
16457has the value @var{value}. Has no effect if no project is specified as
16458tool argument.
16459
16460@item --subdirs=@var{dir}
16461@cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
16462Use the specified subdirectory of the project objects file (or of the
16463project file directory if the project does not specify an object directory)
16464for tool output files. Has no effect if no project is specified as
16465tool argument r if @option{--no_objects_dir} is specified.
16466
16467@item --no_objects_dir
16468@cindex @option{--no_objects_dir} @command{gnatmetric}
16469Place all the result files into the current directory instead of
16470project objects directory. This corresponds to the @command{gnatcheck}
16471behavior when it is called with the project file from the
16472GNAT driver. Has no effect if no project is specified.
16473
16474@item ^-files @var{filename}^/FILES=@var{filename}^
16475@cindex @option{^-files^/FILES^} (@code{gnatmetric})
16476Take the argument source files from the specified file. This file should be an
16477ordinary text file containing file names separated by spaces or
16478line breaks. You can use this switch more than once in the same call to
16479@command{gnatmetric}. You also can combine this switch with
16480an explicit list of files.
16481
16482@item ^-j^/PROCESSES=^@var{n}
16483@cindex @option{^-j^/PROCESSES^} (@command{gnatmetric})
16484Use @var{n} processes to carry out the tree creations (internal representations
16485of the argument sources). On a multiprocessor machine this speeds up processing
16486of big sets of argument sources. If @var{n} is 0, then the maximum number of
16487parallel tree creations is the number of core processors on the platform.
16488
16489@cindex @option{^-t^/TIME^} (@command{gnatmetric})
16490@item ^-t^/TIME^
16491Print out execution time.
16492
16493@item ^-v^/VERBOSE^
16494@cindex @option{^-v^/VERBOSE^} (@command{gnatmetric})
16495Verbose mode;
16496@command{gnatmetric} generates version information and then
16497a trace of sources being processed.
16498
16499@item ^-q^/QUIET^
16500@cindex @option{^-q^/QUIET^} (@command{gnatmetric})
16501Quiet mode.
16502@end table
16503
16504@noindent
16505If a project file is specified and no argument source is explicitly
16506specified (either directly or by means of @option{-files} option), and no
16507@option{-U} is specified, then the set of processed sources is
16508all the immediate units of the argument project.
16509
16510
16511@ignore
16512@node Generate project-wide metrics
16513@subsection Generate project-wide metrics
16514
16515In order to compute metrics on all units of a given project, you can use
16516the @command{gnat} driver along with the @option{-P} option:
16517@smallexample
16518   gnat metric -Pproj
16519@end smallexample
16520
16521@noindent
16522If the project @code{proj} depends upon other projects, you can compute
16523the metrics on the project closure using the @option{-U} option:
16524@smallexample
16525   gnat metric -Pproj -U
16526@end smallexample
16527
16528@noindent
16529Finally, if not all the units are relevant to a particular main
16530program in the project closure, you can generate metrics for the set
16531of units needed to create a given main program (unit closure) using
16532the @option{-U} option followed by the name of the main unit:
16533@smallexample
16534   gnat metric -Pproj -U main
16535@end smallexample
16536@end ignore
16537@end ifclear
16538
16539
16540@c ***********************************
16541@node File Name Krunching with gnatkr
16542@chapter File Name Krunching with @code{gnatkr}
16543@findex gnatkr
16544
16545@noindent
16546This chapter discusses the method used by the compiler to shorten
16547the default file names chosen for Ada units so that they do not
16548exceed the maximum length permitted. It also describes the
16549@code{gnatkr} utility that can be used to determine the result of
16550applying this shortening.
16551@menu
16552* About gnatkr::
16553* Using gnatkr::
16554* Krunching Method::
16555* Examples of gnatkr Usage::
16556@end menu
16557
16558@node About gnatkr
16559@section About @code{gnatkr}
16560
16561@noindent
16562The default file naming rule in GNAT
16563is that the file name must be derived from
16564the unit name. The exact default rule is as follows:
16565@itemize @bullet
16566@item
16567Take the unit name and replace all dots by hyphens.
16568@item
16569If such a replacement occurs in the
16570second character position of a name, and the first character is
16571^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16572then replace the dot by the character
16573^@samp{~} (tilde)^@samp{$} (dollar sign)^
16574instead of a minus.
16575@end itemize
16576The reason for this exception is to avoid clashes
16577with the standard names for children of System, Ada, Interfaces,
16578and GNAT, which use the prefixes
16579^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16580respectively.
16581
16582The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16583switch of the compiler activates a ``krunching''
16584circuit that limits file names to nn characters (where nn is a decimal
16585integer). For example, using OpenVMS,
16586where the maximum file name length is
1658739, the value of nn is usually set to 39, but if you want to generate
16588a set of files that would be usable if ported to a system with some
16589different maximum file length, then a different value can be specified.
16590The default value of 39 for OpenVMS need not be specified.
16591
16592The @code{gnatkr} utility can be used to determine the krunched name for
16593a given file, when krunched to a specified maximum length.
16594
16595@node Using gnatkr
16596@section Using @code{gnatkr}
16597
16598@noindent
16599The @code{gnatkr} command has the form
16600
16601@ifclear vms
16602@smallexample
16603@c $ gnatkr @var{name} @ovar{length}
16604@c Expanding @ovar macro inline (explanation in macro def comments)
16605$ gnatkr @var{name} @r{[}@var{length}@r{]}
16606@end smallexample
16607@end ifclear
16608
16609@ifset vms
16610@smallexample
16611$ gnatkr @var{name} /COUNT=nn
16612@end smallexample
16613@end ifset
16614
16615@noindent
16616@var{name} is the uncrunched file name, derived from the name of the unit
16617in the standard manner described in the previous section (i.e., in particular
16618all dots are replaced by hyphens). The file name may or may not have an
16619extension (defined as a suffix of the form period followed by arbitrary
16620characters other than period). If an extension is present then it will
16621be preserved in the output. For example, when krunching @file{hellofile.ads}
16622to eight characters, the result will be hellofil.ads.
16623
16624Note: for compatibility with previous versions of @code{gnatkr} dots may
16625appear in the name instead of hyphens, but the last dot will always be
16626taken as the start of an extension. So if @code{gnatkr} is given an argument
16627such as @file{Hello.World.adb} it will be treated exactly as if the first
16628period had been a hyphen, and for example krunching to eight characters
16629gives the result @file{hellworl.adb}.
16630
16631Note that the result is always all lower case (except on OpenVMS where it is
16632all upper case). Characters of the other case are folded as required.
16633
16634@var{length} represents the length of the krunched name. The default
16635when no argument is given is ^8^39^ characters. A length of zero stands for
16636unlimited, in other words do not chop except for system files where the
16637implied crunching length is always eight characters.
16638
16639@noindent
16640The output is the krunched name. The output has an extension only if the
16641original argument was a file name with an extension.
16642
16643@node Krunching Method
16644@section Krunching Method
16645
16646@noindent
16647The initial file name is determined by the name of the unit that the file
16648contains. The name is formed by taking the full expanded name of the
16649unit and replacing the separating dots with hyphens and
16650using ^lowercase^uppercase^
16651for all letters, except that a hyphen in the second character position is
16652replaced by a ^tilde^dollar sign^ if the first character is
16653^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16654The extension is @code{.ads} for a
16655spec and @code{.adb} for a body.
16656Krunching does not affect the extension, but the file name is shortened to
16657the specified length by following these rules:
16658
16659@itemize @bullet
16660@item
16661The name is divided into segments separated by hyphens, tildes or
16662underscores and all hyphens, tildes, and underscores are
16663eliminated. If this leaves the name short enough, we are done.
16664
16665@item
16666If the name is too long, the longest segment is located (left-most
16667if there are two of equal length), and shortened by dropping
16668its last character. This is repeated until the name is short enough.
16669
16670As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16671to fit the name into 8 characters as required by some operating systems.
16672
16673@smallexample
16674our-strings-wide_fixed 22
16675our strings wide fixed 19
16676our string  wide fixed 18
16677our strin   wide fixed 17
16678our stri    wide fixed 16
16679our stri    wide fixe  15
16680our str     wide fixe  14
16681our str     wid  fixe  13
16682our str     wid  fix   12
16683ou  str     wid  fix   11
16684ou  st      wid  fix   10
16685ou  st      wi   fix   9
16686ou  st      wi   fi    8
16687Final file name: oustwifi.adb
16688@end smallexample
16689
16690@item
16691The file names for all predefined units are always krunched to eight
16692characters. The krunching of these predefined units uses the following
16693special prefix replacements:
16694
16695@table @file
16696@item ada-
16697replaced by @file{^a^A^-}
16698
16699@item gnat-
16700replaced by @file{^g^G^-}
16701
16702@item interfaces-
16703replaced by @file{^i^I^-}
16704
16705@item system-
16706replaced by @file{^s^S^-}
16707@end table
16708
16709These system files have a hyphen in the second character position. That
16710is why normal user files replace such a character with a
16711^tilde^dollar sign^, to
16712avoid confusion with system file names.
16713
16714As an example of this special rule, consider
16715@*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16716
16717@smallexample
16718ada-strings-wide_fixed 22
16719a-  strings wide fixed 18
16720a-  string  wide fixed 17
16721a-  strin   wide fixed 16
16722a-  stri    wide fixed 15
16723a-  stri    wide fixe  14
16724a-  str     wide fixe  13
16725a-  str     wid  fixe  12
16726a-  str     wid  fix   11
16727a-  st      wid  fix   10
16728a-  st      wi   fix   9
16729a-  st      wi   fi    8
16730Final file name: a-stwifi.adb
16731@end smallexample
16732@end itemize
16733
16734Of course no file shortening algorithm can guarantee uniqueness over all
16735possible unit names, and if file name krunching is used then it is your
16736responsibility to ensure that no name clashes occur. The utility
16737program @code{gnatkr} is supplied for conveniently determining the
16738krunched name of a file.
16739
16740@node Examples of gnatkr Usage
16741@section Examples of @code{gnatkr} Usage
16742
16743@smallexample
16744@iftex
16745@leftskip=0cm
16746@end iftex
16747@ifclear vms
16748$ gnatkr very_long_unit_name.ads      --> velounna.ads
16749$ gnatkr grandparent-parent-child.ads --> grparchi.ads
16750$ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16751$ gnatkr grandparent-parent-child     --> grparchi
16752@end ifclear
16753$ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16754$ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16755@end smallexample
16756
16757@node Preprocessing with gnatprep
16758@chapter Preprocessing with @code{gnatprep}
16759@findex gnatprep
16760
16761@noindent
16762This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16763preprocessing.
16764Although designed for use with GNAT, @code{gnatprep} does not depend on any
16765special GNAT features.
16766For further discussion of conditional compilation in general, see
16767@ref{Conditional Compilation}.
16768
16769@menu
16770* Preprocessing Symbols::
16771* Using gnatprep::
16772* Switches for gnatprep::
16773* Form of Definitions File::
16774* Form of Input Text for gnatprep::
16775@end menu
16776
16777@node Preprocessing Symbols
16778@section Preprocessing Symbols
16779
16780@noindent
16781Preprocessing symbols are defined in definition files and referred to in
16782sources to be preprocessed. A Preprocessing symbol is an identifier, following
16783normal Ada (case-insensitive) rules for its syntax, with the restriction that
16784all characters need to be in the ASCII set (no accented letters).
16785
16786@node Using gnatprep
16787@section Using @code{gnatprep}
16788
16789@noindent
16790To call @code{gnatprep} use
16791
16792@smallexample
16793@c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16794@c Expanding @ovar macro inline (explanation in macro def comments)
16795$ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16796@end smallexample
16797
16798@noindent
16799where
16800@table @var
16801@item switches
16802is an optional sequence of switches as described in the next section.
16803
16804@item infile
16805is the full name of the input file, which is an Ada source
16806file containing preprocessor directives.
16807
16808@item outfile
16809is the full name of the output file, which is an Ada source
16810in standard Ada form. When used with GNAT, this file name will
16811normally have an ads or adb suffix.
16812
16813@item deffile
16814is the full name of a text file containing definitions of
16815preprocessing symbols to be referenced by the preprocessor. This argument is
16816optional, and can be replaced by the use of the @option{-D} switch.
16817
16818@end table
16819
16820@node Switches for gnatprep
16821@section Switches for @code{gnatprep}
16822
16823@table @option
16824@c !sort!
16825
16826@item ^-b^/BLANK_LINES^
16827@cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16828Causes both preprocessor lines and the lines deleted by
16829preprocessing to be replaced by blank lines in the output source file,
16830preserving line numbers in the output file.
16831
16832@item ^-c^/COMMENTS^
16833@cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16834Causes both preprocessor lines and the lines deleted
16835by preprocessing to be retained in the output source as comments marked
16836with the special string @code{"--! "}. This option will result in line numbers
16837being preserved in the output file.
16838
16839@item ^-C^/REPLACE_IN_COMMENTS^
16840@cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16841Causes comments to be scanned. Normally comments are ignored by gnatprep.
16842If this option is specified, then comments are scanned and any $symbol
16843substitutions performed as in program text. This is particularly useful
16844when structured comments are used (e.g., when writing programs in the
16845SPARK dialect of Ada). Note that this switch is not available when
16846doing integrated preprocessing (it would be useless in this context
16847since comments are ignored by the compiler in any case).
16848
16849@item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16850@cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16851Defines a new preprocessing symbol, associated with value. If no value is given
16852on the command line, then symbol is considered to be @code{True}. This switch
16853can be used in place of a definition file.
16854
16855@ifset vms
16856@item /REMOVE
16857@cindex @option{/REMOVE} (@command{gnatprep})
16858This is the default setting which causes lines deleted by preprocessing
16859to be entirely removed from the output file.
16860@end ifset
16861
16862@item ^-r^/REFERENCE^
16863@cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16864Causes a @code{Source_Reference} pragma to be generated that
16865references the original input file, so that error messages will use
16866the file name of this original file. The use of this switch implies
16867that preprocessor lines are not to be removed from the file, so its
16868use will force @option{^-b^/BLANK_LINES^} mode if
16869@option{^-c^/COMMENTS^}
16870has not been specified explicitly.
16871
16872Note that if the file to be preprocessed contains multiple units, then
16873it will be necessary to @code{gnatchop} the output file from
16874@code{gnatprep}. If a @code{Source_Reference} pragma is present
16875in the preprocessed file, it will be respected by
16876@code{gnatchop ^-r^/REFERENCE^}
16877so that the final chopped files will correctly refer to the original
16878input source file for @code{gnatprep}.
16879
16880@item ^-s^/SYMBOLS^
16881@cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16882Causes a sorted list of symbol names and values to be
16883listed on the standard output file.
16884
16885@item ^-u^/UNDEFINED^
16886@cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16887Causes undefined symbols to be treated as having the value FALSE in the context
16888of a preprocessor test. In the absence of this option, an undefined symbol in
16889a @code{#if} or @code{#elsif} test will be treated as an error.
16890
16891@end table
16892
16893@ifclear vms
16894@noindent
16895Note: if neither @option{-b} nor @option{-c} is present,
16896then preprocessor lines and
16897deleted lines are completely removed from the output, unless -r is
16898specified, in which case -b is assumed.
16899@end ifclear
16900
16901@node Form of Definitions File
16902@section Form of Definitions File
16903
16904@noindent
16905The definitions file contains lines of the form
16906
16907@smallexample
16908symbol := value
16909@end smallexample
16910
16911@noindent
16912where symbol is a preprocessing symbol, and value is one of the following:
16913
16914@itemize @bullet
16915@item
16916Empty, corresponding to a null substitution
16917@item
16918A string literal using normal Ada syntax
16919@item
16920Any sequence of characters from the set
16921(letters, digits, period, underline).
16922@end itemize
16923
16924@noindent
16925Comment lines may also appear in the definitions file, starting with
16926the usual @code{--},
16927and comments may be added to the definitions lines.
16928
16929@node Form of Input Text for gnatprep
16930@section Form of Input Text for @code{gnatprep}
16931
16932@noindent
16933The input text may contain preprocessor conditional inclusion lines,
16934as well as general symbol substitution sequences.
16935
16936The preprocessor conditional inclusion commands have the form
16937
16938@smallexample
16939@group
16940@cartouche
16941#if @i{expression} @r{[}then@r{]}
16942   lines
16943#elsif @i{expression} @r{[}then@r{]}
16944   lines
16945#elsif @i{expression} @r{[}then@r{]}
16946   lines
16947@dots{}
16948#else
16949   lines
16950#end if;
16951@end cartouche
16952@end group
16953@end smallexample
16954
16955@noindent
16956In this example, @i{expression} is defined by the following grammar:
16957@smallexample
16958@i{expression} ::=  <symbol>
16959@i{expression} ::=  <symbol> = "<value>"
16960@i{expression} ::=  <symbol> = <symbol>
16961@i{expression} ::=  <symbol> = <integer>
16962@i{expression} ::=  <symbol> > <integer>
16963@i{expression} ::=  <symbol> >= <integer>
16964@i{expression} ::=  <symbol> < <integer>
16965@i{expression} ::=  <symbol> <= <integer>
16966@i{expression} ::=  <symbol> 'Defined
16967@i{expression} ::=  not @i{expression}
16968@i{expression} ::=  @i{expression} and @i{expression}
16969@i{expression} ::=  @i{expression} or @i{expression}
16970@i{expression} ::=  @i{expression} and then @i{expression}
16971@i{expression} ::=  @i{expression} or else @i{expression}
16972@i{expression} ::=  ( @i{expression} )
16973@end smallexample
16974
16975The following restriction exists: it is not allowed to have "and" or "or"
16976following "not" in the same expression without parentheses. For example, this
16977is not allowed:
16978
16979@smallexample
16980   not X or Y
16981@end smallexample
16982
16983This should be one of the following:
16984
16985@smallexample
16986   (not X) or Y
16987   not (X or Y)
16988@end smallexample
16989
16990@noindent
16991For the first test (@i{expression} ::= <symbol>) the symbol must have
16992either the value true or false, that is to say the right-hand of the
16993symbol definition must be one of the (case-insensitive) literals
16994@code{True} or @code{False}. If the value is true, then the
16995corresponding lines are included, and if the value is false, they are
16996excluded.
16997
16998When comparing a symbol to an integer, the integer is any non negative
16999literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
170002#11#. The symbol value must also be a non negative integer. Integer values
17001in the range 0 .. 2**31-1 are supported.
17002
17003The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17004the symbol has been defined in the definition file or by a @option{-D}
17005switch on the command line. Otherwise, the test is false.
17006
17007The equality tests are case insensitive, as are all the preprocessor lines.
17008
17009If the symbol referenced is not defined in the symbol definitions file,
17010then the effect depends on whether or not switch @option{-u}
17011is specified. If so, then the symbol is treated as if it had the value
17012false and the test fails. If this switch is not specified, then
17013it is an error to reference an undefined symbol. It is also an error to
17014reference a symbol that is defined with a value other than @code{True}
17015or @code{False}.
17016
17017The use of the @code{not} operator inverts the sense of this logical test.
17018The @code{not} operator cannot be combined with the @code{or} or @code{and}
17019operators, without parentheses. For example, "if not X or Y then" is not
17020allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17021
17022The @code{then} keyword is optional as shown
17023
17024The @code{#} must be the first non-blank character on a line, but
17025otherwise the format is free form. Spaces or tabs may appear between
17026the @code{#} and the keyword. The keywords and the symbols are case
17027insensitive as in normal Ada code. Comments may be used on a
17028preprocessor line, but other than that, no other tokens may appear on a
17029preprocessor line. Any number of @code{elsif} clauses can be present,
17030including none at all. The @code{else} is optional, as in Ada.
17031
17032The @code{#} marking the start of a preprocessor line must be the first
17033non-blank character on the line, i.e., it must be preceded only by
17034spaces or horizontal tabs.
17035
17036Symbol substitution outside of preprocessor lines is obtained by using
17037the sequence
17038
17039@smallexample
17040$symbol
17041@end smallexample
17042
17043@noindent
17044anywhere within a source line, except in a comment or within a
17045string literal. The identifier
17046following the @code{$} must match one of the symbols defined in the symbol
17047definition file, and the result is to substitute the value of the
17048symbol in place of @code{$symbol} in the output file.
17049
17050Note that although the substitution of strings within a string literal
17051is not possible, it is possible to have a symbol whose defined value is
17052a string literal. So instead of setting XYZ to @code{hello} and writing:
17053
17054@smallexample
17055Header : String := "$XYZ";
17056@end smallexample
17057
17058@noindent
17059you should set XYZ to @code{"hello"} and write:
17060
17061@smallexample
17062Header : String := $XYZ;
17063@end smallexample
17064
17065@noindent
17066and then the substitution will occur as desired.
17067
17068@node The GNAT Library Browser gnatls
17069@chapter The GNAT Library Browser @code{gnatls}
17070@findex gnatls
17071@cindex Library browser
17072
17073@noindent
17074@code{gnatls} is a tool that outputs information about compiled
17075units. It gives the relationship between objects, unit names and source
17076files. It can also be used to check the source dependencies of a unit
17077as well as various characteristics.
17078
17079Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17080driver (see @ref{The GNAT Driver and Project Files}).
17081
17082@menu
17083* Running gnatls::
17084* Switches for gnatls::
17085* Examples of gnatls Usage::
17086@end menu
17087
17088@node Running gnatls
17089@section Running @code{gnatls}
17090
17091@noindent
17092The @code{gnatls} command has the form
17093
17094@smallexample
17095$ gnatls switches @var{object_or_ali_file}
17096@end smallexample
17097
17098@noindent
17099The main argument is the list of object or @file{ali} files
17100(@pxref{The Ada Library Information Files})
17101for which information is requested.
17102
17103In normal mode, without additional option, @code{gnatls} produces a
17104four-column listing. Each line represents information for a specific
17105object. The first column gives the full path of the object, the second
17106column gives the name of the principal unit in this object, the third
17107column gives the status of the source and the fourth column gives the
17108full path of the source representing this unit.
17109Here is a simple example of use:
17110
17111@smallexample
17112$ gnatls *.o
17113^./^[]^demo1.o            demo1            DIF demo1.adb
17114^./^[]^demo2.o            demo2             OK demo2.adb
17115^./^[]^hello.o            h1                OK hello.adb
17116^./^[]^instr-child.o      instr.child      MOK instr-child.adb
17117^./^[]^instr.o            instr             OK instr.adb
17118^./^[]^tef.o              tef              DIF tef.adb
17119^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
17120^./^[]^tgef.o             tgef             DIF tgef.adb
17121@end smallexample
17122
17123@noindent
17124The first line can be interpreted as follows: the main unit which is
17125contained in
17126object file @file{demo1.o} is demo1, whose main source is in
17127@file{demo1.adb}. Furthermore, the version of the source used for the
17128compilation of demo1 has been modified (DIF). Each source file has a status
17129qualifier which can be:
17130
17131@table @code
17132@item OK (unchanged)
17133The version of the source file used for the compilation of the
17134specified unit corresponds exactly to the actual source file.
17135
17136@item MOK (slightly modified)
17137The version of the source file used for the compilation of the
17138specified unit differs from the actual source file but not enough to
17139require recompilation. If you use gnatmake with the qualifier
17140@option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17141MOK will not be recompiled.
17142
17143@item DIF (modified)
17144No version of the source found on the path corresponds to the source
17145used to build this object.
17146
17147@item ??? (file not found)
17148No source file was found for this unit.
17149
17150@item HID (hidden,  unchanged version not first on PATH)
17151The version of the source that corresponds exactly to the source used
17152for compilation has been found on the path but it is hidden by another
17153version of the same source that has been modified.
17154
17155@end table
17156
17157@node Switches for gnatls
17158@section Switches for @code{gnatls}
17159
17160@noindent
17161@code{gnatls} recognizes the following switches:
17162
17163@table @option
17164@c !sort!
17165@cindex @option{--version} @command{gnatls}
17166Display Copyright and version, then exit disregarding all other options.
17167
17168@item --help
17169@cindex @option{--help} @command{gnatls}
17170If @option{--version} was not used, display usage, then exit disregarding
17171all other options.
17172
17173@item ^-a^/ALL_UNITS^
17174@cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17175Consider all units, including those of the predefined Ada library.
17176Especially useful with @option{^-d^/DEPENDENCIES^}.
17177
17178@item ^-d^/DEPENDENCIES^
17179@cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17180List sources from which specified units depend on.
17181
17182@item ^-h^/OUTPUT=OPTIONS^
17183@cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17184Output the list of options.
17185
17186@item ^-o^/OUTPUT=OBJECTS^
17187@cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17188Only output information about object files.
17189
17190@item ^-s^/OUTPUT=SOURCES^
17191@cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17192Only output information about source files.
17193
17194@item ^-u^/OUTPUT=UNITS^
17195@cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17196Only output information about compilation units.
17197
17198@item ^-files^/FILES^=@var{file}
17199@cindex @option{^-files^/FILES^} (@code{gnatls})
17200Take as arguments the files listed in text file @var{file}.
17201Text file @var{file} may contain empty lines that are ignored.
17202Each nonempty line should contain the name of an existing file.
17203Several such switches may be specified simultaneously.
17204
17205@item ^-aO^/OBJECT_SEARCH=^@var{dir}
17206@itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17207@itemx ^-I^/SEARCH=^@var{dir}
17208@itemx  ^-I-^/NOCURRENT_DIRECTORY^
17209@itemx -nostdinc
17210@cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17211@cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17212@cindex @option{^-I^/SEARCH^} (@code{gnatls})
17213@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17214Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17215flags (@pxref{Switches for gnatmake}).
17216
17217@item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
17218@cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
17219Add @var{dir} at the beginning of the project search dir.
17220
17221@item --RTS=@var{rts-path}
17222@cindex @option{--RTS} (@code{gnatls})
17223Specifies the default location of the runtime library. Same meaning as the
17224equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17225
17226@item ^-v^/OUTPUT=VERBOSE^
17227@cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17228Verbose mode. Output the complete source, object and project paths. Do not use
17229the default column layout but instead use long format giving as much as
17230information possible on each requested units, including special
17231characteristics such as:
17232
17233@table @code
17234@item  Preelaborable
17235The unit is preelaborable in the Ada sense.
17236
17237@item No_Elab_Code
17238No elaboration code has been produced by the compiler for this unit.
17239
17240@item Pure
17241The unit is pure in the Ada sense.
17242
17243@item Elaborate_Body
17244The unit contains a pragma Elaborate_Body.
17245
17246@item Remote_Types
17247The unit contains a pragma Remote_Types.
17248
17249@item Shared_Passive
17250The unit contains a pragma Shared_Passive.
17251
17252@item Predefined
17253This unit is part of the predefined environment and cannot be modified
17254by the user.
17255
17256@item Remote_Call_Interface
17257The unit contains a pragma Remote_Call_Interface.
17258
17259@end table
17260
17261@end table
17262
17263@node Examples of gnatls Usage
17264@section Example of @code{gnatls} Usage
17265@ifclear vms
17266
17267@noindent
17268Example of using the verbose switch. Note how the source and
17269object paths are affected by the -I switch.
17270
17271@smallexample
17272$ gnatls -v -I.. demo1.o
17273
17274GNATLS 5.03w (20041123-34)
17275Copyright 1997-2004 Free Software Foundation, Inc.
17276
17277Source Search Path:
17278   <Current_Directory>
17279   ../
17280   /home/comar/local/adainclude/
17281
17282Object Search Path:
17283   <Current_Directory>
17284   ../
17285   /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17286
17287Project Search Path:
17288   <Current_Directory>
17289   /home/comar/local/lib/gnat/
17290
17291./demo1.o
17292   Unit =>
17293     Name   => demo1
17294     Kind   => subprogram body
17295     Flags  => No_Elab_Code
17296     Source => demo1.adb    modified
17297@end smallexample
17298
17299@noindent
17300The following is an example of use of the dependency list.
17301Note the use of the -s switch
17302which gives a straight list of source files. This can be useful for
17303building specialized scripts.
17304
17305@smallexample
17306$ gnatls -d demo2.o
17307./demo2.o   demo2        OK demo2.adb
17308                         OK gen_list.ads
17309                         OK gen_list.adb
17310                         OK instr.ads
17311                         OK instr-child.ads
17312
17313$ gnatls -d -s -a demo1.o
17314demo1.adb
17315/home/comar/local/adainclude/ada.ads
17316/home/comar/local/adainclude/a-finali.ads
17317/home/comar/local/adainclude/a-filico.ads
17318/home/comar/local/adainclude/a-stream.ads
17319/home/comar/local/adainclude/a-tags.ads
17320gen_list.ads
17321gen_list.adb
17322/home/comar/local/adainclude/gnat.ads
17323/home/comar/local/adainclude/g-io.ads
17324instr.ads
17325/home/comar/local/adainclude/system.ads
17326/home/comar/local/adainclude/s-exctab.ads
17327/home/comar/local/adainclude/s-finimp.ads
17328/home/comar/local/adainclude/s-finroo.ads
17329/home/comar/local/adainclude/s-secsta.ads
17330/home/comar/local/adainclude/s-stalib.ads
17331/home/comar/local/adainclude/s-stoele.ads
17332/home/comar/local/adainclude/s-stratt.ads
17333/home/comar/local/adainclude/s-tasoli.ads
17334/home/comar/local/adainclude/s-unstyp.ads
17335/home/comar/local/adainclude/unchconv.ads
17336@end smallexample
17337@end ifclear
17338
17339@ifset vms
17340@smallexample
17341GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17342
17343GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17344GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17345GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17346GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17347GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17348demo1.adb
17349gen_list.ads
17350gen_list.adb
17351GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17352GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17353instr.ads
17354GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17355GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17356GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17357GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17358GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17359GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17360GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17361GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17362GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17363GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17364GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17365@end smallexample
17366@end ifset
17367
17368@node Cleaning Up with gnatclean
17369@chapter Cleaning Up with @code{gnatclean}
17370@findex gnatclean
17371@cindex Cleaning tool
17372
17373@noindent
17374@code{gnatclean} is a tool that allows the deletion of files produced by the
17375compiler, binder and linker, including ALI files, object files, tree files,
17376expanded source files, library files, interface copy source files, binder
17377generated files and executable files.
17378
17379@menu
17380* Running gnatclean::
17381* Switches for gnatclean::
17382@c * Examples of gnatclean Usage::
17383@end menu
17384
17385@node Running gnatclean
17386@section Running @code{gnatclean}
17387
17388@noindent
17389The @code{gnatclean} command has the form:
17390
17391@smallexample
17392$ gnatclean switches @var{names}
17393@end smallexample
17394
17395@noindent
17396@var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17397@code{^adb^ADB^} may be omitted. If a project file is specified using switch
17398@code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17399
17400@noindent
17401In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17402if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17403the linker. In informative-only mode, specified by switch
17404@code{^-n^/NODELETE^}, the list of files that would have been deleted in
17405normal mode is listed, but no file is actually deleted.
17406
17407@node Switches for gnatclean
17408@section Switches for @code{gnatclean}
17409
17410@noindent
17411@code{gnatclean} recognizes the following switches:
17412
17413@table @option
17414@c !sort!
17415@cindex @option{--version} @command{gnatclean}
17416Display Copyright and version, then exit disregarding all other options.
17417
17418@item --help
17419@cindex @option{--help} @command{gnatclean}
17420If @option{--version} was not used, display usage, then exit disregarding
17421all other options.
17422
17423@item ^--subdirs^/SUBDIRS^=subdir
17424Actual object directory of each project file is the subdirectory subdir of the
17425object directory specified or defaulted in the project file.
17426
17427@item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17428By default, shared library projects are not allowed to import static library
17429projects. When this switch is used on the command line, this restriction is
17430relaxed.
17431
17432@item ^-c^/COMPILER_FILES_ONLY^
17433@cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17434Only attempt to delete the files produced by the compiler, not those produced
17435by the binder or the linker. The files that are not to be deleted are library
17436files, interface copy files, binder generated files and executable files.
17437
17438@item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17439@cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17440Indicate that ALI and object files should normally be found in directory
17441@var{dir}.
17442
17443@item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17444@cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17445When using project files, if some errors or warnings are detected during
17446parsing and verbose mode is not in effect (no use of switch
17447^-v^/VERBOSE^), then error lines start with the full path name of the project
17448file, rather than its simple file name.
17449
17450@item ^-h^/HELP^
17451@cindex @option{^-h^/HELP^} (@code{gnatclean})
17452Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17453
17454@item ^-n^/NODELETE^
17455@cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17456Informative-only mode. Do not delete any files. Output the list of the files
17457that would have been deleted if this switch was not specified.
17458
17459@item ^-P^/PROJECT_FILE=^@var{project}
17460@cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17461Use project file @var{project}. Only one such switch can be used.
17462When cleaning a project file, the files produced by the compilation of the
17463immediate sources or inherited sources of the project files are to be
17464deleted. This is not depending on the presence or not of executable names
17465on the command line.
17466
17467@item ^-q^/QUIET^
17468@cindex @option{^-q^/QUIET^} (@code{gnatclean})
17469Quiet output. If there are no errors, do not output anything, except in
17470verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17471(switch ^-n^/NODELETE^).
17472
17473@item ^-r^/RECURSIVE^
17474@cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17475When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17476clean all imported and extended project files, recursively. If this switch
17477is not specified, only the files related to the main project file are to be
17478deleted. This switch has no effect if no project file is specified.
17479
17480@item ^-v^/VERBOSE^
17481@cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17482Verbose mode.
17483
17484@item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17485@cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17486Indicates the verbosity of the parsing of GNAT project files.
17487@xref{Switches Related to Project Files}.
17488
17489@item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17490@cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17491Indicates that external variable @var{name} has the value @var{value}.
17492The Project Manager will use this value for occurrences of
17493@code{external(name)} when parsing the project file.
17494@xref{Switches Related to Project Files}.
17495
17496@item ^-aO^/OBJECT_SEARCH=^@var{dir}
17497@cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17498When searching for ALI and object files, look in directory
17499@var{dir}.
17500
17501@item ^-I^/SEARCH=^@var{dir}
17502@cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17503Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17504
17505@item ^-I-^/NOCURRENT_DIRECTORY^
17506@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17507@cindex Source files, suppressing search
17508Do not look for ALI or object files in the directory
17509where @code{gnatclean} was invoked.
17510
17511@end table
17512
17513@c @node Examples of gnatclean Usage
17514@c @section Examples of @code{gnatclean} Usage
17515
17516@ifclear vms
17517@node GNAT and Libraries
17518@chapter GNAT and Libraries
17519@cindex Library, building, installing, using
17520
17521@noindent
17522This chapter describes how to build and use libraries with GNAT, and also shows
17523how to recompile the GNAT run-time library. You should be familiar with the
17524Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17525chapter.
17526
17527@menu
17528* Introduction to Libraries in GNAT::
17529* General Ada Libraries::
17530* Stand-alone Ada Libraries::
17531* Rebuilding the GNAT Run-Time Library::
17532@end menu
17533
17534@node Introduction to Libraries in GNAT
17535@section Introduction to Libraries in GNAT
17536
17537@noindent
17538A library is, conceptually, a collection of objects which does not have its
17539own main thread of execution, but rather provides certain services to the
17540applications that use it. A library can be either statically linked with the
17541application, in which case its code is directly included in the application,
17542or, on platforms that support it, be dynamically linked, in which case
17543its code is shared by all applications making use of this library.
17544
17545GNAT supports both types of libraries.
17546In the static case, the compiled code can be provided in different ways. The
17547simplest approach is to provide directly the set of objects resulting from
17548compilation of the library source files. Alternatively, you can group the
17549objects into an archive using whatever commands are provided by the operating
17550system. For the latter case, the objects are grouped into a shared library.
17551
17552In the GNAT environment, a library has three types of components:
17553@itemize @bullet
17554@item
17555Source files.
17556@item
17557@file{ALI} files.
17558@xref{The Ada Library Information Files}.
17559@item
17560Object files, an archive or a shared library.
17561@end itemize
17562
17563@noindent
17564A GNAT library may expose all its source files, which is useful for
17565documentation purposes. Alternatively, it may expose only the units needed by
17566an external user to make use of the library. That is to say, the specs
17567reflecting the library services along with all the units needed to compile
17568those specs, which can include generic bodies or any body implementing an
17569inlined routine. In the case of @emph{stand-alone libraries} those exposed
17570units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17571
17572All compilation units comprising an application, including those in a library,
17573need to be elaborated in an order partially defined by Ada's semantics. GNAT
17574computes the elaboration order from the @file{ALI} files and this is why they
17575constitute a mandatory part of GNAT libraries.
17576@emph{Stand-alone libraries} are the exception to this rule because a specific
17577library elaboration routine is produced independently of the application(s)
17578using the library.
17579
17580@node General Ada Libraries
17581@section General Ada Libraries
17582
17583@menu
17584* Building a library::
17585* Installing a library::
17586* Using a library::
17587@end menu
17588
17589@node Building a library
17590@subsection Building a library
17591
17592@noindent
17593The easiest way to build a library is to use the Project Manager,
17594which supports a special type of project called a @emph{Library Project}
17595(@pxref{Library Projects}).
17596
17597A project is considered a library project, when two project-level attributes
17598are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17599control different aspects of library configuration, additional optional
17600project-level attributes can be specified:
17601@table @code
17602@item Library_Kind
17603This attribute controls whether the library is to be static or dynamic
17604
17605@item Library_Version
17606This attribute specifies the library version; this value is used
17607during dynamic linking of shared libraries to determine if the currently
17608installed versions of the binaries are compatible.
17609
17610@item Library_Options
17611@item Library_GCC
17612These attributes specify additional low-level options to be used during
17613library generation, and redefine the actual application used to generate
17614library.
17615@end table
17616
17617@noindent
17618The GNAT Project Manager takes full care of the library maintenance task,
17619including recompilation of the source files for which objects do not exist
17620or are not up to date, assembly of the library archive, and installation of
17621the library (i.e., copying associated source, object and @file{ALI} files
17622to the specified location).
17623
17624Here is a simple library project file:
17625@smallexample @c ada
17626project My_Lib is
17627   for Source_Dirs use ("src1", "src2");
17628   for Object_Dir use "obj";
17629   for Library_Name use "mylib";
17630   for Library_Dir use "lib";
17631   for Library_Kind use "dynamic";
17632end My_lib;
17633@end smallexample
17634
17635@noindent
17636and the compilation command to build and install the library:
17637
17638@smallexample @c ada
17639  $ gnatmake -Pmy_lib
17640@end smallexample
17641
17642@noindent
17643It is not entirely trivial to perform manually all the steps required to
17644produce a library. We recommend that you use the GNAT Project Manager
17645for this task. In special cases where this is not desired, the necessary
17646steps are discussed below.
17647
17648There are various possibilities for compiling the units that make up the
17649library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17650with a conventional script. For simple libraries, it is also possible to create
17651a dummy main program which depends upon all the packages that comprise the
17652interface of the library. This dummy main program can then be given to
17653@command{gnatmake}, which will ensure that all necessary objects are built.
17654
17655After this task is accomplished, you should follow the standard procedure
17656of the underlying operating system to produce the static or shared library.
17657
17658Here is an example of such a dummy program:
17659@smallexample @c ada
17660@group
17661with My_Lib.Service1;
17662with My_Lib.Service2;
17663with My_Lib.Service3;
17664procedure My_Lib_Dummy is
17665begin
17666   null;
17667end;
17668@end group
17669@end smallexample
17670
17671@noindent
17672Here are the generic commands that will build an archive or a shared library.
17673
17674@smallexample
17675# compiling the library
17676$ gnatmake -c my_lib_dummy.adb
17677
17678# we don't need the dummy object itself
17679$ rm my_lib_dummy.o my_lib_dummy.ali
17680
17681# create an archive with the remaining objects
17682$ ar rc libmy_lib.a *.o
17683# some systems may require "ranlib" to be run as well
17684
17685# or create a shared library
17686$ gcc -shared -o libmy_lib.so *.o
17687# some systems may require the code to have been compiled with -fPIC
17688
17689# remove the object files that are now in the library
17690$ rm *.o
17691
17692# Make the ALI files read-only so that gnatmake will not try to
17693# regenerate the objects that are in the library
17694$ chmod -w *.ali
17695@end smallexample
17696
17697@noindent
17698Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17699or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17700be accessed by the directive @option{-l@var{xxx}} at link time.
17701
17702@node Installing a library
17703@subsection Installing a library
17704@cindex @code{ADA_PROJECT_PATH}
17705@cindex @code{GPR_PROJECT_PATH}
17706
17707@noindent
17708If you use project files, library installation is part of the library build
17709process (@pxref{Installing a library with project files}).
17710
17711When project files are not an option, it is also possible, but not recommended,
17712to install the library so that the sources needed to use the library are on the
17713Ada source path and the ALI files & libraries be on the Ada Object path (see
17714@ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17715administrator can place general-purpose libraries in the default compiler
17716paths, by specifying the libraries' location in the configuration files
17717@file{ada_source_path} and @file{ada_object_path}. These configuration files
17718must be located in the GNAT installation tree at the same place as the gcc spec
17719file. The location of the gcc spec file can be determined as follows:
17720@smallexample
17721$ gcc -v
17722@end smallexample
17723
17724@noindent
17725The configuration files mentioned above have a simple format: each line
17726must contain one unique directory name.
17727Those names are added to the corresponding path
17728in their order of appearance in the file. The names can be either absolute
17729or relative; in the latter case, they are relative to where theses files
17730are located.
17731
17732The files @file{ada_source_path} and @file{ada_object_path} might not be
17733present in a
17734GNAT installation, in which case, GNAT will look for its run-time library in
17735the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17736objects and @file{ALI} files). When the files exist, the compiler does not
17737look in @file{adainclude} and @file{adalib}, and thus the
17738@file{ada_source_path} file
17739must contain the location for the GNAT run-time sources (which can simply
17740be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17741contain the location for the GNAT run-time objects (which can simply
17742be @file{adalib}).
17743
17744You can also specify a new default path to the run-time library at compilation
17745time with the switch @option{--RTS=rts-path}. You can thus choose / change
17746the run-time library you want your program to be compiled with. This switch is
17747recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17748@command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17749
17750It is possible to install a library before or after the standard GNAT
17751library, by reordering the lines in the configuration files. In general, a
17752library must be installed before the GNAT library if it redefines
17753any part of it.
17754
17755@node Using a library
17756@subsection Using a library
17757
17758@noindent Once again, the project facility greatly simplifies the use of
17759libraries. In this context, using a library is just a matter of adding a
17760@code{with} clause in the user project. For instance, to make use of the
17761library @code{My_Lib} shown in examples in earlier sections, you can
17762write:
17763
17764@smallexample @c projectfile
17765with "my_lib";
17766project My_Proj is
17767  @dots{}
17768end My_Proj;
17769@end smallexample
17770
17771Even if you have a third-party, non-Ada library, you can still use GNAT's
17772Project Manager facility to provide a wrapper for it. For example, the
17773following project, when @code{with}ed by your main project, will link with the
17774third-party library @file{liba.a}:
17775
17776@smallexample @c projectfile
17777@group
17778project Liba is
17779   for Externally_Built use "true";
17780   for Source_Files use ();
17781   for Library_Dir use "lib";
17782   for Library_Name use "a";
17783   for Library_Kind use "static";
17784end Liba;
17785@end group
17786@end smallexample
17787This is an alternative to the use of @code{pragma Linker_Options}. It is
17788especially interesting in the context of systems with several interdependent
17789static libraries where finding a proper linker order is not easy and best be
17790left to the tools having visibility over project dependence information.
17791
17792@noindent
17793In order to use an Ada library manually, you need to make sure that this
17794library is on both your source and object path
17795(see @ref{Search Paths and the Run-Time Library (RTL)}
17796and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17797in an archive or a shared library, you need to specify the desired
17798library at link time.
17799
17800For example, you can use the library @file{mylib} installed in
17801@file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17802
17803@smallexample
17804$ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17805  -largs -lmy_lib
17806@end smallexample
17807
17808@noindent
17809This can be expressed more simply:
17810@smallexample
17811$ gnatmake my_appl
17812@end smallexample
17813@noindent
17814when the following conditions are met:
17815@itemize @bullet
17816@item
17817@file{/dir/my_lib_src} has been added by the user to the environment
17818variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17819@file{ada_source_path}
17820@item
17821@file{/dir/my_lib_obj} has been added by the user to the environment
17822variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17823@file{ada_object_path}
17824@item
17825a pragma @code{Linker_Options} has been added to one of the sources.
17826For example:
17827
17828@smallexample @c ada
17829pragma Linker_Options ("-lmy_lib");
17830@end smallexample
17831@end itemize
17832
17833@node Stand-alone Ada Libraries
17834@section Stand-alone Ada Libraries
17835@cindex Stand-alone library, building, using
17836
17837@menu
17838* Introduction to Stand-alone Libraries::
17839* Building a Stand-alone Library::
17840* Creating a Stand-alone Library to be used in a non-Ada context::
17841* Restrictions in Stand-alone Libraries::
17842@end menu
17843
17844@node Introduction to Stand-alone Libraries
17845@subsection Introduction to Stand-alone Libraries
17846
17847@noindent
17848A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17849necessary code to
17850elaborate the Ada units that are included in the library. In contrast with
17851an ordinary library, which consists of all sources, objects and @file{ALI}
17852files of the
17853library, a SAL may specify a restricted subset of compilation units
17854to serve as a library interface. In this case, the fully
17855self-sufficient set of files will normally consist of an objects
17856archive, the sources of interface units' specs, and the @file{ALI}
17857files of interface units.
17858If an interface spec contains a generic unit or an inlined subprogram,
17859the body's
17860source must also be provided; if the units that must be provided in the source
17861form depend on other units, the source and @file{ALI} files of those must
17862also be provided.
17863
17864The main purpose of a SAL is to minimize the recompilation overhead of client
17865applications when a new version of the library is installed. Specifically,
17866if the interface sources have not changed, client applications do not need to
17867be recompiled. If, furthermore, a SAL is provided in the shared form and its
17868version, controlled by @code{Library_Version} attribute, is not changed,
17869then the clients do not need to be relinked.
17870
17871SALs also allow the library providers to minimize the amount of library source
17872text exposed to the clients.  Such ``information hiding'' might be useful or
17873necessary for various reasons.
17874
17875Stand-alone libraries are also well suited to be used in an executable whose
17876main routine is not written in Ada.
17877
17878@node Building a Stand-alone Library
17879@subsection Building a Stand-alone Library
17880
17881@noindent
17882GNAT's Project facility provides a simple way of building and installing
17883stand-alone libraries; see @ref{Stand-alone Library Projects}.
17884To be a Stand-alone Library Project, in addition to the two attributes
17885that make a project a Library Project (@code{Library_Name} and
17886@code{Library_Dir}; see @ref{Library Projects}), the attribute
17887@code{Library_Interface} must be defined.  For example:
17888
17889@smallexample @c projectfile
17890@group
17891   for Library_Dir use "lib_dir";
17892   for Library_Name use "dummy";
17893   for Library_Interface use ("int1", "int1.child");
17894@end group
17895@end smallexample
17896
17897@noindent
17898Attribute @code{Library_Interface} has a non-empty string list value,
17899each string in the list designating a unit contained in an immediate source
17900of the project file.
17901
17902When a Stand-alone Library is built, first the binder is invoked to build
17903a package whose name depends on the library name
17904(@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17905This binder-generated package includes initialization and
17906finalization procedures whose
17907names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17908in the example
17909above). The object corresponding to this package is included in the library.
17910
17911You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17912calling of these procedures if a static SAL is built, or if a shared SAL
17913is built
17914with the project-level attribute @code{Library_Auto_Init} set to
17915@code{"false"}.
17916
17917For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17918(those that are listed in attribute @code{Library_Interface}) are copied to
17919the Library Directory. As a consequence, only the Interface Units may be
17920imported from Ada units outside of the library. If other units are imported,
17921the binding phase will fail.
17922
17923@noindent
17924It is also possible to build an encapsulated library where not only
17925the code to elaborate and finalize the library is embedded but also
17926ensuring that the library is linked only against static
17927libraries. So an encapsulated library only depends on system
17928libraries, all other code, including the GNAT runtime, is embedded. To
17929build an encapsulated library the attribute
17930@code{Library_Standalone} must be set to @code{encapsulated}:
17931
17932@smallexample @c projectfile
17933@group
17934   for Library_Dir use "lib_dir";
17935   for Library_Name use "dummy";
17936   for Library_Kind use "dynamic";
17937   for Library_Interface use ("int1", "int1.child");
17938   for Library_Standalone use "encapsulated";
17939@end group
17940@end smallexample
17941
17942@noindent
17943The default value for this attribute is @code{standard} in which case
17944a stand-alone library is built.
17945
17946The attribute @code{Library_Src_Dir} may be specified for a
17947Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17948single string value. Its value must be the path (absolute or relative to the
17949project directory) of an existing directory. This directory cannot be the
17950object directory or one of the source directories, but it can be the same as
17951the library directory. The sources of the Interface
17952Units of the library that are needed by an Ada client of the library will be
17953copied to the designated directory, called the Interface Copy directory.
17954These sources include the specs of the Interface Units, but they may also
17955include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17956are used, or when there is a generic unit in the spec. Before the sources
17957are copied to the Interface Copy directory, an attempt is made to delete all
17958files in the Interface Copy directory.
17959
17960Building stand-alone libraries by hand is somewhat tedious, but for those
17961occasions when it is necessary here are the steps that you need to perform:
17962@itemize @bullet
17963@item
17964Compile all library sources.
17965
17966@item
17967Invoke the binder with the switch @option{-n} (No Ada main program),
17968with all the @file{ALI} files of the interfaces, and
17969with the switch @option{-L} to give specific names to the @code{init}
17970and @code{final} procedures.  For example:
17971@smallexample
17972  gnatbind -n int1.ali int2.ali -Lsal1
17973@end smallexample
17974
17975@item
17976Compile the binder generated file:
17977@smallexample
17978  gcc -c b~int2.adb
17979@end smallexample
17980
17981@item
17982Link the dynamic library with all the necessary object files,
17983indicating to the linker the names of the @code{init} (and possibly
17984@code{final}) procedures for automatic initialization (and finalization).
17985The built library should be placed in a directory different from
17986the object directory.
17987
17988@item
17989Copy the @code{ALI} files of the interface to the library directory,
17990add in this copy an indication that it is an interface to a SAL
17991(i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17992with letter ``P'') and make the modified copy of the @file{ALI} file
17993read-only.
17994@end itemize
17995
17996@noindent
17997Using SALs is not different from using other libraries
17998(see @ref{Using a library}).
17999
18000@node Creating a Stand-alone Library to be used in a non-Ada context
18001@subsection Creating a Stand-alone Library to be used in a non-Ada context
18002
18003@noindent
18004It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18005a non-Ada context.
18006
18007The only extra step required is to ensure that library interface subprograms
18008are compatible with the main program, by means of @code{pragma Export}
18009or @code{pragma Convention}.
18010
18011Here is an example of simple library interface for use with C main program:
18012
18013@smallexample @c ada
18014package My_Package is
18015
18016   procedure Do_Something;
18017   pragma Export (C, Do_Something, "do_something");
18018
18019   procedure Do_Something_Else;
18020   pragma Export (C, Do_Something_Else, "do_something_else");
18021
18022end My_Package;
18023@end smallexample
18024
18025@noindent
18026On the foreign language side, you must provide a ``foreign'' view of the
18027library interface; remember that it should contain elaboration routines in
18028addition to interface subprograms.
18029
18030The example below shows the content of @code{mylib_interface.h} (note
18031that there is no rule for the naming of this file, any name can be used)
18032@smallexample
18033/* the library elaboration procedure */
18034extern void mylibinit (void);
18035
18036/* the library finalization procedure */
18037extern void mylibfinal (void);
18038
18039/* the interface exported by the library */
18040extern void do_something (void);
18041extern void do_something_else (void);
18042@end smallexample
18043
18044@noindent
18045Libraries built as explained above can be used from any program, provided
18046that the elaboration procedures (named @code{mylibinit} in the previous
18047example) are called before the library services are used. Any number of
18048libraries can be used simultaneously, as long as the elaboration
18049procedure of each library is called.
18050
18051Below is an example of a C program that uses the @code{mylib} library.
18052
18053@smallexample
18054#include "mylib_interface.h"
18055
18056int
18057main (void)
18058@{
18059   /* First, elaborate the library before using it */
18060   mylibinit ();
18061
18062   /* Main program, using the library exported entities */
18063   do_something ();
18064   do_something_else ();
18065
18066   /* Library finalization at the end of the program */
18067   mylibfinal ();
18068   return 0;
18069@}
18070@end smallexample
18071
18072@noindent
18073Note that invoking any library finalization procedure generated by
18074@code{gnatbind} shuts down the Ada run-time environment.
18075Consequently, the
18076finalization of all Ada libraries must be performed at the end of the program.
18077No call to these libraries or to the Ada run-time library should be made
18078after the finalization phase.
18079
18080@node Restrictions in Stand-alone Libraries
18081@subsection Restrictions in Stand-alone Libraries
18082
18083@noindent
18084The pragmas listed below should be used with caution inside libraries,
18085as they can create incompatibilities with other Ada libraries:
18086@itemize @bullet
18087@item pragma @code{Locking_Policy}
18088@item pragma @code{Partition_Elaboration_Policy}
18089@item pragma @code{Queuing_Policy}
18090@item pragma @code{Task_Dispatching_Policy}
18091@item pragma @code{Unreserve_All_Interrupts}
18092@end itemize
18093
18094@noindent
18095When using a library that contains such pragmas, the user must make sure
18096that all libraries use the same pragmas with the same values. Otherwise,
18097@code{Program_Error} will
18098be raised during the elaboration of the conflicting
18099libraries. The usage of these pragmas and its consequences for the user
18100should therefore be well documented.
18101
18102Similarly, the traceback in the exception occurrence mechanism should be
18103enabled or disabled in a consistent manner across all libraries.
18104Otherwise, Program_Error will be raised during the elaboration of the
18105conflicting libraries.
18106
18107If the @code{Version} or @code{Body_Version}
18108attributes are used inside a library, then you need to
18109perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18110libraries, so that version identifiers can be properly computed.
18111In practice these attributes are rarely used, so this is unlikely
18112to be a consideration.
18113
18114@node  Rebuilding the GNAT Run-Time Library
18115@section Rebuilding the GNAT Run-Time Library
18116@cindex GNAT Run-Time Library, rebuilding
18117@cindex Building the GNAT Run-Time Library
18118@cindex Rebuilding the GNAT Run-Time Library
18119@cindex Run-Time Library, rebuilding
18120
18121@noindent
18122It may be useful to recompile the GNAT library in various contexts, the
18123most important one being the use of partition-wide configuration pragmas
18124such as @code{Normalize_Scalars}. A special Makefile called
18125@code{Makefile.adalib} is provided to that effect and can be found in
18126the directory containing the GNAT library. The location of this
18127directory depends on the way the GNAT environment has been installed and can
18128be determined by means of the command:
18129
18130@smallexample
18131$ gnatls -v
18132@end smallexample
18133
18134@noindent
18135The last entry in the object search path usually contains the
18136gnat library. This Makefile contains its own documentation and in
18137particular the set of instructions needed to rebuild a new library and
18138to use it.
18139
18140@node Using the GNU make Utility
18141@chapter Using the GNU @code{make} Utility
18142@findex make
18143
18144@noindent
18145This chapter offers some examples of makefiles that solve specific
18146problems. It does not explain how to write a makefile (@pxref{Top,, GNU
18147make, make, GNU @code{make}}), nor does it try to replace the
18148@command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
18149
18150All the examples in this section are specific to the GNU version of
18151make. Although @command{make} is a standard utility, and the basic language
18152is the same, these examples use some advanced features found only in
18153@code{GNU make}.
18154
18155@menu
18156* Using gnatmake in a Makefile::
18157* Automatically Creating a List of Directories::
18158* Generating the Command Line Switches::
18159* Overcoming Command Line Length Limits::
18160@end menu
18161
18162@node Using gnatmake in a Makefile
18163@section Using gnatmake in a Makefile
18164@findex makefile
18165@cindex GNU make
18166
18167@noindent
18168Complex project organizations can be handled in a very powerful way by
18169using GNU make combined with gnatmake. For instance, here is a Makefile
18170which allows you to build each subsystem of a big project into a separate
18171shared library. Such a makefile allows you to significantly reduce the link
18172time of very big applications while maintaining full coherence at
18173each step of the build process.
18174
18175The list of dependencies are handled automatically by
18176@command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18177the appropriate directories.
18178
18179Note that you should also read the example on how to automatically
18180create the list of directories
18181(@pxref{Automatically Creating a List of Directories})
18182which might help you in case your project has a lot of subdirectories.
18183
18184@smallexample
18185@iftex
18186@leftskip=0cm
18187@font@heightrm=cmr8
18188@heightrm
18189@end iftex
18190## This Makefile is intended to be used with the following directory
18191## configuration:
18192##  - The sources are split into a series of csc (computer software components)
18193##    Each of these csc is put in its own directory.
18194##    Their name are referenced by the directory names.
18195##    They will be compiled into shared library (although this would also work
18196##    with static libraries
18197##  - The main program (and possibly other packages that do not belong to any
18198##    csc is put in the top level directory (where the Makefile is).
18199##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
18200##                    \_ second_csc (sources) __ lib (will contain the library)
18201##                    \_ @dots{}
18202## Although this Makefile is build for shared library, it is easy to modify
18203## to build partial link objects instead (modify the lines with -shared and
18204## gnatlink below)
18205##
18206## With this makefile, you can change any file in the system or add any new
18207## file, and everything will be recompiled correctly (only the relevant shared
18208## objects will be recompiled, and the main program will be re-linked).
18209
18210# The list of computer software component for your project. This might be
18211# generated automatically.
18212CSC_LIST=aa bb cc
18213
18214# Name of the main program (no extension)
18215MAIN=main
18216
18217# If we need to build objects with -fPIC, uncomment the following line
18218#NEED_FPIC=-fPIC
18219
18220# The following variable should give the directory containing libgnat.so
18221# You can get this directory through 'gnatls -v'. This is usually the last
18222# directory in the Object_Path.
18223GLIB=@dots{}
18224
18225# The directories for the libraries
18226# (This macro expands the list of CSC to the list of shared libraries, you
18227# could simply use the expanded form:
18228# LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18229LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18230
18231$@{MAIN@}: objects $@{LIB_DIR@}
18232    gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18233    gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18234
18235objects::
18236    # recompile the sources
18237    gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18238
18239# Note: In a future version of GNAT, the following commands will be simplified
18240# by a new tool, gnatmlib
18241$@{LIB_DIR@}:
18242    mkdir -p $@{dir $@@ @}
18243    cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18244    cd $@{dir $@@ @} && cp -f ../*.ali .
18245
18246# The dependencies for the modules
18247# Note that we have to force the expansion of *.o, since in some cases
18248# make won't be able to do it itself.
18249aa/lib/libaa.so: $@{wildcard aa/*.o@}
18250bb/lib/libbb.so: $@{wildcard bb/*.o@}
18251cc/lib/libcc.so: $@{wildcard cc/*.o@}
18252
18253# Make sure all of the shared libraries are in the path before starting the
18254# program
18255run::
18256    LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18257
18258clean::
18259    $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18260    $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18261    $@{RM@} $@{CSC_LIST:%=%/*.o@}
18262    $@{RM@} *.o *.ali $@{MAIN@}
18263@end smallexample
18264
18265@node Automatically Creating a List of Directories
18266@section Automatically Creating a List of Directories
18267
18268@noindent
18269In most makefiles, you will have to specify a list of directories, and
18270store it in a variable. For small projects, it is often easier to
18271specify each of them by hand, since you then have full control over what
18272is the proper order for these directories, which ones should be
18273included.
18274
18275However, in larger projects, which might involve hundreds of
18276subdirectories, it might be more convenient to generate this list
18277automatically.
18278
18279The example below presents two methods. The first one, although less
18280general, gives you more control over the list. It involves wildcard
18281characters, that are automatically expanded by @command{make}. Its
18282shortcoming is that you need to explicitly specify some of the
18283organization of your project, such as for instance the directory tree
18284depth, whether some directories are found in a separate tree, @enddots{}
18285
18286The second method is the most general one. It requires an external
18287program, called @command{find}, which is standard on all Unix systems. All
18288the directories found under a given root directory will be added to the
18289list.
18290
18291@smallexample
18292@iftex
18293@leftskip=0cm
18294@font@heightrm=cmr8
18295@heightrm
18296@end iftex
18297# The examples below are based on the following directory hierarchy:
18298# All the directories can contain any number of files
18299# ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
18300#                       ->  ab
18301#                       ->  ac
18302#                ->  b  ->  ba  ->  baa
18303#                       ->  bb
18304#                       ->  bc
18305# This Makefile creates a variable called DIRS, that can be reused any time
18306# you need this list (see the other examples in this section)
18307
18308# The root of your project's directory hierarchy
18309ROOT_DIRECTORY=.
18310
18311####
18312# First method: specify explicitly the list of directories
18313# This allows you to specify any subset of all the directories you need.
18314####
18315
18316DIRS := a/aa/ a/ab/ b/ba/
18317
18318####
18319# Second method: use wildcards
18320# Note that the argument(s) to wildcard below should end with a '/'.
18321# Since wildcards also return file names, we have to filter them out
18322# to avoid duplicate directory names.
18323# We thus use make's @code{dir} and @code{sort} functions.
18324# It sets DIRs to the following value (note that the directories aaa and baa
18325# are not given, unless you change the arguments to wildcard).
18326# DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18327####
18328
18329DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18330                    $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18331
18332####
18333# Third method: use an external program
18334# This command is much faster if run on local disks, avoiding NFS slowdowns.
18335# This is the most complete command: it sets DIRs to the following value:
18336# DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18337####
18338
18339DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18340
18341@end smallexample
18342
18343@node Generating the Command Line Switches
18344@section Generating the Command Line Switches
18345
18346@noindent
18347Once you have created the list of directories as explained in the
18348previous section (@pxref{Automatically Creating a List of Directories}),
18349you can easily generate the command line arguments to pass to gnatmake.
18350
18351For the sake of completeness, this example assumes that the source path
18352is not the same as the object path, and that you have two separate lists
18353of directories.
18354
18355@smallexample
18356# see "Automatically creating a list of directories" to create
18357# these variables
18358SOURCE_DIRS=
18359OBJECT_DIRS=
18360
18361GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18362GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18363
18364all:
18365        gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18366@end smallexample
18367
18368@node Overcoming Command Line Length Limits
18369@section Overcoming Command Line Length Limits
18370
18371@noindent
18372One problem that might be encountered on big projects is that many
18373operating systems limit the length of the command line. It is thus hard to give
18374gnatmake the list of source and object directories.
18375
18376This example shows how you can set up environment variables, which will
18377make @command{gnatmake} behave exactly as if the directories had been
18378specified on the command line, but have a much higher length limit (or
18379even none on most systems).
18380
18381It assumes that you have created a list of directories in your Makefile,
18382using one of the methods presented in
18383@ref{Automatically Creating a List of Directories}.
18384For the sake of completeness, we assume that the object
18385path (where the ALI files are found) is different from the sources patch.
18386
18387Note a small trick in the Makefile below: for efficiency reasons, we
18388create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18389expanded immediately by @code{make}. This way we overcome the standard
18390make behavior which is to expand the variables only when they are
18391actually used.
18392
18393On Windows, if you are using the standard Windows command shell, you must
18394replace colons with semicolons in the assignments to these variables.
18395
18396@smallexample
18397@iftex
18398@leftskip=0cm
18399@font@heightrm=cmr8
18400@heightrm
18401@end iftex
18402# In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18403# This is the same thing as putting the -I arguments on the command line.
18404# (the equivalent of using -aI on the command line would be to define
18405#  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18406# You can of course have different values for these variables.
18407#
18408# Note also that we need to keep the previous values of these variables, since
18409# they might have been set before running 'make' to specify where the GNAT
18410# library is installed.
18411
18412# see "Automatically creating a list of directories" to create these
18413# variables
18414SOURCE_DIRS=
18415OBJECT_DIRS=
18416
18417empty:=
18418space:=$@{empty@} $@{empty@}
18419SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18420OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18421ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18422ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18423export ADA_INCLUDE_PATH
18424export ADA_OBJECTS_PATH
18425
18426all:
18427        gnatmake main_unit
18428@end smallexample
18429@end ifclear
18430
18431@node Memory Management Issues
18432@chapter Memory Management Issues
18433
18434@noindent
18435This chapter describes some useful memory pools provided in the GNAT library
18436and in particular the GNAT Debug Pool facility, which can be used to detect
18437incorrect uses of access values (including ``dangling references'').
18438@ifclear vms
18439@ifclear FSFEDITION
18440It also describes the @command{gnatmem} tool, which can be used to track down
18441``memory leaks''.
18442@end ifclear
18443@end ifclear
18444
18445@menu
18446* Some Useful Memory Pools::
18447* The GNAT Debug Pool Facility::
18448@ifclear vms
18449@ifclear FSFEDITION
18450* The gnatmem Tool::
18451@end ifclear
18452@end ifclear
18453@end menu
18454
18455@node Some Useful Memory Pools
18456@section Some Useful Memory Pools
18457@findex Memory Pool
18458@cindex storage, pool
18459
18460@noindent
18461The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18462storage pool. Allocations use the standard system call @code{malloc} while
18463deallocations use the standard system call @code{free}. No reclamation is
18464performed when the pool goes out of scope. For performance reasons, the
18465standard default Ada allocators/deallocators do not use any explicit storage
18466pools but if they did, they could use this storage pool without any change in
18467behavior. That is why this storage pool is used  when the user
18468manages to make the default implicit allocator explicit as in this example:
18469@smallexample @c ada
18470   type T1 is access Something;
18471    -- no Storage pool is defined for T2
18472   type T2 is access Something_Else;
18473   for T2'Storage_Pool use T1'Storage_Pool;
18474   -- the above is equivalent to
18475   for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18476@end smallexample
18477
18478@noindent
18479The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18480pool. The allocation strategy is similar to @code{Pool_Local}'s
18481except that the all
18482storage allocated with this pool is reclaimed when the pool object goes out of
18483scope. This pool provides a explicit mechanism similar to the implicit one
18484provided by several Ada 83 compilers for allocations performed through a local
18485access type and whose purpose was to reclaim memory when exiting the
18486scope of a given local access. As an example, the following program does not
18487leak memory even though it does not perform explicit deallocation:
18488
18489@smallexample @c ada
18490with System.Pool_Local;
18491procedure Pooloc1 is
18492   procedure Internal is
18493      type A is access Integer;
18494      X : System.Pool_Local.Unbounded_Reclaim_Pool;
18495      for A'Storage_Pool use X;
18496      v : A;
18497   begin
18498      for I in  1 .. 50 loop
18499         v := new Integer;
18500      end loop;
18501   end Internal;
18502begin
18503   for I in  1 .. 100 loop
18504      Internal;
18505   end loop;
18506end Pooloc1;
18507@end smallexample
18508
18509@noindent
18510The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18511@code{Storage_Size} is specified for an access type.
18512The whole storage for the pool is
18513allocated at once, usually on the stack at the point where the access type is
18514elaborated. It is automatically reclaimed when exiting the scope where the
18515access type is defined. This package is not intended to be used directly by the
18516user and it is implicitly used for each such declaration:
18517
18518@smallexample @c ada
18519   type T1 is access Something;
18520   for T1'Storage_Size use 10_000;
18521@end smallexample
18522
18523@node The GNAT Debug Pool Facility
18524@section The GNAT Debug Pool Facility
18525@findex Debug Pool
18526@cindex storage, pool, memory corruption
18527
18528@noindent
18529The use of unchecked deallocation and unchecked conversion can easily
18530lead to incorrect memory references. The problems generated by such
18531references are usually difficult to tackle because the symptoms can be
18532very remote from the origin of the problem. In such cases, it is
18533very helpful to detect the problem as early as possible. This is the
18534purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18535
18536In order to use the GNAT specific debugging pool, the user must
18537associate a debug pool object with each of the access types that may be
18538related to suspected memory problems. See Ada Reference Manual 13.11.
18539@smallexample @c ada
18540type Ptr is access Some_Type;
18541Pool : GNAT.Debug_Pools.Debug_Pool;
18542for Ptr'Storage_Pool use Pool;
18543@end smallexample
18544
18545@noindent
18546@code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18547pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18548allow the user to redefine allocation and deallocation strategies. They
18549also provide a checkpoint for each dereference, through the use of
18550the primitive operation @code{Dereference} which is implicitly called at
18551each dereference of an access value.
18552
18553Once an access type has been associated with a debug pool, operations on
18554values of the type may raise four distinct exceptions,
18555which correspond to four potential kinds of memory corruption:
18556@itemize @bullet
18557@item
18558@code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18559@item
18560@code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18561@item
18562@code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18563@item
18564@code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18565@end itemize
18566
18567@noindent
18568For types associated with a Debug_Pool, dynamic allocation is performed using
18569the standard GNAT allocation routine. References to all allocated chunks of
18570memory are kept in an internal dictionary. Several deallocation strategies are
18571provided, whereupon the user can choose to release the memory to the system,
18572keep it allocated for further invalid access checks, or fill it with an easily
18573recognizable pattern for debug sessions. The memory pattern is the old IBM
18574hexadecimal convention: @code{16#DEADBEEF#}.
18575
18576See the documentation in the file g-debpoo.ads for more information on the
18577various strategies.
18578
18579Upon each dereference, a check is made that the access value denotes a
18580properly allocated memory location. Here is a complete example of use of
18581@code{Debug_Pools}, that includes typical instances of  memory corruption:
18582@smallexample @c ada
18583@iftex
18584@leftskip=0cm
18585@end iftex
18586with Gnat.Io; use Gnat.Io;
18587with Unchecked_Deallocation;
18588with Unchecked_Conversion;
18589with GNAT.Debug_Pools;
18590with System.Storage_Elements;
18591with Ada.Exceptions; use Ada.Exceptions;
18592procedure Debug_Pool_Test is
18593
18594   type T is access Integer;
18595   type U is access all T;
18596
18597   P : GNAT.Debug_Pools.Debug_Pool;
18598   for T'Storage_Pool use P;
18599
18600   procedure Free is new Unchecked_Deallocation (Integer, T);
18601   function UC is new Unchecked_Conversion (U, T);
18602   A, B : aliased T;
18603
18604   procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18605
18606begin
18607   Info (P);
18608   A := new Integer;
18609   B := new Integer;
18610   B := A;
18611   Info (P);
18612   Free (A);
18613   begin
18614      Put_Line (Integer'Image(B.all));
18615   exception
18616      when E : others => Put_Line ("raised: " & Exception_Name (E));
18617   end;
18618   begin
18619      Free (B);
18620   exception
18621      when E : others => Put_Line ("raised: " & Exception_Name (E));
18622   end;
18623   B := UC(A'Access);
18624   begin
18625      Put_Line (Integer'Image(B.all));
18626   exception
18627      when E : others => Put_Line ("raised: " & Exception_Name (E));
18628   end;
18629   begin
18630      Free (B);
18631   exception
18632      when E : others => Put_Line ("raised: " & Exception_Name (E));
18633   end;
18634   Info (P);
18635end Debug_Pool_Test;
18636@end smallexample
18637
18638@noindent
18639The debug pool mechanism provides the following precise diagnostics on the
18640execution of this erroneous program:
18641@smallexample
18642Debug Pool info:
18643  Total allocated bytes :  0
18644  Total deallocated bytes :  0
18645  Current Water Mark:  0
18646  High Water Mark:  0
18647
18648Debug Pool info:
18649  Total allocated bytes :  8
18650  Total deallocated bytes :  0
18651  Current Water Mark:  8
18652  High Water Mark:  8
18653
18654raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18655raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18656raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18657raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18658Debug Pool info:
18659  Total allocated bytes :  8
18660  Total deallocated bytes :  4
18661  Current Water Mark:  4
18662  High Water Mark:  8
18663@end smallexample
18664
18665@ifclear vms
18666@ifclear FSFEDITION
18667@node The gnatmem Tool
18668@section The @command{gnatmem} Tool
18669@findex gnatmem
18670
18671@noindent
18672The @code{gnatmem} utility monitors dynamic allocation and
18673deallocation activity in a program, and displays information about
18674incorrect deallocations and possible sources of memory leaks.
18675It is designed to work in association with a static runtime library
18676only and in this context provides three types of information:
18677@itemize @bullet
18678@item
18679General information concerning memory management, such as the total
18680number of allocations and deallocations, the amount of allocated
18681memory and the high water mark, i.e.@: the largest amount of allocated
18682memory in the course of program execution.
18683
18684@item
18685Backtraces for all incorrect deallocations, that is to say deallocations
18686which do not correspond to a valid allocation.
18687
18688@item
18689Information on each allocation that is potentially the origin of a memory
18690leak.
18691@end itemize
18692
18693@menu
18694* Running gnatmem::
18695* Switches for gnatmem::
18696* Example of gnatmem Usage::
18697@end menu
18698
18699@node Running gnatmem
18700@subsection Running @code{gnatmem}
18701
18702@noindent
18703@code{gnatmem} makes use of the output created by the special version of
18704allocation and deallocation routines that record call information. This
18705allows to obtain accurate dynamic memory usage history at a minimal cost to
18706the execution speed. Note however, that @code{gnatmem} is not supported on
18707all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18708Solaris and Windows NT/2000/XP (x86).
18709
18710@noindent
18711The @code{gnatmem} command has the form
18712
18713@smallexample
18714@c    $ gnatmem @ovar{switches} user_program
18715@c Expanding @ovar macro inline (explanation in macro def comments)
18716      $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18717@end smallexample
18718
18719@noindent
18720The program must have been linked with the instrumented version of the
18721allocation and deallocation routines. This is done by linking with the
18722@file{libgmem.a} library. For correct symbolic backtrace information,
18723the user program should be compiled with debugging options
18724(see @ref{Switches for gcc}). For example to build @file{my_program}:
18725
18726@smallexample
18727$ gnatmake -g my_program -largs -lgmem
18728@end smallexample
18729
18730@noindent
18731As library @file{libgmem.a} contains an alternate body for package
18732@code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18733when an executable is linked with library @file{libgmem.a}. It is then not
18734recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18735
18736@noindent
18737When @file{my_program} is executed, the file @file{gmem.out} is produced.
18738This file contains information about all allocations and deallocations
18739performed by the program. It is produced by the instrumented allocations and
18740deallocations routines and will be used by @code{gnatmem}.
18741
18742In order to produce symbolic backtrace information for allocations and
18743deallocations performed by the GNAT run-time library, you need to use a
18744version of that library that has been compiled with the @option{-g} switch
18745(see @ref{Rebuilding the GNAT Run-Time Library}).
18746
18747Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18748examine. If the location of @file{gmem.out} file was not explicitly supplied by
18749@option{-i} switch, gnatmem will assume that this file can be found in the
18750current directory. For example, after you have executed @file{my_program},
18751@file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18752
18753@smallexample
18754$ gnatmem my_program
18755@end smallexample
18756
18757@noindent
18758This will produce the output with the following format:
18759
18760*************** debut cc
18761@smallexample
18762$ gnatmem my_program
18763
18764Global information
18765------------------
18766   Total number of allocations        :  45
18767   Total number of deallocations      :   6
18768   Final Water Mark (non freed mem)   :  11.29 Kilobytes
18769   High Water Mark                    :  11.40 Kilobytes
18770
18771.
18772.
18773.
18774Allocation Root # 2
18775-------------------
18776 Number of non freed allocations    :  11
18777 Final Water Mark (non freed mem)   :   1.16 Kilobytes
18778 High Water Mark                    :   1.27 Kilobytes
18779 Backtrace                          :
18780   my_program.adb:23 my_program.alloc
18781.
18782.
18783.
18784@end smallexample
18785
18786The first block of output gives general information. In this case, the
18787Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18788Unchecked_Deallocation routine occurred.
18789
18790@noindent
18791Subsequent paragraphs display  information on all allocation roots.
18792An allocation root is a specific point in the execution of the program
18793that generates some dynamic allocation, such as a ``@code{@b{new}}''
18794construct. This root is represented by an execution backtrace (or subprogram
18795call stack). By default the backtrace depth for allocations roots is 1, so
18796that a root corresponds exactly to a source location. The backtrace can
18797be made deeper, to make the root more specific.
18798
18799@node Switches for gnatmem
18800@subsection Switches for @code{gnatmem}
18801
18802@noindent
18803@code{gnatmem} recognizes the following switches:
18804
18805@table @option
18806
18807@item -q
18808@cindex @option{-q} (@code{gnatmem})
18809Quiet. Gives the minimum output needed to identify the origin of the
18810memory leaks. Omits statistical information.
18811
18812@item @var{N}
18813@cindex @var{N} (@code{gnatmem})
18814N is an integer literal (usually between 1 and 10) which controls the
18815depth of the backtraces defining allocation root. The default value for
18816N is 1. The deeper the backtrace, the more precise the localization of
18817the root. Note that the total number of roots can depend on this
18818parameter. This parameter must be specified @emph{before} the name of the
18819executable to be analyzed, to avoid ambiguity.
18820
18821@item -b n
18822@cindex @option{-b} (@code{gnatmem})
18823This switch has the same effect as just depth parameter.
18824
18825@item -i @var{file}
18826@cindex @option{-i} (@code{gnatmem})
18827Do the @code{gnatmem} processing starting from @file{file}, rather than
18828@file{gmem.out} in the current directory.
18829
18830@item -m n
18831@cindex @option{-m} (@code{gnatmem})
18832This switch causes @code{gnatmem} to mask the allocation roots that have less
18833than n leaks. The default value is 1. Specifying the value of 0 will allow to
18834examine even the roots that didn't result in leaks.
18835
18836@item -s order
18837@cindex @option{-s} (@code{gnatmem})
18838This switch causes @code{gnatmem} to sort the allocation roots according to the
18839specified order of sort criteria, each identified by a single letter. The
18840currently supported criteria are @code{n, h, w} standing respectively for
18841number of unfreed allocations, high watermark, and final watermark
18842corresponding to a specific root. The default order is @code{nwh}.
18843
18844@end table
18845
18846@node Example of gnatmem Usage
18847@subsection Example of @code{gnatmem} Usage
18848
18849@noindent
18850The following example shows the use of @code{gnatmem}
18851on a simple memory-leaking program.
18852Suppose that we have the following Ada program:
18853
18854@smallexample @c ada
18855@group
18856@cartouche
18857with Unchecked_Deallocation;
18858procedure Test_Gm is
18859
18860   type T is array (1..1000) of Integer;
18861   type Ptr is access T;
18862   procedure Free is new Unchecked_Deallocation (T, Ptr);
18863   A : Ptr;
18864
18865   procedure My_Alloc is
18866   begin
18867      A := new T;
18868   end My_Alloc;
18869
18870   procedure My_DeAlloc is
18871      B : Ptr := A;
18872   begin
18873      Free (B);
18874   end My_DeAlloc;
18875
18876begin
18877   My_Alloc;
18878   for I in 1 .. 5 loop
18879      for J in I .. 5 loop
18880         My_Alloc;
18881      end loop;
18882      My_Dealloc;
18883   end loop;
18884end;
18885@end cartouche
18886@end group
18887@end smallexample
18888
18889@noindent
18890The program needs to be compiled with debugging option and linked with
18891@code{gmem} library:
18892
18893@smallexample
18894$ gnatmake -g test_gm -largs -lgmem
18895@end smallexample
18896
18897@noindent
18898Then we execute the program as usual:
18899
18900@smallexample
18901$ test_gm
18902@end smallexample
18903
18904@noindent
18905Then @code{gnatmem} is invoked simply with
18906@smallexample
18907$ gnatmem test_gm
18908@end smallexample
18909
18910@noindent
18911which produces the following output (result may vary on different platforms):
18912
18913@smallexample
18914Global information
18915------------------
18916   Total number of allocations        :  18
18917   Total number of deallocations      :   5
18918   Final Water Mark (non freed mem)   :  53.00 Kilobytes
18919   High Water Mark                    :  56.90 Kilobytes
18920
18921Allocation Root # 1
18922-------------------
18923 Number of non freed allocations    :  11
18924 Final Water Mark (non freed mem)   :  42.97 Kilobytes
18925 High Water Mark                    :  46.88 Kilobytes
18926 Backtrace                          :
18927   test_gm.adb:11 test_gm.my_alloc
18928
18929Allocation Root # 2
18930-------------------
18931 Number of non freed allocations    :   1
18932 Final Water Mark (non freed mem)   :  10.02 Kilobytes
18933 High Water Mark                    :  10.02 Kilobytes
18934 Backtrace                          :
18935   s-secsta.adb:81 system.secondary_stack.ss_init
18936
18937Allocation Root # 3
18938-------------------
18939 Number of non freed allocations    :   1
18940 Final Water Mark (non freed mem)   :  12 Bytes
18941 High Water Mark                    :  12 Bytes
18942 Backtrace                          :
18943   s-secsta.adb:181 system.secondary_stack.ss_init
18944@end smallexample
18945
18946@noindent
18947Note that the GNAT run time contains itself a certain number of
18948allocations that have no  corresponding deallocation,
18949as shown here for root #2 and root
18950#3. This is a normal behavior when the number of non-freed allocations
18951is one, it allocates dynamic data structures that the run time needs for
18952the complete lifetime of the program. Note also that there is only one
18953allocation root in the user program with a single line back trace:
18954test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18955program shows that 'My_Alloc' is called at 2 different points in the
18956source (line 21 and line 24). If those two allocation roots need to be
18957distinguished, the backtrace depth parameter can be used:
18958
18959@smallexample
18960$ gnatmem 3 test_gm
18961@end smallexample
18962
18963@noindent
18964which will give the following output:
18965
18966@smallexample
18967Global information
18968------------------
18969   Total number of allocations        :  18
18970   Total number of deallocations      :   5
18971   Final Water Mark (non freed mem)   :  53.00 Kilobytes
18972   High Water Mark                    :  56.90 Kilobytes
18973
18974Allocation Root # 1
18975-------------------
18976 Number of non freed allocations    :  10
18977 Final Water Mark (non freed mem)   :  39.06 Kilobytes
18978 High Water Mark                    :  42.97 Kilobytes
18979 Backtrace                          :
18980   test_gm.adb:11 test_gm.my_alloc
18981   test_gm.adb:24 test_gm
18982   b_test_gm.c:52 main
18983
18984Allocation Root # 2
18985-------------------
18986 Number of non freed allocations    :   1
18987 Final Water Mark (non freed mem)   :  10.02 Kilobytes
18988 High Water Mark                    :  10.02 Kilobytes
18989 Backtrace                          :
18990   s-secsta.adb:81  system.secondary_stack.ss_init
18991   s-secsta.adb:283 <system__secondary_stack___elabb>
18992   b_test_gm.c:33   adainit
18993
18994Allocation Root # 3
18995-------------------
18996 Number of non freed allocations    :   1
18997 Final Water Mark (non freed mem)   :   3.91 Kilobytes
18998 High Water Mark                    :   3.91 Kilobytes
18999 Backtrace                          :
19000   test_gm.adb:11 test_gm.my_alloc
19001   test_gm.adb:21 test_gm
19002   b_test_gm.c:52 main
19003
19004Allocation Root # 4
19005-------------------
19006 Number of non freed allocations    :   1
19007 Final Water Mark (non freed mem)   :  12 Bytes
19008 High Water Mark                    :  12 Bytes
19009 Backtrace                          :
19010   s-secsta.adb:181 system.secondary_stack.ss_init
19011   s-secsta.adb:283 <system__secondary_stack___elabb>
19012   b_test_gm.c:33   adainit
19013@end smallexample
19014
19015@noindent
19016The allocation root #1 of the first example has been split in 2 roots #1
19017and #3 thanks to the more precise associated backtrace.
19018@end ifclear
19019@end ifclear
19020
19021@node Stack Related Facilities
19022@chapter Stack Related Facilities
19023
19024@noindent
19025This chapter describes some useful tools associated with stack
19026checking and analysis. In
19027particular, it deals with dynamic and static stack usage measurements.
19028
19029@menu
19030* Stack Overflow Checking::
19031* Static Stack Usage Analysis::
19032* Dynamic Stack Usage Analysis::
19033@end menu
19034
19035@node Stack Overflow Checking
19036@section Stack Overflow Checking
19037@cindex Stack Overflow Checking
19038@cindex -fstack-check
19039
19040@noindent
19041For most operating systems, @command{gcc} does not perform stack overflow
19042checking by default. This means that if the main environment task or
19043some other task exceeds the available stack space, then unpredictable
19044behavior will occur. Most native systems offer some level of protection by
19045adding a guard page at the end of each task stack. This mechanism is usually
19046not enough for dealing properly with stack overflow situations because
19047a large local variable could ``jump'' above the guard page.
19048Furthermore, when the
19049guard page is hit, there may not be any space left on the stack for executing
19050the exception propagation code. Enabling stack checking avoids
19051such situations.
19052
19053To activate stack checking, compile all units with the gcc option
19054@option{-fstack-check}. For example:
19055
19056@smallexample
19057gcc -c -fstack-check package1.adb
19058@end smallexample
19059
19060@noindent
19061Units compiled with this option will generate extra instructions to check
19062that any use of the stack (for procedure calls or for declaring local
19063variables in declare blocks) does not exceed the available stack space.
19064If the space is exceeded, then a @code{Storage_Error} exception is raised.
19065
19066For declared tasks, the stack size is controlled by the size
19067given in an applicable @code{Storage_Size} pragma or by the value specified
19068at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19069the default size as defined in the GNAT runtime otherwise.
19070
19071For the environment task, the stack size depends on
19072system defaults and is unknown to the compiler. Stack checking
19073may still work correctly if a fixed
19074size stack is allocated, but this cannot be guaranteed.
19075@ifclear vms
19076To ensure that a clean exception is signalled for stack
19077overflow, set the environment variable
19078@env{GNAT_STACK_LIMIT} to indicate the maximum
19079stack area that can be used, as in:
19080@cindex GNAT_STACK_LIMIT
19081
19082@smallexample
19083SET GNAT_STACK_LIMIT 1600
19084@end smallexample
19085
19086@noindent
19087The limit is given in kilobytes, so the above declaration would
19088set the stack limit of the environment task to 1.6 megabytes.
19089Note that the only purpose of this usage is to limit the amount
19090of stack used by the environment task. If it is necessary to
19091increase the amount of stack for the environment task, then this
19092is an operating systems issue, and must be addressed with the
19093appropriate operating systems commands.
19094@end ifclear
19095@ifset vms
19096To have a fixed size stack in the environment task, the stack must be put
19097in the P0 address space and its size specified.  Use these switches to
19098create a p0 image:
19099
19100@smallexample
19101gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19102@end smallexample
19103
19104@noindent
19105The quotes are required to keep case.  The number after @samp{STACK=} is the
19106size of the environmental task stack in pagelets (512 bytes).  In this example
19107the stack size is about 2 megabytes.
19108
19109@noindent
19110A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19111be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
19112more details about the @option{/p0image} qualifier and the @option{stack}
19113option.
19114
19115@noindent
19116On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
19117@samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
19118stack in kilobytes.  For example:
19119
19120@smallexample
19121$ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
19122@end smallexample
19123@end ifset
19124
19125@node Static Stack Usage Analysis
19126@section Static Stack Usage Analysis
19127@cindex Static Stack Usage Analysis
19128@cindex -fstack-usage
19129
19130@noindent
19131A unit compiled with @option{-fstack-usage} will generate an extra file
19132that specifies
19133the maximum amount of stack used, on a per-function basis.
19134The file has the same
19135basename as the target object file with a @file{.su} extension.
19136Each line of this file is made up of three fields:
19137
19138@itemize
19139@item
19140The name of the function.
19141@item
19142A number of bytes.
19143@item
19144One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19145@end itemize
19146
19147The second field corresponds to the size of the known part of the function
19148frame.
19149
19150The qualifier @code{static} means that the function frame size
19151is purely static.
19152It usually means that all local variables have a static size.
19153In this case, the second field is a reliable measure of the function stack
19154utilization.
19155
19156The qualifier @code{dynamic} means that the function frame size is not static.
19157It happens mainly when some local variables have a dynamic size. When this
19158qualifier appears alone, the second field is not a reliable measure
19159of the function stack analysis. When it is qualified with  @code{bounded}, it
19160means that the second field is a reliable maximum of the function stack
19161utilization.
19162
19163A unit compiled with @option{-Wstack-usage} will issue a warning for each
19164subprogram whose stack usage might be larger than the specified amount of
19165bytes.  The wording is in keeping with the qualifier documented above.
19166
19167@node Dynamic Stack Usage Analysis
19168@section Dynamic Stack Usage Analysis
19169
19170@noindent
19171It is possible to measure the maximum amount of stack used by a task, by
19172adding a switch to @command{gnatbind}, as:
19173
19174@smallexample
19175$ gnatbind -u0 file
19176@end smallexample
19177
19178@noindent
19179With this option, at each task termination, its stack usage is  output on
19180@file{stderr}.
19181It is not always convenient to output the stack usage when the program
19182is still running. Hence, it is possible to delay this output until program
19183termination. for a given number of tasks specified as the argument of the
19184@option{-u} option. For instance:
19185
19186@smallexample
19187$ gnatbind -u100 file
19188@end smallexample
19189
19190@noindent
19191will buffer the stack usage information of the first 100 tasks to terminate and
19192output this info at program termination. Results are displayed in four
19193columns:
19194
19195@noindent
19196Index | Task Name | Stack Size | Stack Usage
19197
19198@noindent
19199where:
19200
19201@table @emph
19202@item Index
19203is a number associated with each task.
19204
19205@item Task Name
19206is the name of the task analyzed.
19207
19208@item Stack Size
19209is the maximum size for the stack.
19210
19211@item Stack Usage
19212is the measure done by the stack analyzer. In order to prevent overflow, the stack
19213is not entirely analyzed, and it's not possible to know exactly how
19214much has actually been used.
19215
19216@end table
19217
19218@noindent
19219The environment task stack, e.g., the stack that contains the main unit, is
19220only processed when the environment variable GNAT_STACK_LIMIT is set.
19221
19222@noindent
19223The package @code{GNAT.Task_Stack_Usage} provides facilities to get
19224stack usage reports at run-time. See its body for the details.
19225
19226@ifclear FSFEDITION
19227@c *********************************
19228@c *            GNATCHECK          *
19229@c *********************************
19230@node Verifying Properties with gnatcheck
19231@chapter Verifying Properties with @command{gnatcheck}
19232@findex gnatcheck
19233@cindex @command{gnatcheck}
19234
19235@noindent
19236The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19237of Ada source files according to a given set of semantic rules.
19238@cindex ASIS
19239
19240In order to check compliance with a given rule, @command{gnatcheck} has to
19241semantically analyze the Ada sources.
19242Therefore, checks can only be performed on
19243legal Ada units. Moreover, when a unit depends semantically upon units located
19244outside the current directory, the source search path has to be provided when
19245calling @command{gnatcheck}, either through a specified project file or
19246through @command{gnatcheck} switches.
19247
19248For full details, refer to @cite{GNATcheck Reference Manual} document.
19249@end ifclear
19250
19251@ifclear FSFEDITION
19252@c *********************************
19253@node Creating Sample Bodies with gnatstub
19254@chapter Creating Sample Bodies with @command{gnatstub}
19255@findex gnatstub
19256
19257@noindent
19258@command{gnatstub} creates body stubs, that is, empty but compilable bodies
19259for library unit declarations.
19260
19261Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
19262driver (see @ref{The GNAT Driver and Project Files}).
19263
19264To create a body stub, @command{gnatstub} has to compile the library
19265unit declaration. Therefore, bodies can be created only for legal
19266library units. Moreover, if a library unit depends semantically upon
19267units located outside the current directory, you have to provide
19268the source search path when calling @command{gnatstub}, see the description
19269of @command{gnatstub} switches below.
19270
19271By default, all the program unit body stubs generated by @code{gnatstub}
19272raise the predefined @code{Program_Error} exception, which will catch
19273accidental calls of generated stubs. This behavior can be changed with
19274option @option{^--no-exception^/NO_EXCEPTION^} (see below).
19275
19276@menu
19277* Running gnatstub::
19278* Switches for gnatstub::
19279@end menu
19280
19281@node Running gnatstub
19282@section Running @command{gnatstub}
19283
19284@noindent
19285@command{gnatstub} has a command-line interface of the form:
19286
19287@smallexample
19288@c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
19289@c Expanding @ovar macro inline (explanation in macro def comments)
19290$ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19291@end smallexample
19292
19293@noindent
19294where
19295@table @var
19296@item filename
19297is the name of the source file that contains a library unit declaration
19298for which a body must be created. The file name may contain the path
19299information.
19300The file name does not have to follow the GNAT file name conventions. If the
19301name
19302does not follow GNAT file naming conventions, the name of the body file must
19303be provided
19304explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19305If the file name follows the GNAT file naming
19306conventions and the name of the body file is not provided,
19307@command{gnatstub}
19308creates the name
19309of the body file from the argument file name by replacing the @file{.ads}
19310suffix
19311with the @file{.adb} suffix.
19312
19313@item directory
19314indicates the directory in which the body stub is to be placed (the default
19315is the
19316current directory)
19317
19318@item @samp{@var{gcc_switches}} is a list of switches for
19319@command{gcc}. They will be passed on to all compiler invocations made by
19320@command{gnatstub} to generate the ASIS trees. Here you can provide
19321@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19322use the @option{-gnatec} switch to set the configuration file,
19323use the @option{-gnat05} switch if sources should be compiled in
19324Ada 2005 mode etc.
19325
19326@item switches
19327is an optional sequence of switches as described in the next section
19328@end table
19329
19330@node Switches for gnatstub
19331@section Switches for @command{gnatstub}
19332
19333@table @option
19334@c !sort!
19335
19336@item --version
19337@cindex @option{--version} @command{gnatstub}
19338Display Copyright and version, then exit disregarding all other options.
19339
19340@item --help
19341@cindex @option{--help} @command{gnatstub}
19342Display usage, then exit disregarding all other options.
19343
19344@item -P @var{file}
19345@cindex @option{-P} @command{gnatstub}
19346Indicates the name of the project file that describes the set of sources
19347to be processed.
19348
19349@item -X@var{name}=@var{value}
19350@cindex @option{-X} @command{gnatstub}
19351Indicates that external variable @var{name} in the argument project
19352has the value @var{value}. Has no effect if no project is specified as
19353tool argument.
19354
19355@item ^-f^/FULL^
19356@cindex @option{^-f^/FULL^} (@command{gnatstub})
19357If the destination directory already contains a file with the name of the
19358body file
19359for the argument spec file, replace it with the generated body stub.
19360
19361@item ^-hs^/HEADER=SPEC^
19362@cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19363Put the comment header (i.e., all the comments preceding the
19364compilation unit) from the source of the library unit declaration
19365into the body stub.
19366
19367@item ^-hg^/HEADER=GENERAL^
19368@cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19369Put a sample comment header into the body stub.
19370
19371@item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19372@cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19373Use the content of the file as the comment header for a generated body stub.
19374
19375@ifclear vms
19376@item -IDIR
19377@cindex @option{-IDIR} (@command{gnatstub})
19378@itemx -I-
19379@cindex @option{-I-} (@command{gnatstub})
19380@end ifclear
19381@ifset vms
19382@item /NOCURRENT_DIRECTORY
19383@cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19384@end ifset
19385^These switches have ^This switch has^ the same meaning as in calls to
19386@command{gcc}.
19387^They define ^It defines ^ the source search path in the call to
19388@command{gcc} issued
19389by @command{gnatstub} to compile an argument source file.
19390
19391@item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19392@cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19393This switch has the same meaning as in calls to @command{gcc}.
19394It defines the additional configuration file to be passed to the call to
19395@command{gcc} issued
19396by @command{gnatstub} to compile an argument source file.
19397
19398@item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19399@cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19400(@var{n} is a non-negative integer). Set the maximum line length that is
19401allowed in a source file. The default is 79. The maximum value that can be
19402specified is 32767. Note that in the special case of configuration
19403pragma files, the maximum is always 32767 regardless of whether or
19404not this switch appears.
19405
19406@item ^-gnaty^/STYLE_CHECKS=^@var{n}
19407@cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19408(@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19409the generated body sample to @var{n}.
19410The default indentation is 3.
19411
19412@item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19413@cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19414Order local bodies alphabetically. (By default local bodies are ordered
19415in the same way as the corresponding local specs in the argument spec file.)
19416
19417@item ^-i^/INDENTATION=^@var{n}
19418@cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19419Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19420
19421@item ^-k^/TREE_FILE=SAVE^
19422@cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19423Do not remove the tree file (i.e., the snapshot of the compiler internal
19424structures used by @command{gnatstub}) after creating the body stub.
19425
19426@item ^-l^/LINE_LENGTH=^@var{n}
19427@cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19428Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19429
19430@item ^--no-exception^/NO_EXCEPTION^
19431@cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19432Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19433This is not always possible for function stubs.
19434
19435@item ^--no-local-header^/NO_LOCAL_HEADER^
19436@cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19437Do not place local comment header with unit name before body stub for a
19438unit.
19439
19440@item ^-o ^/BODY=^@var{body-name}
19441@cindex @option{^-o^/BODY^} (@command{gnatstub})
19442Body file name.  This should be set if the argument file name does not
19443follow
19444the GNAT file naming
19445conventions. If this switch is omitted the default name for the body will be
19446obtained
19447from the argument file name according to the GNAT file naming conventions.
19448
19449@item ^-q^/QUIET^
19450@cindex @option{^-q^/QUIET^} (@command{gnatstub})
19451Quiet mode: do not generate a confirmation when a body is
19452successfully created, and do not generate a message when a body is not
19453required for an
19454argument unit.
19455
19456@item ^-r^/TREE_FILE=REUSE^
19457@cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19458Reuse the tree file (if it exists) instead of creating it.  Instead of
19459creating the tree file for the library unit declaration, @command{gnatstub}
19460tries to find it in the current directory and use it for creating
19461a body. If the tree file is not found, no body is created. This option
19462also implies @option{^-k^/SAVE^}, whether or not
19463the latter is set explicitly.
19464
19465@item ^-t^/TREE_FILE=OVERWRITE^
19466@cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19467Overwrite the existing tree file.  If the current directory already
19468contains the file which, according to the GNAT file naming rules should
19469be considered as a tree file for the argument source file,
19470@command{gnatstub}
19471will refuse to create the tree file needed to create a sample body
19472unless this option is set.
19473
19474@item ^-v^/VERBOSE^
19475@cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19476Verbose mode: generate version information.
19477
19478@end table
19479@end ifclear
19480
19481@ifclear FSFEDITION
19482@c *********************************
19483@node Creating Unit Tests with gnattest
19484@chapter Creating Unit Tests with @command{gnattest}
19485@findex gnattest
19486
19487@noindent
19488@command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19489as well as a test driver infrastructure (harness). @command{gnattest} creates
19490a skeleton for each visible subprogram in the packages under consideration when
19491they do not exist already.
19492
19493In order to process source files from a project, @command{gnattest} has to
19494semantically analyze the sources. Therefore, test skeletons can only be
19495generated for legal Ada units. If a unit is dependent on other units,
19496those units should be among the source files of the project or of other projects
19497imported by this one.
19498
19499Generated skeletons and harnesses are based on the AUnit testing framework.
19500AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19501for Java or CppUnit for C++. While it is advised that gnattest users read
19502the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19503For correct operation of @command{gnattest}, AUnit should be installed and
19504aunit.gpr must be on the project path. This happens automatically when Aunit
19505is installed at its default location.
19506@menu
19507* Running gnattest::
19508* Switches for gnattest::
19509* Project Attributes for gnattest::
19510* Simple Example::
19511* Setting Up and Tearing Down the Testing Environment::
19512* Regenerating Tests::
19513* Default Test Behavior::
19514* Testing Primitive Operations of Tagged Types::
19515* Testing Inheritance::
19516* Tagged Types Substitutability Testing::
19517* Testing with Contracts::
19518* Additional Tests::
19519@ifclear vms
19520* Support for other platforms/run-times::
19521@end ifclear
19522* Current Limitations::
19523@end menu
19524
19525@node Running gnattest
19526@section Running @command{gnattest}
19527
19528@noindent
19529@command{gnattest} has a command-line interface of the form
19530
19531@smallexample
19532@c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19533@c Expanding @ovar macro inline (explanation in macro def comments)
19534$ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19535@end smallexample
19536
19537@noindent
19538where
19539@table @var
19540
19541@item -Pprojname
19542specifies the project defining the location of source files. When no
19543file names are provided on the command line, all sources in the project
19544are used as input. This switch is required.
19545
19546@item filename
19547is the name of the source file containing the library unit package declaration
19548for which a test package will be created. The file name may be given with a
19549path.
19550
19551@item @samp{@var{gcc_switches}}
19552is a list of switches for
19553@command{gcc}. These switches will be passed on to all compiler invocations
19554made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19555@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19556use the @option{-gnatec} switch to set the configuration file,
19557use the @option{-gnat05} switch if sources should be compiled in
19558Ada 2005 mode, etc.
19559
19560@item switches
19561is an optional sequence of switches as described in the next section.
19562
19563@end table
19564
19565@command{gnattest} results can be found in two different places.
19566
19567@itemize @bullet
19568@item automatic harness:
19569the harness code, which is located by default in "gnattest/harness" directory
19570that is created in the object directory of corresponding project file. All of
19571this code is generated completely automatically and can be destroyed and
19572regenerated at will. It is not recommended to modify this code manually, since
19573it could easily be overridden by mistake. The entry point in the harness code is
19574the project file named @command{test_driver.gpr}. Tests can be compiled and run
19575using a command such as:
19576
19577@smallexample
19578gnatmake -P<harness-dir>/test_driver
19579test_runner
19580@end smallexample
19581
19582Note that you might need to specify the necessary values of scenario variables
19583when you are not using the AUnit defaults.
19584
19585@item actual unit test skeletons:
19586a test skeleton for each visible subprogram is created in a separate file, if it
19587doesn't exist already. By default, those separate test files are located in a
19588"gnattest/tests" directory that is created in the object directory of
19589corresponding project file. For example, if a source file my_unit.ads in
19590directory src contains a visible subprogram Proc, then the corresponding unit
19591test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19592<code> is a signature encoding used to differentiate test names in case of
19593overloading.
19594
19595Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19596this will cause a name conflict with the generated test package.
19597@end itemize
19598
19599@node Switches for gnattest
19600@section Switches for @command{gnattest}
19601
19602@table @option
19603@c !sort!
19604
19605@item --harness-only
19606@cindex @option{--harness-only} (@command{gnattest})
19607When this option is given, @command{gnattest} creates a harness for all
19608sources, treating them as test packages.
19609
19610@item --additional-tests=@var{projname}
19611@cindex @option{--additional-tests} (@command{gnattest})
19612Sources described in @var{projname} are considered potential additional
19613manual tests to be added to the test suite.
19614
19615@item -r
19616@cindex @option{-r} (@command{gnattest})
19617Recursively consider all sources from all projects.
19618
19619@item -X@var{name=value}
19620@cindex @option{-X} (@command{gnattest})
19621Indicate that external variable @var{name} has the value @var{value}.
19622
19623@item -q
19624@cindex @option{-q} (@command{gnattest})
19625Suppresses noncritical output messages.
19626
19627@item -v
19628@cindex @option{-v} (@command{gnattest})
19629Verbose mode: generates version information.
19630
19631@item --validate-type-extensions
19632@cindex @option{--validate-type-extensions} (@command{gnattest})
19633Enables substitution check: run all tests from all parents in order
19634to check substitutability.
19635
19636@item --skeleton-default=@var{val}
19637@cindex @option{--skeleton-default} (@command{gnattest})
19638Specifies the default behavior of generated skeletons. @var{val} can be either
19639"fail" or "pass", "fail" being the default.
19640
19641@item --passed-tests=@var{val}
19642@cindex @option{--skeleton-default} (@command{gnattest})
19643Specifies whether or not passed tests should be shown. @var{val} can be either
19644"show" or "hide", "show" being the default.
19645
19646
19647@item --tests-root=@var{dirname}
19648@cindex @option{--tests-root} (@command{gnattest})
19649The directory hierarchy of tested sources is recreated in the @var{dirname}
19650directory, and test packages are placed in corresponding directories.
19651If the @var{dirname} is a relative path, it is considered relative to the object
19652directory of the project file. When all sources from all projects are taken
19653recursively from all projects, directory hierarchies of tested sources are
19654recreated for each project in their object directories and test packages are
19655placed accordingly.
19656
19657@item --subdir=@var{dirname}
19658@cindex @option{--subdir} (@command{gnattest})
19659Test packages are placed in subdirectories.
19660
19661@item --tests-dir=@var{dirname}
19662@cindex @option{--tests-dir} (@command{gnattest})
19663All test packages are placed in the @var{dirname} directory.
19664If the @var{dirname} is a relative path, it is considered relative to the object
19665directory of the project file. When all sources from all projects are taken
19666recursively from all projects, @var{dirname} directories are created for each
19667project in their object directories and test packages are placed accordingly.
19668
19669@item --harness-dir=@var{dirname}
19670@cindex @option{--harness-dir} (@command{gnattest})
19671specifies the directory that will hold the harness packages and project file
19672for the test driver. If the @var{dirname} is a relative path, it is considered
19673relative to the object directory of the project file.
19674
19675@item --separates
19676@cindex @option{--separates} (@command{gnattest})
19677Bodies of all test routines are generated as separates. Note that this mode is
19678kept for compatibility reasons only and it is not advised to use it due to
19679possible problems with hash in names of test skeletons when using an
19680inconsistent casing. Separate test skeletons can be incorporated to monolith
19681test package with improved hash being used by using @option{--transition}
19682switch.
19683
19684
19685@item --transition
19686@cindex @option{--transition} (@command{gnattest})
19687This allows transition from separate test routines to monolith test packages.
19688All matching test routines are overwritten with contents of corresponding
19689separates. Note that if separate test routines had any manually added with
19690clauses they will be moved to the test package body as is and have to be moved
19691by hand.
19692
19693@end table
19694
19695@option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19696mutually exclusive.
19697
19698@node Project Attributes for gnattest
19699@section Project Attributes for @command{gnattest}
19700
19701@noindent
19702
19703Most of the command-line options can also be passed to the tool by adding
19704special attributes to the project file. Those attributes should be put in
19705package gnattest. Here is the list of attributes:
19706
19707@itemize @bullet
19708
19709@item Tests_Root
19710is used to select the same output mode as with the --tests-root option.
19711This attribute cannot be used together with Subdir or Tests_Dir.
19712
19713@item Subdir
19714is used to select the same output mode as with the --subdir option.
19715This attribute cannot be used together with Tests_Root or Tests_Dir.
19716
19717@item Tests_Dir
19718is used to select the same output mode as with the --tests-dir option.
19719This attribute cannot be used together with Subdir or Tests_Root.
19720
19721@item Harness_Dir
19722is used to specify the directory in which to place harness packages and project
19723file for the test driver, otherwise specified by --harness-dir.
19724
19725@item Additional_Tests
19726is used to specify the project file, otherwise given by
19727--additional-tests switch.
19728
19729@item Skeletons_Default
19730is used to specify the default behaviour of test skeletons, otherwise
19731specified by --skeleton-default option. The value of this attribute
19732should be either "pass" or "fail".
19733
19734@end itemize
19735
19736Each of those attributes can be overridden from the command line if needed.
19737Other @command{gnattest} switches can also be passed via the project
19738file as an attribute list called GNATtest_Switches.
19739
19740@node Simple Example
19741@section Simple Example
19742
19743@noindent
19744
19745Let's take a very simple example using the first @command{gnattest} example
19746located in:
19747
19748@smallexample
19749<install_prefix>/share/examples/gnattest/simple
19750@end smallexample
19751
19752This project contains a simple package containing one subprogram. By running gnattest:
19753
19754@smallexample
19755$ gnattest --harness-dir=driver -Psimple.gpr
19756@end smallexample
19757
19758a test driver is created in directory "driver". It can be compiled and run:
19759
19760@smallexample
19761$ cd obj/driver
19762$ gnatmake -Ptest_driver
19763$ test_runner
19764@end smallexample
19765
19766One failed test with diagnosis "test not implemented" is reported.
19767Since no special output option was specified, the test package Simple.Tests
19768is located in:
19769
19770@smallexample
19771<install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19772@end smallexample
19773
19774For each package containing visible subprograms, a child test package is
19775generated. It contains one test routine per tested subprogram. Each
19776declaration of a test subprogram has a comment specifying which tested
19777subprogram it corresponds to. Bodies of test routines are placed in test package
19778bodies and are surrounded by special comment sections. Those comment sections
19779should not be removed or modified in order for gnattest to be able to regenerate
19780test packages and keep already written tests in place.
19781The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19782a single statement: a call to procedure Assert. It has two arguments:
19783the Boolean expression we want to check and the diagnosis message to display if
19784the condition is false.
19785
19786That is where actual testing code should be written after a proper setup.
19787An actual check can be performed by replacing the Assert call with:
19788
19789@smallexample @c ada
19790Assert (Inc (1) = 2, "wrong incrementation");
19791@end smallexample
19792
19793After recompiling and running the test driver, one successfully passed test
19794is reported.
19795
19796@node Setting Up and Tearing Down the Testing Environment
19797@section Setting Up and Tearing Down the Testing Environment
19798
19799@noindent
19800
19801Besides test routines themselves, each test package has a parent package
19802Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19803overwritten by the tool. Set_Up is called before each test routine of the
19804package and Tear_Down is called after each test routine. Those two procedures
19805can be used to perform necessary initialization and finalization,
19806memory allocation, etc. Test type declared in Test_Data package is parent type
19807for the test type of test package and can have user-defined components whose
19808values can be set by Set_Up routine and used in test routines afterwards.
19809
19810@node Regenerating Tests
19811@section Regenerating Tests
19812
19813@noindent
19814
19815Bodies of test routines and test_data packages are never overridden after they
19816have been created once. As long as the name of the subprogram, full expanded Ada
19817names, and the order of its parameters is the same, and comment sections are
19818intact the old test routine will fit in its place and no test skeleton will be
19819generated for the subprogram.
19820
19821This can be demonstrated with the previous example. By uncommenting declaration
19822and body of function Dec in simple.ads and simple.adb, running
19823@command{gnattest} on the project, and then running the test driver:
19824
19825@smallexample
19826gnattest --harness-dir=driver -Psimple.gpr
19827cd obj/driver
19828gnatmake -Ptest_driver
19829test_runner
19830@end smallexample
19831
19832the old test is not replaced with a stub, nor is it lost, but a new test
19833skeleton is created for function Dec.
19834
19835The only way of regenerating tests skeletons is to remove the previously created
19836tests together with corresponding comment sections.
19837
19838@node Default Test Behavior
19839@section Default Test Behavior
19840
19841@noindent
19842
19843The generated test driver can treat unimplemented tests in two ways:
19844either count them all as failed (this is useful to see which tests are still
19845left to implement) or as passed (to sort out unimplemented ones from those
19846actually failing).
19847
19848The test driver accepts a switch to specify this behavior:
19849--skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19850@command{gnattest}).
19851
19852The default behavior of the test driver is set with the same switch
19853as passed to gnattest when generating the test driver.
19854
19855Passing it to the driver generated on the first example:
19856
19857@smallexample
19858test_runner --skeleton-default=pass
19859@end smallexample
19860
19861makes both tests pass, even the unimplemented one.
19862
19863@node Testing Primitive Operations of Tagged Types
19864@section Testing Primitive Operations of Tagged Types
19865
19866@noindent
19867
19868Creation of test skeletons for primitive operations of tagged types entails
19869a number of features. Test routines for all primitives of a given tagged type
19870are placed in a separate child package named according to the tagged type. For
19871example, if you have tagged type T in package P, all tests for primitives
19872of T will be in P.T_Test_Data.T_Tests.
19873
19874Consider running gnattest on the second example (note: actual tests for this
19875example already exist, so there's no need to worry if the tool reports that
19876no new stubs were generated):
19877
19878@smallexample
19879cd <install_prefix>/share/examples/gnattest/tagged_rec
19880gnattest --harness-dir=driver -Ptagged_rec.gpr
19881@end smallexample
19882
19883Taking a closer look at the test type declared in the test package
19884Speed1.Controller_Test_Data is necessary. It is declared in:
19885
19886@smallexample
19887<install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19888@end smallexample
19889
19890Test types are direct or indirect descendants of
19891AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19892subprograms, the user doesn't need to be concerned with them. However,
19893when generating test packages for primitive operations, there are some things
19894the user needs to know.
19895
19896Type Test_Controller has components that allow assignment of various
19897derivations of type Controller. And if you look at the specification of
19898package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19899actually derives from Test_Controller rather than AUnit type Test_Fixture.
19900Thus, test types mirror the hierarchy of tested types.
19901
19902The Set_Up procedure of Test_Data package corresponding to a test package
19903of primitive operations of type T assigns to Fixture a reference to an
19904object of that exact type T. Notice, however, that if the tagged type has
19905discriminants, the Set_Up only has a commented template for setting
19906up the fixture, since filling the discriminant with actual value is up
19907to the user.
19908
19909The knowledge of the structure of test types allows additional testing
19910without additional effort. Those possibilities are described below.
19911
19912@node Testing Inheritance
19913@section Testing Inheritance
19914
19915@noindent
19916
19917Since the test type hierarchy mimics the hierarchy of tested types, the
19918inheritance of tests takes place. An example of such inheritance can be
19919seen by running the test driver generated for the second example. As previously
19920mentioned, actual tests are already written for this example.
19921
19922@smallexample
19923cd obj/driver
19924gnatmake -Ptest_driver
19925test_runner
19926@end smallexample
19927
19928There are 6 passed tests while there are only 5 testable subprograms. The test
19929routine for function Speed has been inherited and run against objects of the
19930derived type.
19931
19932@node Tagged Types Substitutability Testing
19933@section Tagged Types Substitutability Testing
19934
19935@noindent
19936
19937Tagged Types Substitutability Testing is a way of verifying the global type
19938consistency by testing. Global type consistency is a principle stating that if
19939S is a subtype of T (in Ada, S is a derived type of tagged type T),
19940then objects of type T may be replaced with objects of type S (that is,
19941objects of type S may be substituted for objects of type T), without
19942altering any of the desirable properties of the program. When the properties
19943of the program are expressed in the form of subprogram preconditions and
19944postconditions (let's call them pre and post), the principle is formulated as
19945relations between the pre and post of primitive operations and the pre and post
19946of their derived operations. The pre of a derived operation should not be
19947stronger than the original pre, and the post of the derived operation should
19948not be weaker than the original post. Those relations ensure that verifying if
19949a dispatching call is safe can be done just by using the pre and post of the
19950root operation.
19951
19952Verifying global type consistency by testing consists of running all the unit
19953tests associated with the primitives of a given tagged type with objects of its
19954derived types.
19955
19956In the example used in the previous section, there was clearly a violation of
19957type consistency. The overriding primitive Adjust_Speed in package Speed2
19958removes the functionality of the overridden primitive and thus doesn't respect
19959the consistency principle.
19960Gnattest has a special option to run overridden parent tests against objects
19961of the type which have overriding primitives:
19962
19963@smallexample
19964gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19965cd obj/driver
19966gnatmake -Ptest_driver
19967test_runner
19968@end smallexample
19969
19970While all the tests pass by themselves, the parent test for Adjust_Speed fails
19971against objects of the derived type.
19972
19973Non-overridden tests are already inherited for derived test types, so the
19974--validate-type-extensions enables the application of overriden tests to objects
19975of derived types.
19976
19977@node Testing with Contracts
19978@section Testing with Contracts
19979
19980@noindent
19981
19982@command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19983as well as corresponding aspects.
19984Test routines are generated, one per each Test_Case associated with a tested
19985subprogram. Those test routines have special wrappers for tested functions
19986that have composition of pre- and postcondition of the subprogram with
19987"requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19988either count for Nominal mode or do not count for Robustness mode).
19989
19990The third example demonstrates how this works:
19991
19992@smallexample
19993cd <install_prefix>/share/examples/gnattest/contracts
19994gnattest --harness-dir=driver -Pcontracts.gpr
19995@end smallexample
19996
19997Putting actual checks within the range of the contract does not cause any
19998error reports. For example, for the test routine which corresponds to
19999test case 1:
20000
20001@smallexample @c ada
20002Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
20003@end smallexample
20004
20005and for the test routine corresponding to test case 2:
20006
20007@smallexample @c ada
20008Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
20009@end smallexample
20010
20011are acceptable:
20012
20013@smallexample
20014cd obj/driver
20015gnatmake -Ptest_driver
20016test_runner
20017@end smallexample
20018
20019However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
20020a precondition violation for test case one. Also, by using any otherwise
20021correct but positive pair of numbers in the second test routine, you can also
20022get a precondition violation. Postconditions are checked and reported
20023the same way.
20024
20025@node Additional Tests
20026@section Additional Tests
20027
20028@noindent
20029@command{gnattest} can add user-written tests to the main suite of the test
20030driver. @command{gnattest} traverses the given packages and searches for test
20031routines. All procedures with a single in out parameter of a type which is
20032derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
20033specifications are added to the suites and are then executed by the test driver.
20034(Set_Up and Tear_Down are filtered out.)
20035
20036An example illustrates two ways of creating test harnesses for user-written
20037tests. Directory additional_tests contains an AUnit-based test driver written
20038by hand.
20039
20040@smallexample
20041<install_prefix>/share/examples/gnattest/additional_tests/
20042@end smallexample
20043
20044To create a test driver for already-written tests, use the --harness-only
20045option:
20046
20047@smallexample
20048gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
20049  --harness-only
20050gnatmake -Pharness_only/test_driver.gpr
20051harness_only/test_runner
20052@end smallexample
20053
20054Additional tests can also be executed together with generated tests:
20055
20056@smallexample
20057gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
20058  --harness-dir=mixing
20059gnatmake -Pmixing/test_driver.gpr
20060mixing/test_runner
20061@end smallexample
20062
20063@ifclear vms
20064@node Support for other platforms/run-times
20065@section Support for other platforms/run-times
20066
20067@noindent
20068@command{gnattest} can be used to generate the test harness for platforms
20069and run-time libraries others than the default native target with the
20070default full run-time. For example, when using a limited run-time library
20071such as Zero FootPrint (ZFP), a simplified harness is generated.
20072
20073Two variables are used to tell the underlying AUnit framework how to generate
20074the test harness: @code{PLATFORM}, which identifies the target, and
20075@code{RUNTIME}, used to determine the run-time library for which the harness
20076is generated. Corresponding prefix should also be used when calling
20077@command{gnattest} for non-native targets. For example, the following options
20078are used to generate the AUnit test harness for a PowerPC ELF target using
20079the ZFP run-time library:
20080
20081@smallexample
20082powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
20083@end smallexample
20084@end ifclear
20085
20086@node Current Limitations
20087@section Current Limitations
20088
20089@noindent
20090
20091The tool currently does not support following features:
20092
20093@itemize @bullet
20094@item generic tests for generic packages and package instantiations
20095@item tests for protected subprograms and entries
20096
20097@end itemize
20098@end ifclear
20099
20100
20101@c *********************************
20102@node Performing Dimensionality Analysis in GNAT
20103@chapter Performing Dimensionality Analysis in GNAT
20104@noindent
20105The GNAT compiler now supports dimensionality checking. The user can
20106specify physical units for objects, and the compiler will verify that uses
20107of these objects are compatible with their dimensions, in a fashion that is
20108familiar to engineering practice. The dimensions of algebraic expressions
20109(including powers with static exponents) are computed from their consistuents.
20110
20111This feature depends on Ada 2012 aspect specifications, and is available from
20112version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
20113you to define a system of units; the aspect Dimension then allows the user
20114to declare dimensioned quantities within a given system.
20115
20116The major advantage of this model is that it does not require the declaration of
20117multiple operators for all possible combinations of types: it is only necessary
20118to use the proper subtypes in object declarations.
20119
20120The simplest way to impose dimensionality checking on a computation is to make
20121use of the package System.Dim.Mks, which is part of the GNAT library. This
20122package defines a floating-point type MKS_Type, for which a sequence of
20123dimension names are specified, together with their conventional abbreviations.
20124The following should be read together with the full specification of the
20125package, in file s-dimmks.ads.
20126
20127@smallexample @c ada
20128   type Mks_Type is new Long_Long_Float
20129     with
20130      Dimension_System => (
20131        (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
20132        (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
20133        (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
20134        (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
20135        (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
20136        (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
20137        (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
20138@end smallexample
20139
20140@noindent
20141The package then defines a series of subtypes that correspond to these
20142conventional units. For example:
20143@smallexample @c ada
20144   subtype Length is Mks_Type
20145     with
20146      Dimension => (Symbol => 'm', Meter  => 1, others => 0);
20147@end smallexample
20148@noindent
20149and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
20150Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
20151the SI system).
20152
20153The package also defines conventional names for values of each unit, for
20154example:
20155
20156@smallexample @c ada
20157   m   : constant Length           := 1.0;
20158   kg  : constant Mass             := 1.0;
20159   s   : constant Time             := 1.0;
20160   A   : constant Electric_Current := 1.0;
20161@end smallexample
20162
20163@noindent
20164as well as useful multiples of these units:
20165
20166@smallexample @c ada
20167   cm  : constant Length := 1.0E-02;
20168   g   : constant Mass   := 1.0E-03;
20169   min : constant Time   := 60.0;
20170   day : constant TIme   := 60.0 * 24.0 * min;
20171  ...
20172@end smallexample
20173
20174@noindent
20175Using this package, you can then define a derived unit by
20176providing the aspect that
20177specifies its dimensions within the MKS system, as well as the string to
20178be used for output of a value of that unit:
20179
20180@smallexample @c ada
20181  subtype Acceleration is Mks_Type
20182    with Dimension => ("m/sec^^^2",
20183                       Meter => 1,
20184                       Second => -2,
20185                       others => 0);
20186@end smallexample
20187
20188@noindent
20189Here is a complete example of use:
20190
20191@smallexample @c ada
20192with System.Dim.MKS; use System.Dim.Mks;
20193with System.Dim.Mks_IO; use System.Dim.Mks_IO;
20194with Text_IO; use Text_IO;
20195procedure Free_Fall is
20196  subtype Acceleration is Mks_Type
20197    with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
20198  G : constant acceleration := 9.81 * m / (s ** 2);
20199  T : Time := 10.0*s;
20200  Distance : Length;
20201begin
20202  Put ("Gravitational constant: ");
20203  Put (G, Aft => 2, Exp => 0); Put_Line ("");
20204  Distance := 0.5 * G * T ** 2;
20205  Put ("distance travelled in 10 seconds of free fall ");
20206  Put (Distance, Aft => 2, Exp => 0);
20207  Put_Line ("");
20208end Free_Fall;
20209@end smallexample
20210
20211@noindent
20212Execution of this program yields:
20213@smallexample
20214Gravitational constant:  9.81 m/sec^^^2
20215distance travelled in 10 seconds of free fall 490.50 m
20216@end smallexample
20217
20218@noindent
20219However, incorrect assignments such as:
20220
20221@smallexample @c ada
20222   Distance := 5.0;
20223   Distance := 5.0 * kg:
20224@end smallexample
20225
20226@noindent
20227are rejected with the following diagnoses:
20228
20229@smallexample
20230   Distance := 5.0;
20231      >>> dimensions mismatch in assignment
20232      >>> left-hand side has dimension [L]
20233      >>> right-hand side is dimensionless
20234
20235   Distance := 5.0 * kg:
20236      >>> dimensions mismatch in assignment
20237      >>> left-hand side has dimension [L]
20238      >>> right-hand side has dimension [M]
20239@end smallexample
20240
20241@noindent
20242The dimensions of an expression are properly displayed, even if there is
20243no explicit subtype for it. If we add to the program:
20244
20245@smallexample @c ada
20246      Put ("Final velocity: ");
20247      Put (G * T, Aft =>2, Exp =>0);
20248      Put_Line ("");
20249@end smallexample
20250
20251@noindent
20252then the output includes:
20253@smallexample
20254     Final velocity: 98.10 m.s**(-1)
20255@end smallexample
20256
20257@c *********************************
20258@node Generating Ada Bindings for C and C++ headers
20259@chapter Generating Ada Bindings for C and C++ headers
20260@findex binding
20261
20262@noindent
20263GNAT now comes with a binding generator for C and C++ headers which is
20264intended to do 95% of the tedious work of generating Ada specs from C
20265or C++ header files.
20266
20267Note that this capability is not intended to generate 100% correct Ada specs,
20268and will is some cases require manual adjustments, although it can often
20269be used out of the box in practice.
20270
20271Some of the known limitations include:
20272
20273@itemize @bullet
20274@item only very simple character constant macros are translated into Ada
20275constants. Function macros (macros with arguments) are partially translated
20276as comments, to be completed manually if needed.
20277@item some extensions (e.g. vector types) are not supported
20278@item pointers to pointers or complex structures are mapped to System.Address
20279@item identifiers with identical name (except casing) will generate compilation
20280      errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20281@end itemize
20282
20283The code generated is using the Ada 2005 syntax, which makes it
20284easier to interface with other languages than previous versions of Ada.
20285
20286@menu
20287* Running the binding generator::
20288* Generating bindings for C++ headers::
20289* Switches::
20290@end menu
20291
20292@node Running the binding generator
20293@section Running the binding generator
20294
20295@noindent
20296The binding generator is part of the @command{gcc} compiler and can be
20297invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20298spec files for the header files specified on the command line, and all
20299header files needed by these files transitively. For example:
20300
20301@smallexample
20302$ g++ -c -fdump-ada-spec -C /usr/include/time.h
20303$ gcc -c -gnat05 *.ads
20304@end smallexample
20305
20306will generate, under GNU/Linux, the following files: @file{time_h.ads},
20307@file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20308correspond to the files @file{/usr/include/time.h},
20309@file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20310mode these Ada specs.
20311
20312The @code{-C} switch tells @command{gcc} to extract comments from headers,
20313and will attempt to generate corresponding Ada comments.
20314
20315If you want to generate a single Ada file and not the transitive closure, you
20316can use instead the @option{-fdump-ada-spec-slim} switch.
20317
20318You can optionally specify a parent unit, of which all generated units will
20319be children, using @code{-fada-spec-parent=}@var{unit}.
20320
20321Note that we recommend when possible to use the @command{g++} driver to
20322generate bindings, even for most C headers, since this will in general
20323generate better Ada specs. For generating bindings for C++ headers, it is
20324mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20325is equivalent in this case. If @command{g++} cannot work on your C headers
20326because of incompatibilities between C and C++, then you can fallback to
20327@command{gcc} instead.
20328
20329For an example of better bindings generated from the C++ front-end,
20330the name of the parameters (when available) are actually ignored by the C
20331front-end. Consider the following C header:
20332
20333@smallexample
20334extern void foo (int variable);
20335@end smallexample
20336
20337with the C front-end, @code{variable} is ignored, and the above is handled as:
20338
20339@smallexample
20340extern void foo (int);
20341@end smallexample
20342
20343generating a generic:
20344
20345@smallexample
20346procedure foo (param1 : int);
20347@end smallexample
20348
20349with the C++ front-end, the name is available, and we generate:
20350
20351@smallexample
20352procedure foo (variable : int);
20353@end smallexample
20354
20355In some cases, the generated bindings will be more complete or more meaningful
20356when defining some macros, which you can do via the @option{-D} switch. This
20357is for example the case with @file{Xlib.h} under GNU/Linux:
20358
20359@smallexample
20360g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20361@end smallexample
20362
20363The above will generate more complete bindings than a straight call without
20364the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20365
20366In other cases, it is not possible to parse a header file in a stand-alone
20367manner, because other include files need to be included first. In this
20368case, the solution is to create a small header file including the needed
20369@code{#include} and possible @code{#define} directives. For example, to
20370generate Ada bindings for @file{readline/readline.h}, you need to first
20371include @file{stdio.h}, so you can create a file with the following two
20372lines in e.g. @file{readline1.h}:
20373
20374@smallexample
20375#include <stdio.h>
20376#include <readline/readline.h>
20377@end smallexample
20378
20379and then generate Ada bindings from this file:
20380
20381@smallexample
20382$ g++ -c -fdump-ada-spec readline1.h
20383@end smallexample
20384
20385@node Generating bindings for C++ headers
20386@section Generating bindings for C++ headers
20387
20388@noindent
20389Generating bindings for C++ headers is done using the same options, always
20390with the @command{g++} compiler.
20391
20392In this mode, C++ classes will be mapped to Ada tagged types, constructors
20393will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20394multiple inheritance of abstract classes will be mapped to Ada interfaces
20395(@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20396information on interfacing to C++).
20397
20398For example, given the following C++ header file:
20399
20400@smallexample
20401@group
20402@cartouche
20403class Carnivore @{
20404public:
20405   virtual int Number_Of_Teeth () = 0;
20406@};
20407
20408class Domestic @{
20409public:
20410   virtual void Set_Owner (char* Name) = 0;
20411@};
20412
20413class Animal @{
20414public:
20415  int Age_Count;
20416  virtual void Set_Age (int New_Age);
20417@};
20418
20419class Dog : Animal, Carnivore, Domestic @{
20420 public:
20421  int  Tooth_Count;
20422  char *Owner;
20423
20424  virtual int  Number_Of_Teeth ();
20425  virtual void Set_Owner (char* Name);
20426
20427  Dog();
20428@};
20429@end cartouche
20430@end group
20431@end smallexample
20432
20433The corresponding Ada code is generated:
20434
20435@smallexample @c ada
20436@group
20437@cartouche
20438  package Class_Carnivore is
20439    type Carnivore is limited interface;
20440    pragma Import (CPP, Carnivore);
20441
20442    function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20443  end;
20444  use Class_Carnivore;
20445
20446  package Class_Domestic is
20447    type Domestic is limited interface;
20448    pragma Import (CPP, Domestic);
20449
20450    procedure Set_Owner
20451      (this : access Domestic;
20452       Name : Interfaces.C.Strings.chars_ptr) is abstract;
20453  end;
20454  use Class_Domestic;
20455
20456  package Class_Animal is
20457    type Animal is tagged limited record
20458      Age_Count : aliased int;
20459    end record;
20460    pragma Import (CPP, Animal);
20461
20462    procedure Set_Age (this : access Animal; New_Age : int);
20463    pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20464  end;
20465  use Class_Animal;
20466
20467  package Class_Dog is
20468    type Dog is new Animal and Carnivore and Domestic with record
20469      Tooth_Count : aliased int;
20470      Owner : Interfaces.C.Strings.chars_ptr;
20471    end record;
20472    pragma Import (CPP, Dog);
20473
20474    function Number_Of_Teeth (this : access Dog) return int;
20475    pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20476
20477    procedure Set_Owner
20478      (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20479    pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20480
20481    function New_Dog return Dog;
20482    pragma CPP_Constructor (New_Dog);
20483    pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20484  end;
20485  use Class_Dog;
20486@end cartouche
20487@end group
20488@end smallexample
20489
20490@node Switches
20491@section Switches
20492
20493@table @option
20494@item -fdump-ada-spec
20495@cindex @option{-fdump-ada-spec} (@command{gcc})
20496Generate Ada spec files for the given header files transitively (including
20497all header files that these headers depend upon).
20498
20499@item -fdump-ada-spec-slim
20500@cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20501Generate Ada spec files for the header files specified on the command line
20502only.
20503
20504@item -fada-spec-parent=@var{unit}
20505@cindex -fada-spec-parent (@command{gcc})
20506Specifies that all files generated by @option{-fdump-ada-spec*} are
20507to be child units of the specified parent unit.
20508
20509@item -C
20510@cindex @option{-C} (@command{gcc})
20511Extract comments from headers and generate Ada comments in the Ada spec files.
20512@end table
20513
20514@node Other Utility Programs
20515@chapter Other Utility Programs
20516
20517@noindent
20518This chapter discusses some other utility programs available in the Ada
20519environment.
20520
20521@menu
20522* Using Other Utility Programs with GNAT::
20523* The External Symbol Naming Scheme of GNAT::
20524* Converting Ada Files to html with gnathtml::
20525* Installing gnathtml::
20526@ifset vms
20527* LSE::
20528* Profiling::
20529@end ifset
20530@end menu
20531
20532@node Using Other Utility Programs with GNAT
20533@section Using Other Utility Programs with GNAT
20534
20535@noindent
20536The object files generated by GNAT are in standard system format and in
20537particular the debugging information uses this format. This means
20538programs generated by GNAT can be used with existing utilities that
20539depend on these formats.
20540
20541@ifclear vms
20542In general, any utility program that works with C will also often work with
20543Ada programs generated by GNAT. This includes software utilities such as
20544gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20545as Purify.
20546@end ifclear
20547
20548@node The External Symbol Naming Scheme of GNAT
20549@section The External Symbol Naming Scheme of GNAT
20550
20551@noindent
20552In order to interpret the output from GNAT, when using tools that are
20553originally intended for use with other languages, it is useful to
20554understand the conventions used to generate link names from the Ada
20555entity names.
20556
20557All link names are in all lowercase letters. With the exception of library
20558procedure names, the mechanism used is simply to use the full expanded
20559Ada name with dots replaced by double underscores. For example, suppose
20560we have the following package spec:
20561
20562@smallexample @c ada
20563@group
20564@cartouche
20565package QRS is
20566   MN : Integer;
20567end QRS;
20568@end cartouche
20569@end group
20570@end smallexample
20571
20572@noindent
20573The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20574the corresponding link name is @code{qrs__mn}.
20575@findex Export
20576Of course if a @code{pragma Export} is used this may be overridden:
20577
20578@smallexample @c ada
20579@group
20580@cartouche
20581package Exports is
20582   Var1 : Integer;
20583   pragma Export (Var1, C, External_Name => "var1_name");
20584   Var2 : Integer;
20585   pragma Export (Var2, C, Link_Name => "var2_link_name");
20586end Exports;
20587@end cartouche
20588@end group
20589@end smallexample
20590
20591@noindent
20592In this case, the link name for @var{Var1} is whatever link name the
20593C compiler would assign for the C function @var{var1_name}. This typically
20594would be either @var{var1_name} or @var{_var1_name}, depending on operating
20595system conventions, but other possibilities exist. The link name for
20596@var{Var2} is @var{var2_link_name}, and this is not operating system
20597dependent.
20598
20599@findex _main
20600One exception occurs for library level procedures. A potential ambiguity
20601arises between the required name @code{_main} for the C main program,
20602and the name we would otherwise assign to an Ada library level procedure
20603called @code{Main} (which might well not be the main program).
20604
20605To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20606names. So if we have a library level procedure such as
20607
20608@smallexample @c ada
20609@group
20610@cartouche
20611procedure Hello (S : String);
20612@end cartouche
20613@end group
20614@end smallexample
20615
20616@noindent
20617the external name of this procedure will be @var{_ada_hello}.
20618
20619
20620@node Converting Ada Files to html with gnathtml
20621@section Converting Ada Files to HTML with @code{gnathtml}
20622
20623@noindent
20624This @code{Perl} script allows Ada source files to be browsed using
20625standard Web browsers. For installation procedure, see the section
20626@xref{Installing gnathtml}.
20627
20628Ada reserved keywords are highlighted in a bold font and Ada comments in
20629a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20630switch to suppress the generation of cross-referencing information, user
20631defined variables and types will appear in a different color; you will
20632be able to click on any identifier and go to its declaration.
20633
20634The command line is as follow:
20635@smallexample
20636@c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20637@c Expanding @ovar macro inline (explanation in macro def comments)
20638$ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20639@end smallexample
20640
20641@noindent
20642You can pass it as many Ada files as you want. @code{gnathtml} will generate
20643an html file for every ada file, and a global file called @file{index.htm}.
20644This file is an index of every identifier defined in the files.
20645
20646The available ^switches^options^ are the following ones:
20647
20648@table @option
20649@item -83
20650@cindex @option{-83} (@code{gnathtml})
20651Only the Ada 83 subset of keywords will be highlighted.
20652
20653@item -cc @var{color}
20654@cindex @option{-cc} (@code{gnathtml})
20655This option allows you to change the color used for comments. The default
20656value is green. The color argument can be any name accepted by html.
20657
20658@item -d
20659@cindex @option{-d} (@code{gnathtml})
20660If the Ada files depend on some other files (for instance through
20661@code{with} clauses, the latter files will also be converted to html.
20662Only the files in the user project will be converted to html, not the files
20663in the run-time library itself.
20664
20665@item -D
20666@cindex @option{-D} (@code{gnathtml})
20667This command is the same as @option{-d} above, but @command{gnathtml} will
20668also look for files in the run-time library, and generate html files for them.
20669
20670@item -ext @var{extension}
20671@cindex @option{-ext} (@code{gnathtml})
20672This option allows you to change the extension of the generated HTML files.
20673If you do not specify an extension, it will default to @file{htm}.
20674
20675@item -f
20676@cindex @option{-f} (@code{gnathtml})
20677By default, gnathtml will generate html links only for global entities
20678('with'ed units, global variables and types,@dots{}).  If you specify
20679@option{-f} on the command line, then links will be generated for local
20680entities too.
20681
20682@item -l @var{number}
20683@cindex @option{-l} (@code{gnathtml})
20684If this ^switch^option^ is provided and @var{number} is not 0, then
20685@code{gnathtml} will number the html files every @var{number} line.
20686
20687@item -I @var{dir}
20688@cindex @option{-I} (@code{gnathtml})
20689Specify a directory to search for library files (@file{.ALI} files) and
20690source files. You can provide several -I switches on the command line,
20691and the directories will be parsed in the order of the command line.
20692
20693@item -o @var{dir}
20694@cindex @option{-o} (@code{gnathtml})
20695Specify the output directory for html files. By default, gnathtml will
20696saved the generated html files in a subdirectory named @file{html/}.
20697
20698@item -p @var{file}
20699@cindex @option{-p} (@code{gnathtml})
20700If you are using Emacs and the most recent Emacs Ada mode, which provides
20701a full Integrated Development Environment for compiling, checking,
20702running and debugging applications, you may use @file{.gpr} files
20703to give the directories where Emacs can find sources and object files.
20704
20705Using this ^switch^option^, you can tell gnathtml to use these files.
20706This allows you to get an html version of your application, even if it
20707is spread over multiple directories.
20708
20709@item -sc @var{color}
20710@cindex @option{-sc} (@code{gnathtml})
20711This ^switch^option^ allows you to change the color used for symbol
20712definitions.
20713The default value is red. The color argument can be any name accepted by html.
20714
20715@item -t @var{file}
20716@cindex @option{-t} (@code{gnathtml})
20717This ^switch^option^ provides the name of a file. This file contains a list of
20718file names to be converted, and the effect is exactly as though they had
20719appeared explicitly on the command line. This
20720is the recommended way to work around the command line length limit on some
20721systems.
20722
20723@end table
20724
20725@node Installing gnathtml
20726@section Installing @code{gnathtml}
20727
20728@noindent
20729@code{Perl} needs to be installed on your machine to run this script.
20730@code{Perl} is freely available for almost every architecture and
20731Operating System via the Internet.
20732
20733On Unix systems, you  may want to modify  the  first line of  the script
20734@code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
20735is. The syntax of this line is:
20736@smallexample
20737#!full_path_name_to_perl
20738@end smallexample
20739
20740@noindent
20741Alternatively, you may run the script using the following command line:
20742
20743@smallexample
20744@c $ perl gnathtml.pl @ovar{switches} @var{files}
20745@c Expanding @ovar macro inline (explanation in macro def comments)
20746$ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20747@end smallexample
20748
20749@ifset vms
20750@node LSE
20751@section LSE
20752@findex LSE
20753
20754@noindent
20755The GNAT distribution provides an Ada 95 template for the HP Language
20756Sensitive Editor (LSE), a component of DECset. In order to
20757access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20758
20759@node Profiling
20760@section Profiling
20761@findex PCA
20762
20763@noindent
20764GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20765of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20766the collection phase with the /DEBUG qualifier.
20767
20768@smallexample
20769$ GNAT MAKE /DEBUG <PROGRAM_NAME>
20770$ DEFINE LIB$DEBUG PCA$COLLECTOR
20771$ RUN/DEBUG <PROGRAM_NAME>
20772@end smallexample
20773@noindent
20774@end ifset
20775
20776@ifclear vms
20777@c ******************************
20778@node Code Coverage and Profiling
20779@chapter Code Coverage and Profiling
20780@cindex Code Coverage
20781@cindex Profiling
20782
20783@noindent
20784This chapter describes how to use @code{gcov} - coverage testing tool - and
20785@code{gprof} - profiler tool - on your Ada programs.
20786
20787@menu
20788* Code Coverage of Ada Programs with gcov::
20789* Profiling an Ada Program with gprof::
20790@end menu
20791
20792@node Code Coverage of Ada Programs with gcov
20793@section Code Coverage of Ada Programs with gcov
20794@cindex gcov
20795@cindex -fprofile-arcs
20796@cindex -ftest-coverage
20797@cindex -coverage
20798@cindex Code Coverage
20799
20800@noindent
20801@code{gcov} is a test coverage program: it analyzes the execution of a given
20802program on selected tests, to help you determine the portions of the program
20803that are still untested.
20804
20805@code{gcov} is part of the GCC suite, and is described in detail in the GCC
20806User's Guide. You can refer to this documentation for a more complete
20807description.
20808
20809This chapter provides a quick startup guide, and
20810details some Gnat-specific features.
20811
20812@menu
20813* Quick startup guide::
20814* Gnat specifics::
20815@end menu
20816
20817@node Quick startup guide
20818@subsection Quick startup guide
20819
20820In order to perform coverage analysis of a program using @code{gcov}, 3
20821steps are needed:
20822
20823@itemize @bullet
20824@item
20825Code instrumentation during the compilation process
20826@item
20827Execution of the instrumented program
20828@item
20829Execution of the @code{gcov} tool to generate the result.
20830@end itemize
20831
20832The code instrumentation needed by gcov is created at the object level:
20833The source code is not modified in any way, because the instrumentation code is
20834inserted by gcc during the compilation process. To compile your code with code
20835coverage activated, you need to recompile your whole project using the
20836switches
20837@code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20838@code{-fprofile-arcs}.
20839
20840@smallexample
20841$ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20842   -largs -fprofile-arcs
20843@end smallexample
20844
20845This compilation process will create @file{.gcno} files together with
20846the usual object files.
20847
20848Once the program is compiled with coverage instrumentation, you can
20849run it as many times as needed - on portions of a test suite for
20850example. The first execution will produce @file{.gcda} files at the
20851same location as the @file{.gcno} files.  The following executions
20852will update those files, so that a cumulative result of the covered
20853portions of the program is generated.
20854
20855Finally, you need to call the @code{gcov} tool. The different options of
20856@code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20857
20858This will create annotated source files with a @file{.gcov} extension:
20859@file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20860
20861@node Gnat specifics
20862@subsection Gnat specifics
20863
20864Because Ada semantics, portions of the source code may be shared among
20865several object files. This is the case for example when generics are
20866involved, when inlining is active  or when declarations generate  initialisation
20867calls. In order to take
20868into account this shared code, you need to call @code{gcov} on all
20869source files of the tested program at once.
20870
20871The list of source files might exceed the system's maximum command line
20872length. In order to bypass this limitation, a new mechanism has been
20873implemented in @code{gcov}: you can now list all your project's files into a
20874text file, and provide this file to gcov as a parameter,  preceded by a @@
20875(e.g. @samp{gcov @@mysrclist.txt}).
20876
20877Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20878not supported as there can be unresolved symbols during the final link.
20879
20880@node Profiling an Ada Program with gprof
20881@section Profiling an Ada Program with gprof
20882@cindex gprof
20883@cindex -pg
20884@cindex Profiling
20885
20886@noindent
20887This section is not meant to be an exhaustive documentation of @code{gprof}.
20888Full documentation for it can be found in the GNU Profiler User's Guide
20889documentation that is part of this GNAT distribution.
20890
20891Profiling a program helps determine the parts of a program that are executed
20892most often, and are therefore the most time-consuming.
20893
20894@code{gprof} is the standard GNU profiling tool; it has been enhanced to
20895better handle Ada programs and multitasking.
20896It is currently supported on the following platforms
20897@itemize @bullet
20898@item
20899linux x86/x86_64
20900@item
20901solaris sparc/sparc64/x86
20902@item
20903windows x86
20904@end itemize
20905
20906@noindent
20907In order to profile a program using @code{gprof}, 3 steps are needed:
20908
20909@itemize @bullet
20910@item
20911Code instrumentation, requiring a full recompilation of the project with the
20912proper switches.
20913@item
20914Execution of the program under the analysis conditions, i.e. with the desired
20915input.
20916@item
20917Analysis of the results using the @code{gprof} tool.
20918@end itemize
20919
20920@noindent
20921The following sections detail the different steps, and indicate how
20922to interpret the results:
20923@menu
20924* Compilation for profiling::
20925* Program execution::
20926* Running gprof::
20927* Interpretation of profiling results::
20928@end menu
20929
20930@node Compilation for profiling
20931@subsection Compilation for profiling
20932@cindex -pg
20933@cindex Profiling
20934
20935In order to profile a program the first step is to tell the compiler
20936to generate the necessary profiling information. The compiler switch to be used
20937is @code{-pg}, which must be added to other compilation switches. This
20938switch needs to be specified both during compilation and link stages, and can
20939be specified once when using gnatmake:
20940
20941@smallexample
20942gnatmake -f -pg -P my_project
20943@end smallexample
20944
20945@noindent
20946Note that only the objects that were compiled with the @samp{-pg} switch will
20947be profiled; if you need to profile your whole project, use the @samp{-f}
20948gnatmake switch to force full recompilation.
20949
20950@node Program execution
20951@subsection Program execution
20952
20953@noindent
20954Once the program has been compiled for profiling, you can run it as usual.
20955
20956The only constraint imposed by profiling is that the program must terminate
20957normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20958properly analyzed.
20959
20960Once the program completes execution, a data file called @file{gmon.out} is
20961generated in the directory where the program was launched from. If this file
20962already exists, it will be overwritten.
20963
20964@node Running gprof
20965@subsection Running gprof
20966
20967@noindent
20968The @code{gprof} tool is called as follow:
20969
20970@smallexample
20971gprof my_prog gmon.out
20972@end smallexample
20973
20974@noindent
20975or simpler:
20976
20977@smallexample
20978gprof my_prog
20979@end smallexample
20980
20981@noindent
20982The complete form of the gprof command line is the following:
20983
20984@smallexample
20985gprof [^switches^options^] [executable [data-file]]
20986@end smallexample
20987
20988@noindent
20989@code{gprof} supports numerous ^switch^options^. The order of these
20990^switch^options^ does not matter. The full list of options can be found in
20991the GNU Profiler User's Guide documentation that comes with this documentation.
20992
20993The following is the subset of those switches that is most relevant:
20994
20995@table @option
20996
20997@item --demangle[=@var{style}]
20998@itemx --no-demangle
20999@cindex @option{--demangle} (@code{gprof})
21000These options control whether symbol names should be demangled when
21001printing output.  The default is to demangle C++ symbols.  The
21002@code{--no-demangle} option may be used to turn off demangling. Different
21003compilers have different mangling styles.  The optional demangling style
21004argument can be used to choose an appropriate demangling style for your
21005compiler, in particular Ada symbols generated by GNAT can be demangled using
21006@code{--demangle=gnat}.
21007
21008@item -e @var{function_name}
21009@cindex @option{-e} (@code{gprof})
21010The @samp{-e @var{function}} option tells @code{gprof} not to print
21011information about the function @var{function_name} (and its
21012children@dots{}) in the call graph.  The function will still be listed
21013as a child of any functions that call it, but its index number will be
21014shown as @samp{[not printed]}.  More than one @samp{-e} option may be
21015given; only one @var{function_name} may be indicated with each @samp{-e}
21016option.
21017
21018@item -E @var{function_name}
21019@cindex @option{-E} (@code{gprof})
21020The @code{-E @var{function}} option works like the @code{-e} option, but
21021execution time spent in the function (and children who were not called from
21022anywhere else), will not be used to compute the percentages-of-time for
21023the call graph.  More than one @samp{-E} option may be given; only one
21024@var{function_name} may be indicated with each @samp{-E} option.
21025
21026@item -f @var{function_name}
21027@cindex @option{-f} (@code{gprof})
21028The @samp{-f @var{function}} option causes @code{gprof} to limit the
21029call graph to the function @var{function_name} and its children (and
21030their children@dots{}).  More than one @samp{-f} option may be given;
21031only one @var{function_name} may be indicated with each @samp{-f}
21032option.
21033
21034@item -F @var{function_name}
21035@cindex @option{-F} (@code{gprof})
21036The @samp{-F @var{function}} option works like the @code{-f} option, but
21037only time spent in the function and its children (and their
21038children@dots{}) will be used to determine total-time and
21039percentages-of-time for the call graph.  More than one @samp{-F} option
21040may be given; only one @var{function_name} may be indicated with each
21041@samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
21042
21043@end table
21044
21045@node Interpretation of profiling results
21046@subsection Interpretation of profiling results
21047
21048@noindent
21049
21050The results of the profiling analysis are represented by two arrays: the
21051'flat profile' and the 'call graph'. Full documentation of those outputs
21052can be found in the GNU Profiler User's Guide.
21053
21054The flat profile shows the time spent in each function of the program, and how
21055many time it has been called. This allows you to locate easily the most
21056time-consuming functions.
21057
21058The call graph shows, for each subprogram, the subprograms that call it,
21059and the subprograms that it calls. It also provides an estimate of the time
21060spent in each of those callers/called subprograms.
21061@end ifclear
21062
21063@c ******************************
21064@node Running and Debugging Ada Programs
21065@chapter Running and Debugging Ada Programs
21066@cindex Debugging
21067
21068@noindent
21069This chapter discusses how to debug Ada programs.
21070@ifset vms
21071It applies to GNAT on the Alpha OpenVMS platform;
21072for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21073since HP has implemented Ada support in the OpenVMS debugger on I64.
21074@end ifset
21075
21076An incorrect Ada program may be handled in three ways by the GNAT compiler:
21077
21078@enumerate
21079@item
21080The illegality may be a violation of the static semantics of Ada. In
21081that case GNAT diagnoses the constructs in the program that are illegal.
21082It is then a straightforward matter for the user to modify those parts of
21083the program.
21084
21085@item
21086The illegality may be a violation of the dynamic semantics of Ada. In
21087that case the program compiles and executes, but may generate incorrect
21088results, or may terminate abnormally with some exception.
21089
21090@item
21091When presented with a program that contains convoluted errors, GNAT
21092itself may terminate abnormally without providing full diagnostics on
21093the incorrect user program.
21094@end enumerate
21095
21096@menu
21097* The GNAT Debugger GDB::
21098* Running GDB::
21099* Introduction to GDB Commands::
21100* Using Ada Expressions::
21101* Calling User-Defined Subprograms::
21102* Using the Next Command in a Function::
21103* Ada Exceptions::
21104* Ada Tasks::
21105* Debugging Generic Units::
21106* Remote Debugging with gdbserver::
21107* GNAT Abnormal Termination or Failure to Terminate::
21108* Naming Conventions for GNAT Source Files::
21109* Getting Internal Debugging Information::
21110* Stack Traceback::
21111@end menu
21112
21113@cindex Debugger
21114@findex gdb
21115
21116@node The GNAT Debugger GDB
21117@section The GNAT Debugger GDB
21118
21119@noindent
21120@code{GDB} is a general purpose, platform-independent debugger that
21121can be used to debug mixed-language programs compiled with @command{gcc},
21122and in particular is capable of debugging Ada programs compiled with
21123GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21124complex Ada data structures.
21125
21126@xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
21127@ifset vms
21128located in the GNU:[DOCS] directory,
21129@end ifset
21130for full details on the usage of @code{GDB}, including a section on
21131its usage on programs. This manual should be consulted for full
21132details. The section that follows is a brief introduction to the
21133philosophy and use of @code{GDB}.
21134
21135When GNAT programs are compiled, the compiler optionally writes debugging
21136information into the generated object file, including information on
21137line numbers, and on declared types and variables. This information is
21138separate from the generated code. It makes the object files considerably
21139larger, but it does not add to the size of the actual executable that
21140will be loaded into memory, and has no impact on run-time performance. The
21141generation of debug information is triggered by the use of the
21142^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
21143used to carry out the compilations. It is important to emphasize that
21144the use of these options does not change the generated code.
21145
21146The debugging information is written in standard system formats that
21147are used by many tools, including debuggers and profilers. The format
21148of the information is typically designed to describe C types and
21149semantics, but GNAT implements a translation scheme which allows full
21150details about Ada types and variables to be encoded into these
21151standard C formats. Details of this encoding scheme may be found in
21152the file exp_dbug.ads in the GNAT source distribution. However, the
21153details of this encoding are, in general, of no interest to a user,
21154since @code{GDB} automatically performs the necessary decoding.
21155
21156When a program is bound and linked, the debugging information is
21157collected from the object files, and stored in the executable image of
21158the program. Again, this process significantly increases the size of
21159the generated executable file, but it does not increase the size of
21160the executable program itself. Furthermore, if this program is run in
21161the normal manner, it runs exactly as if the debug information were
21162not present, and takes no more actual memory.
21163
21164However, if the program is run under control of @code{GDB}, the
21165debugger is activated.  The image of the program is loaded, at which
21166point it is ready to run.  If a run command is given, then the program
21167will run exactly as it would have if @code{GDB} were not present. This
21168is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
21169entirely non-intrusive until a breakpoint is encountered.  If no
21170breakpoint is ever hit, the program will run exactly as it would if no
21171debugger were present. When a breakpoint is hit, @code{GDB} accesses
21172the debugging information and can respond to user commands to inspect
21173variables, and more generally to report on the state of execution.
21174
21175@c **************
21176@node Running GDB
21177@section Running GDB
21178
21179@noindent
21180This section describes how to initiate the debugger.
21181@c The above sentence is really just filler, but it was otherwise
21182@c clumsy to get the first paragraph nonindented given the conditional
21183@c nature of the description
21184
21185@ifclear vms
21186The debugger can be launched from a @code{GPS} menu or
21187directly from the command line. The description below covers the latter use.
21188All the commands shown can be used in the @code{GPS} debug console window,
21189but there are usually more GUI-based ways to achieve the same effect.
21190@end ifclear
21191
21192The command to run @code{GDB} is
21193
21194@smallexample
21195$ ^gdb program^GDB PROGRAM^
21196@end smallexample
21197
21198@noindent
21199where @code{^program^PROGRAM^} is the name of the executable file. This
21200activates the debugger and results in a prompt for debugger commands.
21201The simplest command is simply @code{run}, which causes the program to run
21202exactly as if the debugger were not present. The following section
21203describes some of the additional commands that can be given to @code{GDB}.
21204
21205@c *******************************
21206@node Introduction to GDB Commands
21207@section Introduction to GDB Commands
21208
21209@noindent
21210@code{GDB} contains a large repertoire of commands.  @xref{Top,,
21211Debugging with GDB, gdb, Debugging with GDB},
21212@ifset vms
21213located in the GNU:[DOCS] directory,
21214@end ifset
21215for extensive documentation on the use
21216of these commands, together with examples of their use. Furthermore,
21217the command @command{help} invoked from within GDB activates a simple help
21218facility which summarizes the available commands and their options.
21219In this section we summarize a few of the most commonly
21220used commands to give an idea of what @code{GDB} is about. You should create
21221a simple program with debugging information and experiment with the use of
21222these @code{GDB} commands on the program as you read through the
21223following section.
21224
21225@table @code
21226@item set args @var{arguments}
21227The @var{arguments} list above is a list of arguments to be passed to
21228the program on a subsequent run command, just as though the arguments
21229had been entered on a normal invocation of the program. The @code{set args}
21230command is not needed if the program does not require arguments.
21231
21232@item run
21233The @code{run} command causes execution of the program to start from
21234the beginning. If the program is already running, that is to say if
21235you are currently positioned at a breakpoint, then a prompt will ask
21236for confirmation that you want to abandon the current execution and
21237restart.
21238
21239@item breakpoint @var{location}
21240The breakpoint command sets a breakpoint, that is to say a point at which
21241execution will halt and @code{GDB} will await further
21242commands. @var{location} is
21243either a line number within a file, given in the format @code{file:linenumber},
21244or it is the name of a subprogram. If you request that a breakpoint be set on
21245a subprogram that is overloaded, a prompt will ask you to specify on which of
21246those subprograms you want to breakpoint. You can also
21247specify that all of them should be breakpointed. If the program is run
21248and execution encounters the breakpoint, then the program
21249stops and @code{GDB} signals that the breakpoint was encountered by
21250printing the line of code before which the program is halted.
21251
21252@item catch exception @var{name}
21253This command causes the program execution to stop whenever exception
21254@var{name} is raised.  If @var{name} is omitted, then the execution is
21255suspended when any exception is raised.
21256
21257@item print @var{expression}
21258This will print the value of the given expression. Most simple
21259Ada expression formats are properly handled by @code{GDB}, so the expression
21260can contain function calls, variables, operators, and attribute references.
21261
21262@item continue
21263Continues execution following a breakpoint, until the next breakpoint or the
21264termination of the program.
21265
21266@item step
21267Executes a single line after a breakpoint. If the next statement
21268is a subprogram call, execution continues into (the first statement of)
21269the called subprogram.
21270
21271@item next
21272Executes a single line. If this line is a subprogram call, executes and
21273returns from the call.
21274
21275@item list
21276Lists a few lines around the current source location. In practice, it
21277is usually more convenient to have a separate edit window open with the
21278relevant source file displayed. Successive applications of this command
21279print subsequent lines. The command can be given an argument which is a
21280line number, in which case it displays a few lines around the specified one.
21281
21282@item backtrace
21283Displays a backtrace of the call chain. This command is typically
21284used after a breakpoint has occurred, to examine the sequence of calls that
21285leads to the current breakpoint. The display includes one line for each
21286activation record (frame) corresponding to an active subprogram.
21287
21288@item up
21289At a breakpoint, @code{GDB} can display the values of variables local
21290to the current frame. The command @code{up} can be used to
21291examine the contents of other active frames, by moving the focus up
21292the stack, that is to say from callee to caller, one frame at a time.
21293
21294@item down
21295Moves the focus of @code{GDB} down from the frame currently being
21296examined to the frame of its callee (the reverse of the previous command),
21297
21298@item frame @var{n}
21299Inspect the frame with the given number. The value 0 denotes the frame
21300of the current breakpoint, that is to say the top of the call stack.
21301
21302@item kill
21303Kills the child process in which the program is running under GDB.
21304This may be useful for several purposes:
21305@itemize @bullet
21306@item
21307It allows you to recompile and relink your program, since on many systems
21308you cannot regenerate an executable file while it is running in a process.
21309@item
21310You can run your program outside the debugger, on systems that do not
21311permit executing a program outside GDB while breakpoints are set
21312within GDB.
21313@item
21314It allows you to debug a core dump rather than a running process.
21315@end itemize
21316@end table
21317
21318@noindent
21319The above list is a very short introduction to the commands that
21320@code{GDB} provides. Important additional capabilities, including conditional
21321breakpoints, the ability to execute command sequences on a breakpoint,
21322the ability to debug at the machine instruction level and many other
21323features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21324Debugging with GDB}.  Note that most commands can be abbreviated
21325(for example, c for continue, bt for backtrace).
21326
21327@node Using Ada Expressions
21328@section Using Ada Expressions
21329@cindex Ada expressions
21330
21331@noindent
21332@code{GDB} supports a fairly large subset of Ada expression syntax, with some
21333extensions. The philosophy behind the design of this subset is
21334
21335@itemize @bullet
21336@item
21337That @code{GDB} should provide basic literals and access to operations for
21338arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21339leaving more sophisticated computations to subprograms written into the
21340program (which therefore may be called from @code{GDB}).
21341
21342@item
21343That type safety and strict adherence to Ada language restrictions
21344are not particularly important to the @code{GDB} user.
21345
21346@item
21347That brevity is important to the @code{GDB} user.
21348@end itemize
21349
21350@noindent
21351Thus, for brevity, the debugger acts as if there were
21352implicit @code{with} and @code{use} clauses in effect for all user-written
21353packages, thus making it unnecessary to fully qualify most names with
21354their packages, regardless of context. Where this causes ambiguity,
21355@code{GDB} asks the user's intent.
21356
21357For details on the supported Ada syntax, see @ref{Top,, Debugging with
21358GDB, gdb, Debugging with GDB}.
21359
21360@node Calling User-Defined Subprograms
21361@section Calling User-Defined Subprograms
21362
21363@noindent
21364An important capability of @code{GDB} is the ability to call user-defined
21365subprograms while debugging. This is achieved simply by entering
21366a subprogram call statement in the form:
21367
21368@smallexample
21369call subprogram-name (parameters)
21370@end smallexample
21371
21372@noindent
21373The keyword @code{call} can be omitted in the normal case where the
21374@code{subprogram-name} does not coincide with any of the predefined
21375@code{GDB} commands.
21376
21377The effect is to invoke the given subprogram, passing it the
21378list of parameters that is supplied. The parameters can be expressions and
21379can include variables from the program being debugged. The
21380subprogram must be defined
21381at the library level within your program, and @code{GDB} will call the
21382subprogram within the environment of your program execution (which
21383means that the subprogram is free to access or even modify variables
21384within your program).
21385
21386The most important use of this facility is in allowing the inclusion of
21387debugging routines that are tailored to particular data structures
21388in your program. Such debugging routines can be written to provide a suitably
21389high-level description of an abstract type, rather than a low-level dump
21390of its physical layout. After all, the standard
21391@code{GDB print} command only knows the physical layout of your
21392types, not their abstract meaning. Debugging routines can provide information
21393at the desired semantic level and are thus enormously useful.
21394
21395For example, when debugging GNAT itself, it is crucial to have access to
21396the contents of the tree nodes used to represent the program internally.
21397But tree nodes are represented simply by an integer value (which in turn
21398is an index into a table of nodes).
21399Using the @code{print} command on a tree node would simply print this integer
21400value, which is not very useful. But the PN routine (defined in file
21401treepr.adb in the GNAT sources) takes a tree node as input, and displays
21402a useful high level representation of the tree node, which includes the
21403syntactic category of the node, its position in the source, the integers
21404that denote descendant nodes and parent node, as well as varied
21405semantic information. To study this example in more detail, you might want to
21406look at the body of the PN procedure in the stated file.
21407
21408@node Using the Next Command in a Function
21409@section Using the Next Command in a Function
21410
21411@noindent
21412When you use the @code{next} command in a function, the current source
21413location will advance to the next statement as usual. A special case
21414arises in the case of a @code{return} statement.
21415
21416Part of the code for a return statement is the ``epilog'' of the function.
21417This is the code that returns to the caller. There is only one copy of
21418this epilog code, and it is typically associated with the last return
21419statement in the function if there is more than one return. In some
21420implementations, this epilog is associated with the first statement
21421of the function.
21422
21423The result is that if you use the @code{next} command from a return
21424statement that is not the last return statement of the function you
21425may see a strange apparent jump to the last return statement or to
21426the start of the function. You should simply ignore this odd jump.
21427The value returned is always that from the first return statement
21428that was stepped through.
21429
21430@node Ada Exceptions
21431@section Stopping when Ada Exceptions are Raised
21432@cindex Exceptions
21433
21434@noindent
21435You can set catchpoints that stop the program execution when your program
21436raises selected exceptions.
21437
21438@table @code
21439@item catch exception
21440Set a catchpoint that stops execution whenever (any task in the) program
21441raises any exception.
21442
21443@item catch exception @var{name}
21444Set a catchpoint that stops execution whenever (any task in the) program
21445raises the exception @var{name}.
21446
21447@item catch exception unhandled
21448Set a catchpoint that stops executing whenever (any task in the) program
21449raises an exception for which there is no handler.
21450
21451@item info exceptions
21452@itemx info exceptions @var{regexp}
21453The @code{info exceptions} command permits the user to examine all defined
21454exceptions within Ada programs. With a regular expression, @var{regexp}, as
21455argument, prints out only those exceptions whose name matches @var{regexp}.
21456@end table
21457
21458@node Ada Tasks
21459@section Ada Tasks
21460@cindex Tasks
21461
21462@noindent
21463@code{GDB} allows the following task-related commands:
21464
21465@table @code
21466@item info tasks
21467This command shows a list of current Ada tasks, as in the following example:
21468
21469@smallexample
21470@iftex
21471@leftskip=0cm
21472@end iftex
21473(gdb) info tasks
21474  ID       TID P-ID   Thread Pri State                 Name
21475   1   8088000   0   807e000  15 Child Activation Wait main_task
21476   2   80a4000   1   80ae000  15 Accept/Select Wait    b
21477   3   809a800   1   80a4800  15 Child Activation Wait a
21478*  4   80ae800   3   80b8000  15 Running               c
21479@end smallexample
21480
21481@noindent
21482In this listing, the asterisk before the first task indicates it to be the
21483currently running task. The first column lists the task ID that is used
21484to refer to tasks in the following commands.
21485
21486@item break @var{linespec} task @var{taskid}
21487@itemx break @var{linespec} task @var{taskid} if @dots{}
21488@cindex Breakpoints and tasks
21489These commands are like the @code{break @dots{} thread @dots{}}.
21490@var{linespec} specifies source lines.
21491
21492Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21493to specify that you only want @code{GDB} to stop the program when a
21494particular Ada task reaches this breakpoint. @var{taskid} is one of the
21495numeric task identifiers assigned by @code{GDB}, shown in the first
21496column of the @samp{info tasks} display.
21497
21498If you do not specify @samp{task @var{taskid}} when you set a
21499breakpoint, the breakpoint applies to @emph{all} tasks of your
21500program.
21501
21502You can use the @code{task} qualifier on conditional breakpoints as
21503well; in this case, place @samp{task @var{taskid}} before the
21504breakpoint condition (before the @code{if}).
21505
21506@item task @var{taskno}
21507@cindex Task switching
21508
21509This command allows to switch to the task referred by @var{taskno}. In
21510particular, This allows to browse the backtrace of the specified
21511task. It is advised to switch back to the original task before
21512continuing execution otherwise the scheduling of the program may be
21513perturbed.
21514@end table
21515
21516@noindent
21517For more detailed information on the tasking support,
21518see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21519
21520@node Debugging Generic Units
21521@section Debugging Generic Units
21522@cindex Debugging Generic Units
21523@cindex Generics
21524
21525@noindent
21526GNAT always uses code expansion for generic instantiation. This means that
21527each time an instantiation occurs, a complete copy of the original code is
21528made, with appropriate substitutions of formals by actuals.
21529
21530It is not possible to refer to the original generic entities in
21531@code{GDB}, but it is always possible to debug a particular instance of
21532a generic, by using the appropriate expanded names. For example, if we have
21533
21534@smallexample @c ada
21535@group
21536@cartouche
21537procedure g is
21538
21539   generic package k is
21540      procedure kp (v1 : in out integer);
21541   end k;
21542
21543   package body k is
21544      procedure kp (v1 : in out integer) is
21545      begin
21546         v1 := v1 + 1;
21547      end kp;
21548   end k;
21549
21550   package k1 is new k;
21551   package k2 is new k;
21552
21553   var : integer := 1;
21554
21555begin
21556   k1.kp (var);
21557   k2.kp (var);
21558   k1.kp (var);
21559   k2.kp (var);
21560end;
21561@end cartouche
21562@end group
21563@end smallexample
21564
21565@noindent
21566Then to break on a call to procedure kp in the k2 instance, simply
21567use the command:
21568
21569@smallexample
21570(gdb) break g.k2.kp
21571@end smallexample
21572
21573@noindent
21574When the breakpoint occurs, you can step through the code of the
21575instance in the normal manner and examine the values of local variables, as for
21576other units.
21577
21578@node Remote Debugging with gdbserver
21579@section Remote Debugging with gdbserver
21580@cindex Remote Debugging with gdbserver
21581
21582@noindent
21583On platforms where gdbserver is supported, it is possible to use this tool
21584to debug your application remotely.  This can be useful in situations
21585where the program needs to be run on a target host that is different
21586from the host used for development, particularly when the target has
21587a limited amount of resources (either CPU and/or memory).
21588
21589To do so, start your program using gdbserver on the target machine.
21590gdbserver then automatically suspends the execution of your program
21591at its entry point, waiting for a debugger to connect to it.  The
21592following commands starts an application and tells gdbserver to
21593wait for a connection with the debugger on localhost port 4444.
21594
21595@smallexample
21596$ gdbserver localhost:4444 program
21597Process program created; pid = 5685
21598Listening on port 4444
21599@end smallexample
21600
21601Once gdbserver has started listening, we can tell the debugger to establish
21602a connection with this gdbserver, and then start the same debugging session
21603as if the program was being debugged on the same host, directly under
21604the control of GDB.
21605
21606@smallexample
21607$ gdb program
21608(gdb) target remote targethost:4444
21609Remote debugging using targethost:4444
216100x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21611(gdb) b foo.adb:3
21612Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21613(gdb) continue
21614Continuing.
21615
21616Breakpoint 1, foo () at foo.adb:4
216174       end foo;
21618@end smallexample
21619
21620It is also possible to use gdbserver to attach to an already running
21621program, in which case the execution of that program is simply suspended
21622until the connection between the debugger and gdbserver is established.
21623
21624For more information on how to use gdbserver, @ref{Top, Server, Using
21625the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
21626for gdbserver on x86-linux, x86-windows and x86_64-linux.
21627
21628@node GNAT Abnormal Termination or Failure to Terminate
21629@section GNAT Abnormal Termination or Failure to Terminate
21630@cindex GNAT Abnormal Termination or Failure to Terminate
21631
21632@noindent
21633When presented with programs that contain serious errors in syntax
21634or semantics,
21635GNAT may on rare occasions  experience problems in operation, such
21636as aborting with a
21637segmentation fault or illegal memory access, raising an internal
21638exception, terminating abnormally, or failing to terminate at all.
21639In such cases, you can activate
21640various features of GNAT that can help you pinpoint the construct in your
21641program that is the likely source of the problem.
21642
21643The following strategies are presented in increasing order of
21644difficulty, corresponding to your experience in using GNAT and your
21645familiarity with compiler internals.
21646
21647@enumerate
21648@item
21649Run @command{gcc} with the @option{-gnatf}. This first
21650switch causes all errors on a given line to be reported. In its absence,
21651only the first error on a line is displayed.
21652
21653The @option{-gnatdO} switch causes errors to be displayed as soon as they
21654are encountered, rather than after compilation is terminated. If GNAT
21655terminates prematurely or goes into an infinite loop, the last error
21656message displayed may help to pinpoint the culprit.
21657
21658@item
21659Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21660mode, @command{gcc} produces ongoing information about the progress of the
21661compilation and provides the name of each procedure as code is
21662generated. This switch allows you to find which Ada procedure was being
21663compiled when it encountered a code generation problem.
21664
21665@item
21666@cindex @option{-gnatdc} switch
21667Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21668switch that does for the front-end what @option{^-v^VERBOSE^} does
21669for the back end. The system prints the name of each unit,
21670either a compilation unit or nested unit, as it is being analyzed.
21671@item
21672Finally, you can start
21673@code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21674front-end of GNAT, and can be run independently (normally it is just
21675called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21676would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21677@code{where} command is the first line of attack; the variable
21678@code{lineno} (seen by @code{print lineno}), used by the second phase of
21679@code{gnat1} and by the @command{gcc} backend, indicates the source line at
21680which the execution stopped, and @code{input_file name} indicates the name of
21681the source file.
21682@end enumerate
21683
21684@node Naming Conventions for GNAT Source Files
21685@section Naming Conventions for GNAT Source Files
21686
21687@noindent
21688In order to examine the workings of the GNAT system, the following
21689brief description of its organization may be helpful:
21690
21691@itemize @bullet
21692@item
21693Files with prefix @file{^sc^SC^} contain the lexical scanner.
21694
21695@item
21696All files prefixed with @file{^par^PAR^} are components of the parser. The
21697numbers correspond to chapters of the Ada Reference Manual. For example,
21698parsing of select statements can be found in @file{par-ch9.adb}.
21699
21700@item
21701All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21702numbers correspond to chapters of the Ada standard. For example, all
21703issues involving context clauses can be found in @file{sem_ch10.adb}. In
21704addition, some features of the language require sufficient special processing
21705to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21706dynamic dispatching, etc.
21707
21708@item
21709All files prefixed with @file{^exp^EXP^} perform normalization and
21710expansion of the intermediate representation (abstract syntax tree, or AST).
21711these files use the same numbering scheme as the parser and semantics files.
21712For example, the construction of record initialization procedures is done in
21713@file{exp_ch3.adb}.
21714
21715@item
21716The files prefixed with @file{^bind^BIND^} implement the binder, which
21717verifies the consistency of the compilation, determines an order of
21718elaboration, and generates the bind file.
21719
21720@item
21721The files @file{atree.ads} and @file{atree.adb} detail the low-level
21722data structures used by the front-end.
21723
21724@item
21725The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21726the abstract syntax tree as produced by the parser.
21727
21728@item
21729The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21730all entities, computed during semantic analysis.
21731
21732@item
21733Library management issues are dealt with in files with prefix
21734@file{^lib^LIB^}.
21735
21736@item
21737@findex Ada
21738@cindex Annex A
21739Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21740defined in Annex A.
21741
21742@item
21743@findex Interfaces
21744@cindex Annex B
21745Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21746defined in Annex B.
21747
21748@item
21749@findex System
21750Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21751both language-defined children and GNAT run-time routines.
21752
21753@item
21754@findex GNAT
21755Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21756general-purpose packages, fully documented in their specs. All
21757the other @file{.c} files are modifications of common @command{gcc} files.
21758@end itemize
21759
21760@node Getting Internal Debugging Information
21761@section Getting Internal Debugging Information
21762
21763@noindent
21764Most compilers have internal debugging switches and modes. GNAT
21765does also, except GNAT internal debugging switches and modes are not
21766secret. A summary and full description of all the compiler and binder
21767debug flags are in the file @file{debug.adb}. You must obtain the
21768sources of the compiler to see the full detailed effects of these flags.
21769
21770The switches that print the source of the program (reconstructed from
21771the internal tree) are of general interest for user programs, as are the
21772options to print
21773the full internal tree, and the entity table (the symbol table
21774information). The reconstructed source provides a readable version of the
21775program after the front-end has completed analysis and  expansion,
21776and is useful when studying the performance of specific constructs.
21777For example, constraint checks are indicated, complex aggregates
21778are replaced with loops and assignments, and tasking primitives
21779are replaced with run-time calls.
21780
21781@node Stack Traceback
21782@section Stack Traceback
21783@cindex traceback
21784@cindex stack traceback
21785@cindex stack unwinding
21786
21787@noindent
21788Traceback is a mechanism to display the sequence of subprogram calls that
21789leads to a specified execution point in a program. Often (but not always)
21790the execution point is an instruction at which an exception has been raised.
21791This mechanism is also known as @i{stack unwinding} because it obtains
21792its information by scanning the run-time stack and recovering the activation
21793records of all active subprograms. Stack unwinding is one of the most
21794important tools for program debugging.
21795
21796The first entry stored in traceback corresponds to the deepest calling level,
21797that is to say the subprogram currently executing the instruction
21798from which we want to obtain the traceback.
21799
21800Note that there is no runtime performance penalty when stack traceback
21801is enabled, and no exception is raised during program execution.
21802
21803@menu
21804* Non-Symbolic Traceback::
21805* Symbolic Traceback::
21806@end menu
21807
21808@node Non-Symbolic Traceback
21809@subsection Non-Symbolic Traceback
21810@cindex traceback, non-symbolic
21811
21812@noindent
21813Note: this feature is not supported on all platforms. See
21814@file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21815platforms.
21816
21817@menu
21818* Tracebacks From an Unhandled Exception::
21819* Tracebacks From Exception Occurrences (non-symbolic)::
21820* Tracebacks From Anywhere in a Program (non-symbolic)::
21821@end menu
21822
21823@node Tracebacks From an Unhandled Exception
21824@subsubsection Tracebacks From an Unhandled Exception
21825
21826@noindent
21827A runtime non-symbolic traceback is a list of addresses of call instructions.
21828To enable this feature you must use the @option{-E}
21829@code{gnatbind}'s option. With this option a stack traceback is stored as part
21830of exception information. You can retrieve this information using the
21831@code{addr2line} tool.
21832
21833Here is a simple example:
21834
21835@smallexample @c ada
21836@cartouche
21837procedure STB is
21838
21839   procedure P1 is
21840   begin
21841      raise Constraint_Error;
21842   end P1;
21843
21844   procedure P2 is
21845   begin
21846      P1;
21847   end P2;
21848
21849begin
21850   P2;
21851end STB;
21852@end cartouche
21853@end smallexample
21854
21855@smallexample
21856$ gnatmake stb -bargs -E
21857$ stb
21858
21859Execution terminated by unhandled exception
21860Exception name: CONSTRAINT_ERROR
21861Message: stb.adb:5
21862Call stack traceback locations:
218630x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21864@end smallexample
21865
21866@noindent
21867As we see the traceback lists a sequence of addresses for the unhandled
21868exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21869guess that this exception come from procedure P1. To translate these
21870addresses into the source lines where the calls appear, the
21871@code{addr2line} tool, described below, is invaluable. The use of this tool
21872requires the program to be compiled with debug information.
21873
21874@smallexample
21875$ gnatmake -g stb -bargs -E
21876$ stb
21877
21878Execution terminated by unhandled exception
21879Exception name: CONSTRAINT_ERROR
21880Message: stb.adb:5
21881Call stack traceback locations:
218820x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21883
21884$ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21885   0x4011f1 0x77e892a4
21886
2188700401373 at d:/stb/stb.adb:5
218880040138B at d:/stb/stb.adb:10
218890040139C at d:/stb/stb.adb:14
2189000401335 at d:/stb/b~stb.adb:104
21891004011C4 at /build/@dots{}/crt1.c:200
21892004011F1 at /build/@dots{}/crt1.c:222
2189377E892A4 in ?? at ??:0
21894@end smallexample
21895
21896@noindent
21897The @code{addr2line} tool has several other useful options:
21898
21899@table @code
21900@item --functions
21901to get the function name corresponding to any location
21902
21903@item --demangle=gnat
21904to use the gnat decoding mode for the function names. Note that
21905for binutils version 2.9.x the option is simply @option{--demangle}.
21906@end table
21907
21908@smallexample
21909$ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21910   0x40139c 0x401335 0x4011c4 0x4011f1
21911
2191200401373 in stb.p1 at d:/stb/stb.adb:5
219130040138B in stb.p2 at d:/stb/stb.adb:10
219140040139C in stb at d:/stb/stb.adb:14
2191500401335 in main at d:/stb/b~stb.adb:104
21916004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21917004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21918@end smallexample
21919
21920@noindent
21921From this traceback we can see that the exception was raised in
21922@file{stb.adb} at line 5, which was reached from a procedure call in
21923@file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21924which contains the call to the main program.
21925@xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21926and the output will vary from platform to platform.
21927
21928It is also possible to use @code{GDB} with these traceback addresses to debug
21929the program. For example, we can break at a given code location, as reported
21930in the stack traceback:
21931
21932@smallexample
21933$ gdb -nw stb
21934@ifclear vms
21935@noindent
21936Furthermore, this feature is not implemented inside Windows DLL. Only
21937the non-symbolic traceback is reported in this case.
21938@end ifclear
21939
21940(gdb) break *0x401373
21941Breakpoint 1 at 0x401373: file stb.adb, line 5.
21942@end smallexample
21943
21944@noindent
21945It is important to note that the stack traceback addresses
21946do not change when debug information is included. This is particularly useful
21947because it makes it possible to release software without debug information (to
21948minimize object size), get a field report that includes a stack traceback
21949whenever an internal bug occurs, and then be able to retrieve the sequence
21950of calls with the same program compiled with debug information.
21951
21952@node Tracebacks From Exception Occurrences (non-symbolic)
21953@subsubsection Tracebacks From Exception Occurrences
21954
21955@noindent
21956Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21957The stack traceback is attached to the exception information string, and can
21958be retrieved in an exception handler within the Ada program, by means of the
21959Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21960
21961@smallexample @c ada
21962with Ada.Text_IO;
21963with Ada.Exceptions;
21964
21965procedure STB is
21966
21967   use Ada;
21968   use Ada.Exceptions;
21969
21970   procedure P1 is
21971      K : Positive := 1;
21972   begin
21973      K := K - 1;
21974   exception
21975      when E : others =>
21976         Text_IO.Put_Line (Exception_Information (E));
21977   end P1;
21978
21979   procedure P2 is
21980   begin
21981      P1;
21982   end P2;
21983
21984begin
21985   P2;
21986end STB;
21987@end smallexample
21988
21989@noindent
21990This program will output:
21991
21992@smallexample
21993$ stb
21994
21995Exception name: CONSTRAINT_ERROR
21996Message: stb.adb:12
21997Call stack traceback locations:
219980x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21999@end smallexample
22000
22001@node Tracebacks From Anywhere in a Program (non-symbolic)
22002@subsubsection Tracebacks From Anywhere in a Program
22003
22004@noindent
22005It is also possible to retrieve a stack traceback from anywhere in a
22006program. For this you need to
22007use the @code{GNAT.Traceback} API. This package includes a procedure called
22008@code{Call_Chain} that computes a complete stack traceback, as well as useful
22009display procedures described below. It is not necessary to use the
22010@option{-E gnatbind} option in this case, because the stack traceback mechanism
22011is invoked explicitly.
22012
22013@noindent
22014In the following example we compute a traceback at a specific location in
22015the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22016convert addresses to strings:
22017
22018@smallexample @c ada
22019with Ada.Text_IO;
22020with GNAT.Traceback;
22021with GNAT.Debug_Utilities;
22022
22023procedure STB is
22024
22025   use Ada;
22026   use GNAT;
22027   use GNAT.Traceback;
22028
22029   procedure P1 is
22030      TB  : Tracebacks_Array (1 .. 10);
22031      --  We are asking for a maximum of 10 stack frames.
22032      Len : Natural;
22033      --  Len will receive the actual number of stack frames returned.
22034   begin
22035      Call_Chain (TB, Len);
22036
22037      Text_IO.Put ("In STB.P1 : ");
22038
22039      for K in 1 .. Len loop
22040         Text_IO.Put (Debug_Utilities.Image (TB (K)));
22041         Text_IO.Put (' ');
22042      end loop;
22043
22044      Text_IO.New_Line;
22045   end P1;
22046
22047   procedure P2 is
22048   begin
22049      P1;
22050   end P2;
22051
22052begin
22053   P2;
22054end STB;
22055@end smallexample
22056
22057@smallexample
22058$ gnatmake -g stb
22059$ stb
22060
22061In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
2206216#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22063@end smallexample
22064
22065@noindent
22066You can then get further information by invoking the @code{addr2line}
22067tool as described earlier (note that the hexadecimal addresses
22068need to be specified in C format, with a leading ``0x'').
22069
22070@node Symbolic Traceback
22071@subsection Symbolic Traceback
22072@cindex traceback, symbolic
22073
22074@noindent
22075A symbolic traceback is a stack traceback in which procedure names are
22076associated with each code location.
22077
22078@noindent
22079Note that this feature is not supported on all platforms. See
22080@file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22081list of currently supported platforms.
22082
22083@noindent
22084Note that the symbolic traceback requires that the program be compiled
22085with debug information. If it is not compiled with debug information
22086only the non-symbolic information will be valid.
22087
22088@menu
22089* Tracebacks From Exception Occurrences (symbolic)::
22090* Tracebacks From Anywhere in a Program (symbolic)::
22091@end menu
22092
22093@node Tracebacks From Exception Occurrences (symbolic)
22094@subsubsection Tracebacks From Exception Occurrences
22095
22096@smallexample @c ada
22097with Ada.Text_IO;
22098with GNAT.Traceback.Symbolic;
22099
22100procedure STB is
22101
22102   procedure P1 is
22103   begin
22104      raise Constraint_Error;
22105   end P1;
22106
22107   procedure P2 is
22108   begin
22109      P1;
22110   end P2;
22111
22112   procedure P3 is
22113   begin
22114      P2;
22115   end P3;
22116
22117begin
22118   P3;
22119exception
22120   when E : others =>
22121      Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22122end STB;
22123@end smallexample
22124
22125@smallexample
22126$ gnatmake -g .\stb -bargs -E
22127$ stb
22128
221290040149F in stb.p1 at stb.adb:8
22130004014B7 in stb.p2 at stb.adb:13
22131004014CF in stb.p3 at stb.adb:18
22132004015DD in ada.stb at stb.adb:22
2213300401461 in main at b~stb.adb:168
22134004011C4 in __mingw_CRTStartup at crt1.c:200
22135004011F1 in mainCRTStartup at crt1.c:222
2213677E892A4 in ?? at ??:0
22137@end smallexample
22138
22139@noindent
22140In the above example the ``.\'' syntax in the @command{gnatmake} command
22141is currently required by @command{addr2line} for files that are in
22142the current working directory.
22143Moreover, the exact sequence of linker options may vary from platform
22144to platform.
22145The above @option{-largs} section is for Windows platforms. By contrast,
22146under Unix there is no need for the @option{-largs} section.
22147Differences across platforms are due to details of linker implementation.
22148
22149@node Tracebacks From Anywhere in a Program (symbolic)
22150@subsubsection Tracebacks From Anywhere in a Program
22151
22152@noindent
22153It is possible to get a symbolic stack traceback
22154from anywhere in a program, just as for non-symbolic tracebacks.
22155The first step is to obtain a non-symbolic
22156traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22157information. Here is an example:
22158
22159@smallexample @c ada
22160with Ada.Text_IO;
22161with GNAT.Traceback;
22162with GNAT.Traceback.Symbolic;
22163
22164procedure STB is
22165
22166   use Ada;
22167   use GNAT.Traceback;
22168   use GNAT.Traceback.Symbolic;
22169
22170   procedure P1 is
22171      TB  : Tracebacks_Array (1 .. 10);
22172      --  We are asking for a maximum of 10 stack frames.
22173      Len : Natural;
22174      --  Len will receive the actual number of stack frames returned.
22175   begin
22176      Call_Chain (TB, Len);
22177      Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22178   end P1;
22179
22180   procedure P2 is
22181   begin
22182      P1;
22183   end P2;
22184
22185begin
22186   P2;
22187end STB;
22188@end smallexample
22189
22190@c ******************************
22191@ifset vms
22192@node Compatibility with HP Ada
22193@chapter Compatibility with HP Ada
22194@cindex Compatibility
22195
22196@noindent
22197@cindex DEC Ada
22198@cindex HP Ada
22199@cindex Compatibility between GNAT and HP Ada
22200This chapter compares HP Ada (formerly known as ``DEC Ada'')
22201for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22202GNAT is highly compatible
22203with HP Ada, and it should generally be straightforward to port code
22204from the HP Ada environment to GNAT. However, there are a few language
22205and implementation differences of which the user must be aware. These
22206differences are discussed in this chapter. In
22207addition, the operating environment and command structure for the
22208compiler are different, and these differences are also discussed.
22209
22210For further details on these and other compatibility issues,
22211see Appendix E of the HP publication
22212@cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22213
22214Except where otherwise indicated, the description of GNAT for OpenVMS
22215applies to both the Alpha and I64 platforms.
22216
22217For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22218I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22219
22220The discussion in this chapter addresses specifically the implementation
22221of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22222of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22223GNAT always follows the Alpha implementation.
22224
22225For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22226attributes are recognized, although only a subset of them can sensibly
22227be implemented.  The description of pragmas in
22228@xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
22229indicates whether or not they are applicable to non-VMS systems.
22230
22231@menu
22232* Ada Language Compatibility::
22233* Differences in the Definition of Package System::
22234* Language-Related Features::
22235* The Package STANDARD::
22236* The Package SYSTEM::
22237* Tasking and Task-Related Features::
22238* Pragmas and Pragma-Related Features::
22239* Library of Predefined Units::
22240* Bindings::
22241* Main Program Definition::
22242* Implementation-Defined Attributes::
22243* Compiler and Run-Time Interfacing::
22244* Program Compilation and Library Management::
22245* Input-Output::
22246* Implementation Limits::
22247* Tools and Utilities::
22248@end menu
22249
22250@node Ada Language Compatibility
22251@section Ada Language Compatibility
22252
22253@noindent
22254GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22255for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22256with Ada 83, and therefore Ada 83 programs will compile
22257and run under GNAT with
22258no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22259provides details on specific incompatibilities.
22260
22261GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22262as well as the pragma @code{ADA_83}, to force the compiler to
22263operate in Ada 83 mode. This mode does not guarantee complete
22264conformance to Ada 83, but in practice is sufficient to
22265eliminate most sources of incompatibilities.
22266In particular, it eliminates the recognition of the
22267additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22268in Ada 83 programs is legal, and handles the cases of packages
22269with optional bodies, and generics that instantiate unconstrained
22270types without the use of @code{(<>)}.
22271
22272@node Differences in the Definition of Package System
22273@section Differences in the Definition of Package @code{System}
22274
22275@noindent
22276An Ada compiler is allowed to add
22277implementation-dependent declarations to package @code{System}.
22278In normal mode,
22279GNAT does not take advantage of this permission, and the version of
22280@code{System} provided by GNAT exactly matches that defined in the Ada
22281Reference Manual.
22282
22283However, HP Ada adds an extensive set of declarations to package
22284@code{System},
22285as fully documented in the HP Ada manuals. To minimize changes required
22286for programs that make use of these extensions, GNAT provides the pragma
22287@code{Extend_System} for extending the definition of package System. By using:
22288@cindex pragma @code{Extend_System}
22289@cindex @code{Extend_System} pragma
22290
22291@smallexample @c ada
22292@group
22293@cartouche
22294pragma Extend_System (Aux_DEC);
22295@end cartouche
22296@end group
22297@end smallexample
22298
22299@noindent
22300the set of definitions in @code{System} is extended to include those in
22301package @code{System.Aux_DEC}.
22302@cindex @code{System.Aux_DEC} package
22303@cindex @code{Aux_DEC} package (child of @code{System})
22304These definitions are incorporated directly into package @code{System},
22305as though they had been declared there. For a
22306list of the declarations added, see the spec of this package,
22307which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22308@cindex @file{s-auxdec.ads} file
22309The pragma @code{Extend_System} is a configuration pragma, which means that
22310it can be placed in the file @file{gnat.adc}, so that it will automatically
22311apply to all subsequent compilations. See @ref{Configuration Pragmas},
22312for further details.
22313
22314An alternative approach that avoids the use of the non-standard
22315@code{Extend_System} pragma is to add a context clause to the unit that
22316references these facilities:
22317
22318@smallexample @c ada
22319@cartouche
22320with System.Aux_DEC;
22321use  System.Aux_DEC;
22322@end cartouche
22323@end smallexample
22324
22325@noindent
22326The effect is not quite semantically identical to incorporating
22327the declarations directly into package @code{System},
22328but most programs will not notice a difference
22329unless they use prefix notation (e.g.@: @code{System.Integer_8})
22330to reference the entities directly in package @code{System}.
22331For units containing such references,
22332the prefixes must either be removed, or the pragma @code{Extend_System}
22333must be used.
22334
22335@node Language-Related Features
22336@section Language-Related Features
22337
22338@noindent
22339The following sections highlight differences in types,
22340representations of types, operations, alignment, and
22341related topics.
22342
22343@menu
22344* Integer Types and Representations::
22345* Floating-Point Types and Representations::
22346* Pragmas Float_Representation and Long_Float::
22347* Fixed-Point Types and Representations::
22348* Record and Array Component Alignment::
22349* Address Clauses::
22350* Other Representation Clauses::
22351@end menu
22352
22353@node Integer Types and Representations
22354@subsection Integer Types and Representations
22355
22356@noindent
22357The set of predefined integer types is identical in HP Ada and GNAT.
22358Furthermore the representation of these integer types is also identical,
22359including the capability of size clauses forcing biased representation.
22360
22361In addition,
22362HP Ada for OpenVMS Alpha systems has defined the
22363following additional integer types in package @code{System}:
22364
22365@itemize @bullet
22366
22367@item
22368@code{INTEGER_8}
22369
22370@item
22371@code{INTEGER_16}
22372
22373@item
22374@code{INTEGER_32}
22375
22376@item
22377@code{INTEGER_64}
22378
22379@item
22380@code{LARGEST_INTEGER}
22381@end itemize
22382
22383@noindent
22384In GNAT, the first four of these types may be obtained from the
22385standard Ada package @code{Interfaces}.
22386Alternatively, by use of the pragma @code{Extend_System}, identical
22387declarations can be referenced directly in package @code{System}.
22388On both GNAT and HP Ada, the maximum integer size is 64 bits.
22389
22390@node Floating-Point Types and Representations
22391@subsection Floating-Point Types and Representations
22392@cindex Floating-Point types
22393
22394@noindent
22395The set of predefined floating-point types is identical in HP Ada and GNAT.
22396Furthermore the representation of these floating-point
22397types is also identical. One important difference is that the default
22398representation for HP Ada is @code{VAX_Float}, but the default representation
22399for GNAT is IEEE.
22400
22401Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22402pragma @code{Float_Representation} as described in the HP Ada
22403documentation.
22404For example, the declarations:
22405
22406@smallexample @c ada
22407@cartouche
22408type F_Float is digits 6;
22409pragma Float_Representation (VAX_Float, F_Float);
22410@end cartouche
22411@end smallexample
22412
22413@noindent
22414declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22415format.
22416This set of declarations actually appears in @code{System.Aux_DEC},
22417which contains
22418the full set of additional floating-point declarations provided in
22419the HP Ada version of package @code{System}.
22420This and similar declarations may be accessed in a user program
22421by using pragma @code{Extend_System}. The use of this
22422pragma, and the related pragma @code{Long_Float} is described in further
22423detail in the following section.
22424
22425@node Pragmas Float_Representation and Long_Float
22426@subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22427
22428@noindent
22429HP Ada provides the pragma @code{Float_Representation}, which
22430acts as a program library switch to allow control over
22431the internal representation chosen for the predefined
22432floating-point types declared in the package @code{Standard}.
22433The format of this pragma is as follows:
22434
22435@smallexample @c ada
22436@cartouche
22437pragma Float_Representation(VAX_Float | IEEE_Float);
22438@end cartouche
22439@end smallexample
22440
22441@noindent
22442This pragma controls the representation of floating-point
22443types as follows:
22444
22445@itemize @bullet
22446@item
22447@code{VAX_Float} specifies that floating-point
22448types are represented by default with the VAX system hardware types
22449@code{F-floating}, @code{D-floating}, @code{G-floating}.
22450Note that the @code{H-floating}
22451type was available only on VAX systems, and is not available
22452in either HP Ada or GNAT.
22453
22454@item
22455@code{IEEE_Float} specifies that floating-point
22456types are represented by default with the IEEE single and
22457double floating-point types.
22458@end itemize
22459
22460@noindent
22461GNAT provides an identical implementation of the pragma
22462@code{Float_Representation}, except that it functions as a
22463configuration pragma. Note that the
22464notion of configuration pragma corresponds closely to the
22465HP Ada notion of a program library switch.
22466
22467When no pragma is used in GNAT, the default is @code{IEEE_Float},
22468which is different
22469from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22470predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22471advisable to change the format of numbers passed to standard library
22472routines, and if necessary explicit type conversions may be needed.
22473
22474The use of @code{IEEE_Float} is recommended in GNAT since it is more
22475efficient, and (given that it conforms to an international standard)
22476potentially more portable.
22477The situation in which @code{VAX_Float} may be useful is in interfacing
22478to existing code and data that expect the use of @code{VAX_Float}.
22479In such a situation use the predefined @code{VAX_Float}
22480types in package @code{System}, as extended by
22481@code{Extend_System}. For example, use @code{System.F_Float}
22482to specify the 32-bit @code{F-Float} format.
22483
22484@noindent
22485On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22486to allow control over the internal representation chosen
22487for the predefined type @code{Long_Float} and for floating-point
22488type declarations with digits specified in the range 7 .. 15.
22489The format of this pragma is as follows:
22490
22491@smallexample @c ada
22492@cartouche
22493pragma Long_Float (D_FLOAT | G_FLOAT);
22494@end cartouche
22495@end smallexample
22496
22497@node Fixed-Point Types and Representations
22498@subsection Fixed-Point Types and Representations
22499
22500@noindent
22501On HP Ada for OpenVMS Alpha systems, rounding is
22502away from zero for both positive and negative numbers.
22503Therefore, @code{+0.5} rounds to @code{1},
22504and @code{-0.5} rounds to @code{-1}.
22505
22506On GNAT the results of operations
22507on fixed-point types are in accordance with the Ada
22508rules. In particular, results of operations on decimal
22509fixed-point types are truncated.
22510
22511@node Record and Array Component Alignment
22512@subsection Record and Array Component Alignment
22513
22514@noindent
22515On HP Ada for OpenVMS Alpha, all non-composite components
22516are aligned on natural boundaries. For example, 1-byte
22517components are aligned on byte boundaries, 2-byte
22518components on 2-byte boundaries, 4-byte components on 4-byte
22519byte boundaries, and so on. The OpenVMS Alpha hardware
22520runs more efficiently with naturally aligned data.
22521
22522On GNAT, alignment rules are compatible
22523with HP Ada for OpenVMS Alpha.
22524
22525@node Address Clauses
22526@subsection Address Clauses
22527
22528@noindent
22529In HP Ada and GNAT, address clauses are supported for
22530objects and imported subprograms.
22531The predefined type @code{System.Address} is a private type
22532in both compilers on Alpha OpenVMS, with the same representation
22533(it is simply a machine pointer). Addition, subtraction, and comparison
22534operations are available in the standard Ada package
22535@code{System.Storage_Elements}, or in package @code{System}
22536if it is extended to include @code{System.Aux_DEC} using a
22537pragma @code{Extend_System} as previously described.
22538
22539Note that code that @code{with}'s both this extended package @code{System}
22540and the package @code{System.Storage_Elements} should not @code{use}
22541both packages, or ambiguities will result. In general it is better
22542not to mix these two sets of facilities. The Ada package was
22543designed specifically to provide the kind of features that HP Ada
22544adds directly to package @code{System}.
22545
22546The type @code{System.Address} is a 64-bit integer type in GNAT for
22547I64 OpenVMS.  For more information,
22548see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22549
22550GNAT is compatible with HP Ada in its handling of address
22551clauses, except for some limitations in
22552the form of address clauses for composite objects with
22553initialization. Such address clauses are easily replaced
22554by the use of an explicitly-defined constant as described
22555in the Ada Reference Manual (13.1(22)). For example, the sequence
22556of declarations:
22557
22558@smallexample @c ada
22559@cartouche
22560X, Y : Integer := Init_Func;
22561Q : String (X .. Y) := "abc";
22562@dots{}
22563for Q'Address use Compute_Address;
22564@end cartouche
22565@end smallexample
22566
22567@noindent
22568will be rejected by GNAT, since the address cannot be computed at the time
22569that @code{Q} is declared. To achieve the intended effect, write instead:
22570
22571@smallexample @c ada
22572@group
22573@cartouche
22574X, Y : Integer := Init_Func;
22575Q_Address : constant Address := Compute_Address;
22576Q : String (X .. Y) := "abc";
22577@dots{}
22578for Q'Address use Q_Address;
22579@end cartouche
22580@end group
22581@end smallexample
22582
22583@noindent
22584which will be accepted by GNAT (and other Ada compilers), and is also
22585compatible with Ada 83. A fuller description of the restrictions
22586on address specifications is found in @ref{Top, GNAT Reference Manual,
22587About This Guide, gnat_rm, GNAT Reference Manual}.
22588
22589@node Other Representation Clauses
22590@subsection Other Representation Clauses
22591
22592@noindent
22593GNAT implements in a compatible manner all the representation
22594clauses supported by HP Ada. In addition, GNAT
22595implements the representation clause forms that were introduced in Ada 95,
22596including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22597
22598@node The Package STANDARD
22599@section The Package @code{STANDARD}
22600
22601@noindent
22602The package @code{STANDARD}, as implemented by HP Ada, is fully
22603described in the @cite{Ada Reference Manual} and in the
22604@cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22605package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22606
22607In addition, HP Ada supports the Latin-1 character set in
22608the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22609in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22610the type @code{WIDE_CHARACTER}.
22611
22612The floating-point types supported by GNAT are those
22613supported by HP Ada, but the defaults are different, and are controlled by
22614pragmas. See @ref{Floating-Point Types and Representations}, for details.
22615
22616@node The Package SYSTEM
22617@section The Package @code{SYSTEM}
22618
22619@noindent
22620HP Ada provides a specific version of the package
22621@code{SYSTEM} for each platform on which the language is implemented.
22622For the complete spec of the package @code{SYSTEM}, see
22623Appendix F of the @cite{HP Ada Language Reference Manual}.
22624
22625On HP Ada, the package @code{SYSTEM} includes the following conversion
22626functions:
22627@itemize @bullet
22628@item @code{TO_ADDRESS(INTEGER)}
22629
22630@item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22631
22632@item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22633
22634@item @code{TO_INTEGER(ADDRESS)}
22635
22636@item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22637
22638@item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22639functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22640@end itemize
22641
22642@noindent
22643By default, GNAT supplies a version of @code{SYSTEM} that matches
22644the definition given in the @cite{Ada Reference Manual}.
22645This
22646is a subset of the HP system definitions, which is as
22647close as possible to the original definitions. The only difference
22648is that the definition of @code{SYSTEM_NAME} is different:
22649
22650@smallexample @c ada
22651@cartouche
22652type Name is (SYSTEM_NAME_GNAT);
22653System_Name : constant Name := SYSTEM_NAME_GNAT;
22654@end cartouche
22655@end smallexample
22656
22657@noindent
22658Also, GNAT adds the Ada declarations for
22659@code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22660
22661However, the use of the following pragma causes GNAT
22662to extend the definition of package @code{SYSTEM} so that it
22663encompasses the full set of HP-specific extensions,
22664including the functions listed above:
22665
22666@smallexample @c ada
22667@cartouche
22668pragma Extend_System (Aux_DEC);
22669@end cartouche
22670@end smallexample
22671
22672@noindent
22673The pragma @code{Extend_System} is a configuration pragma that
22674is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22675Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22676
22677HP Ada does not allow the recompilation of the package
22678@code{SYSTEM}. Instead HP Ada provides several pragmas
22679(@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22680to modify values in the package @code{SYSTEM}.
22681On OpenVMS Alpha systems, the pragma
22682@code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22683its single argument.
22684
22685GNAT does permit the recompilation of package @code{SYSTEM} using
22686the special switch @option{-gnatg}, and this switch can be used if
22687it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22688not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22689or @code{MEMORY_SIZE} by any other means.
22690
22691On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22692enumeration literal @code{SYSTEM_NAME_GNAT}.
22693
22694The definitions provided by the use of
22695
22696@smallexample @c ada
22697pragma Extend_System (AUX_Dec);
22698@end smallexample
22699
22700@noindent
22701are virtually identical to those provided by the HP Ada 83 package
22702@code{SYSTEM}. One important difference is that the name of the
22703@code{TO_ADDRESS}
22704function for type @code{UNSIGNED_LONGWORD} is changed to
22705@code{TO_ADDRESS_LONG}.
22706@xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22707discussion of why this change was necessary.
22708
22709@noindent
22710The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22711is in fact
22712an extension to Ada 83 not strictly compatible with the reference manual.
22713GNAT, in order to be exactly compatible with the standard,
22714does not provide this capability. In HP Ada 83, the
22715point of this definition is to deal with a call like:
22716
22717@smallexample @c ada
22718TO_ADDRESS (16#12777#);
22719@end smallexample
22720
22721@noindent
22722Normally, according to Ada 83 semantics, one would expect this to be
22723ambiguous, since it matches both the @code{INTEGER} and
22724@code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22725However, in HP Ada 83, there is no ambiguity, since the
22726definition using @i{universal_integer} takes precedence.
22727
22728In GNAT, since the version with @i{universal_integer} cannot be supplied,
22729it is
22730not possible to be 100% compatible. Since there are many programs using
22731numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22732GNAT was
22733to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22734so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22735
22736@smallexample @c ada
22737function To_Address (X : Integer) return Address;
22738pragma Pure_Function (To_Address);
22739
22740function To_Address_Long (X : Unsigned_Longword) return Address;
22741pragma Pure_Function (To_Address_Long);
22742@end smallexample
22743
22744@noindent
22745This means that programs using @code{TO_ADDRESS} for
22746@code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22747
22748@node Tasking and Task-Related Features
22749@section Tasking and Task-Related Features
22750
22751@noindent
22752This section compares the treatment of tasking in GNAT
22753and in HP Ada for OpenVMS Alpha.
22754The GNAT description applies to both Alpha and I64 OpenVMS.
22755For detailed information on tasking in
22756HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22757relevant run-time reference manual.
22758
22759@menu
22760* Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22761* Assigning Task IDs::
22762* Task IDs and Delays::
22763* Task-Related Pragmas::
22764* Scheduling and Task Priority::
22765* The Task Stack::
22766* External Interrupts::
22767@end menu
22768
22769@node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22770@subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22771
22772@noindent
22773On OpenVMS Alpha systems, each Ada task (except a passive
22774task) is implemented as a single stream of execution
22775that is created and managed by the kernel. On these
22776systems, HP Ada tasking support is based on DECthreads,
22777an implementation of the POSIX standard for threads.
22778
22779Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22780code that calls DECthreads routines can be used together.
22781The interaction between Ada tasks and DECthreads routines
22782can have some benefits. For example when on OpenVMS Alpha,
22783HP Ada can call C code that is already threaded.
22784
22785GNAT uses the facilities of DECthreads,
22786and Ada tasks are mapped to threads.
22787
22788@node Assigning Task IDs
22789@subsection Assigning Task IDs
22790
22791@noindent
22792The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22793the environment task that executes the main program. On
22794OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22795that have been created but are not yet activated.
22796
22797On OpenVMS Alpha systems, task IDs are assigned at
22798activation. On GNAT systems, task IDs are also assigned at
22799task creation but do not have the same form or values as
22800task ID values in HP Ada. There is no null task, and the
22801environment task does not have a specific task ID value.
22802
22803@node Task IDs and Delays
22804@subsection Task IDs and Delays
22805
22806@noindent
22807On OpenVMS Alpha systems, tasking delays are implemented
22808using Timer System Services. The Task ID is used for the
22809identification of the timer request (the @code{REQIDT} parameter).
22810If Timers are used in the application take care not to use
22811@code{0} for the identification, because cancelling such a timer
22812will cancel all timers and may lead to unpredictable results.
22813
22814@node Task-Related Pragmas
22815@subsection Task-Related Pragmas
22816
22817@noindent
22818Ada supplies the pragma @code{TASK_STORAGE}, which allows
22819specification of the size of the guard area for a task
22820stack. (The guard area forms an area of memory that has no
22821read or write access and thus helps in the detection of
22822stack overflow.) On OpenVMS Alpha systems, if the pragma
22823@code{TASK_STORAGE} specifies a value of zero, a minimal guard
22824area is created. In the absence of a pragma @code{TASK_STORAGE},
22825a default guard area is created.
22826
22827GNAT supplies the following task-related pragmas:
22828
22829@itemize @bullet
22830@item  @code{TASK_INFO}
22831
22832This pragma appears within a task definition and
22833applies to the task in which it appears. The argument
22834must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
22835
22836@item  @code{TASK_STORAGE}
22837
22838GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22839Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22840@code{SUPPRESS}, and @code{VOLATILE}.
22841@end itemize
22842@node Scheduling and Task Priority
22843@subsection Scheduling and Task Priority
22844
22845@noindent
22846HP Ada implements the Ada language requirement that
22847when two tasks are eligible for execution and they have
22848different priorities, the lower priority task does not
22849execute while the higher priority task is waiting. The HP
22850Ada Run-Time Library keeps a task running until either the
22851task is suspended or a higher priority task becomes ready.
22852
22853On OpenVMS Alpha systems, the default strategy is round-
22854robin with preemption. Tasks of equal priority take turns
22855at the processor. A task is run for a certain period of
22856time and then placed at the tail of the ready queue for
22857its priority level.
22858
22859HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22860which can be used to enable or disable round-robin
22861scheduling of tasks with the same priority.
22862See the relevant HP Ada run-time reference manual for
22863information on using the pragmas to control HP Ada task
22864scheduling.
22865
22866GNAT follows the scheduling rules of Annex D (Real-Time
22867Annex) of the @cite{Ada Reference Manual}. In general, this
22868scheduling strategy is fully compatible with HP Ada
22869although it provides some additional constraints (as
22870fully documented in Annex D).
22871GNAT implements time slicing control in a manner compatible with
22872HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22873are identical to the HP Ada 83 pragma of the same name.
22874Note that it is not possible to mix GNAT tasking and
22875HP Ada 83 tasking in the same program, since the two run-time
22876libraries are not compatible.
22877
22878@node The Task Stack
22879@subsection The Task Stack
22880
22881@noindent
22882In HP Ada, a task stack is allocated each time a
22883non-passive task is activated. As soon as the task is
22884terminated, the storage for the task stack is deallocated.
22885If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22886a default stack size is used. Also, regardless of the size
22887specified, some additional space is allocated for task
22888management purposes. On OpenVMS Alpha systems, at least
22889one page is allocated.
22890
22891GNAT handles task stacks in a similar manner. In accordance with
22892the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22893an alternative method for controlling the task stack size.
22894The specification of the attribute @code{T'STORAGE_SIZE} is also
22895supported in a manner compatible with HP Ada.
22896
22897@node External Interrupts
22898@subsection External Interrupts
22899
22900@noindent
22901On HP Ada, external interrupts can be associated with task entries.
22902GNAT is compatible with HP Ada in its handling of external interrupts.
22903
22904@node Pragmas and Pragma-Related Features
22905@section Pragmas and Pragma-Related Features
22906
22907@noindent
22908Both HP Ada and GNAT supply all language-defined pragmas
22909as specified by the Ada 83 standard. GNAT also supplies all
22910language-defined pragmas introduced by Ada 95 and Ada 2005.
22911In addition, GNAT implements the implementation-defined pragmas
22912from HP Ada 83.
22913
22914@itemize @bullet
22915@item  @code{AST_ENTRY}
22916
22917@item  @code{COMMON_OBJECT}
22918
22919@item  @code{COMPONENT_ALIGNMENT}
22920
22921@item  @code{EXPORT_EXCEPTION}
22922
22923@item  @code{EXPORT_FUNCTION}
22924
22925@item  @code{EXPORT_OBJECT}
22926
22927@item  @code{EXPORT_PROCEDURE}
22928
22929@item  @code{EXPORT_VALUED_PROCEDURE}
22930
22931@item  @code{FLOAT_REPRESENTATION}
22932
22933@item  @code{IDENT}
22934
22935@item  @code{IMPORT_EXCEPTION}
22936
22937@item  @code{IMPORT_FUNCTION}
22938
22939@item  @code{IMPORT_OBJECT}
22940
22941@item  @code{IMPORT_PROCEDURE}
22942
22943@item  @code{IMPORT_VALUED_PROCEDURE}
22944
22945@item  @code{INLINE_GENERIC}
22946
22947@item  @code{INTERFACE_NAME}
22948
22949@item  @code{LONG_FLOAT}
22950
22951@item  @code{MAIN_STORAGE}
22952
22953@item  @code{PASSIVE}
22954
22955@item  @code{PSECT_OBJECT}
22956
22957@item  @code{SHARE_GENERIC}
22958
22959@item  @code{SUPPRESS_ALL}
22960
22961@item  @code{TASK_STORAGE}
22962
22963@item  @code{TIME_SLICE}
22964
22965@item  @code{TITLE}
22966@end itemize
22967
22968@noindent
22969These pragmas are all fully implemented, with the exception of @code{TITLE},
22970@code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22971recognized, but which have no
22972effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22973use of Ada protected objects. In GNAT, all generics are inlined.
22974
22975Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22976a separate subprogram specification which must appear before the
22977subprogram body.
22978
22979GNAT also supplies a number of implementation-defined pragmas including the
22980following:
22981
22982@itemize @bullet
22983@item  @code{ABORT_DEFER}
22984
22985@item  @code{ADA_83}
22986
22987@item  @code{ADA_95}
22988
22989@item  @code{ADA_05}
22990
22991@item  @code{Ada_2005}
22992
22993@item  @code{Ada_12}
22994
22995@item  @code{Ada_2012}
22996
22997@item  @code{ALLOW_INTEGER_ADDRESS}
22998
22999@item  @code{ANNOTATE}
23000
23001@item  @code{ASSERT}
23002
23003@item  @code{C_PASS_BY_COPY}
23004
23005@item  @code{CPP_CLASS}
23006
23007@item  @code{CPP_CONSTRUCTOR}
23008
23009@item  @code{CPP_DESTRUCTOR}
23010
23011@item  @code{DEBUG}
23012
23013@item  @code{EXTEND_SYSTEM}
23014
23015@item  @code{LINKER_ALIAS}
23016
23017@item  @code{LINKER_SECTION}
23018
23019@item  @code{MACHINE_ATTRIBUTE}
23020
23021@item  @code{NO_RETURN}
23022
23023@item  @code{PURE_FUNCTION}
23024
23025@item  @code{SOURCE_FILE_NAME}
23026
23027@item  @code{SOURCE_REFERENCE}
23028
23029@item  @code{TASK_INFO}
23030
23031@item  @code{UNCHECKED_UNION}
23032
23033@item  @code{UNIMPLEMENTED_UNIT}
23034
23035@item  @code{UNIVERSAL_DATA}
23036
23037@item  @code{UNSUPPRESS}
23038
23039@item  @code{WARNINGS}
23040
23041@item  @code{WEAK_EXTERNAL}
23042@end itemize
23043
23044@noindent
23045For full details on these and other GNAT implementation-defined pragmas,
23046see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
23047Manual}.
23048
23049@menu
23050* Restrictions on the Pragma INLINE::
23051* Restrictions on the Pragma INTERFACE::
23052* Restrictions on the Pragma SYSTEM_NAME::
23053@end menu
23054
23055@node Restrictions on the Pragma INLINE
23056@subsection Restrictions on Pragma @code{INLINE}
23057
23058@noindent
23059HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23060@itemize @bullet
23061@item  Parameters cannot have a task type.
23062
23063@item  Function results cannot be task types, unconstrained
23064array types, or unconstrained types with discriminants.
23065
23066@item  Bodies cannot declare the following:
23067@itemize @bullet
23068@item  Subprogram body or stub (imported subprogram is allowed)
23069
23070@item  Tasks
23071
23072@item  Generic declarations
23073
23074@item  Instantiations
23075
23076@item  Exceptions
23077
23078@item  Access types (types derived from access types allowed)
23079
23080@item  Array or record types
23081
23082@item  Dependent tasks
23083
23084@item  Direct recursive calls of subprogram or containing
23085subprogram, directly or via a renaming
23086
23087@end itemize
23088@end itemize
23089
23090@noindent
23091In GNAT, the only restriction on pragma @code{INLINE} is that the
23092body must occur before the call if both are in the same
23093unit, and the size must be appropriately small. There are
23094no other specific restrictions which cause subprograms to
23095be incapable of being inlined.
23096
23097@node  Restrictions on the Pragma INTERFACE
23098@subsection  Restrictions on Pragma @code{INTERFACE}
23099
23100@noindent
23101The following restrictions on pragma @code{INTERFACE}
23102are enforced by both HP Ada and GNAT:
23103@itemize @bullet
23104@item  Languages accepted: Ada, Bliss, C, Fortran, Default.
23105Default is the default on OpenVMS Alpha systems.
23106
23107@item  Parameter passing: Language specifies default
23108mechanisms but can be overridden with an @code{EXPORT} pragma.
23109
23110@itemize @bullet
23111@item  Ada: Use internal Ada rules.
23112
23113@item  Bliss, C: Parameters must be mode @code{in}; cannot be
23114record or task type. Result cannot be a string, an
23115array, or a record.
23116
23117@item  Fortran: Parameters cannot have a task type. Result cannot
23118be a string, an array, or a record.
23119@end itemize
23120@end itemize
23121
23122@noindent
23123GNAT is entirely upwards compatible with HP Ada, and in addition allows
23124record parameters for all languages.
23125
23126@node  Restrictions on the Pragma SYSTEM_NAME
23127@subsection  Restrictions on Pragma @code{SYSTEM_NAME}
23128
23129@noindent
23130For HP Ada for OpenVMS Alpha, the enumeration literal
23131for the type @code{NAME} is @code{OPENVMS_AXP}.
23132In GNAT, the enumeration
23133literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23134
23135@node  Library of Predefined Units
23136@section  Library of Predefined Units
23137
23138@noindent
23139A library of predefined units is provided as part of the
23140HP Ada and GNAT implementations. HP Ada does not provide
23141the package @code{MACHINE_CODE} but instead recommends importing
23142assembler code.
23143
23144The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23145units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23146version.
23147The HP Ada Predefined Library units are modified to remove post-Ada 83
23148incompatibilities and to make them interoperable with GNAT
23149(@pxref{Changes to DECLIB}, for details).
23150The units are located in the @file{DECLIB} directory.
23151
23152The GNAT RTL is contained in
23153the @file{ADALIB} directory, and
23154the default search path is set up to find @code{DECLIB} units in preference
23155to @code{ADALIB} units with the same name (@code{TEXT_IO},
23156@code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23157
23158@menu
23159* Changes to DECLIB::
23160@end menu
23161
23162@node Changes to DECLIB
23163@subsection Changes to @code{DECLIB}
23164
23165@noindent
23166The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23167compatibility are minor and include the following:
23168
23169@itemize @bullet
23170@item  Adjusting the location of pragmas and record representation
23171clauses to obey Ada 95 (and thus Ada 2005) rules
23172
23173@item  Adding the proper notation to generic formal parameters
23174that take unconstrained types in instantiation
23175
23176@item  Adding pragma @code{ELABORATE_BODY} to package specs
23177that have package bodies not otherwise allowed
23178
23179@item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23180``@code{PROTECTD}''.
23181Currently these are found only in the @code{STARLET} package spec.
23182
23183@item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23184where the address size is constrained to 32 bits.
23185@end itemize
23186
23187@noindent
23188None of the above changes is visible to users.
23189
23190@node Bindings
23191@section Bindings
23192
23193@noindent
23194On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23195@itemize @bullet
23196
23197@item  Command Language Interpreter (CLI interface)
23198
23199@item  DECtalk Run-Time Library (DTK interface)
23200
23201@item  Librarian utility routines (LBR interface)
23202
23203@item  General Purpose Run-Time Library (LIB interface)
23204
23205@item  Math Run-Time Library (MTH interface)
23206
23207@item  National Character Set Run-Time Library (NCS interface)
23208
23209@item  Compiled Code Support Run-Time Library (OTS interface)
23210
23211@item  Parallel Processing Run-Time Library (PPL interface)
23212
23213@item  Screen Management Run-Time Library (SMG interface)
23214
23215@item  Sort Run-Time Library (SOR interface)
23216
23217@item  String Run-Time Library (STR interface)
23218
23219@item STARLET System Library
23220@findex Starlet
23221
23222@item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
23223
23224@item  X Windows Toolkit (XT interface)
23225
23226@item  X/Motif Version 1.1.3 and 1.2 (XM interface)
23227@end itemize
23228
23229@noindent
23230GNAT provides implementations of these HP bindings in the @code{DECLIB}
23231directory, on both the Alpha and I64 OpenVMS platforms.
23232
23233The X components of DECLIB compatibility package are located in a separate
23234library, called XDECGNAT, which is not linked with by default; this library
23235must be explicitly linked with any application that makes use of any X facilities,
23236with a command similar to
23237
23238@code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
23239
23240The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23241in the
23242HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23243A pragma @code{Linker_Options} has been added to packages @code{Xm},
23244@code{Xt}, and @code{X_Lib}
23245causing the default X/Motif sharable image libraries to be linked in. This
23246is done via options files named @file{xm.opt}, @file{xt.opt}, and
23247@file{x_lib.opt} (also located in the @file{DECLIB} directory).
23248
23249It may be necessary to edit these options files to update or correct the
23250library names if, for example, the newer X/Motif bindings from
23251@file{ADA$EXAMPLES}
23252had been (previous to installing GNAT) copied and renamed to supersede the
23253default @file{ADA$PREDEFINED} versions.
23254
23255@menu
23256* Shared Libraries and Options Files::
23257* Interfaces to C::
23258@end menu
23259
23260@node Shared Libraries and Options Files
23261@subsection Shared Libraries and Options Files
23262
23263@noindent
23264When using the HP Ada
23265predefined X and Motif bindings, the linking with their sharable images is
23266done automatically by @command{GNAT LINK}.
23267When using other X and Motif bindings, you need
23268to add the corresponding sharable images to the command line for
23269@code{GNAT LINK}. When linking with shared libraries, or with
23270@file{.OPT} files, you must
23271also add them to the command line for @command{GNAT LINK}.
23272
23273A shared library to be used with GNAT is built in the same way as other
23274libraries under VMS. The VMS Link command can be used in standard fashion.
23275
23276@node Interfaces to C
23277@subsection Interfaces to C
23278
23279@noindent
23280HP Ada
23281provides the following Ada types and operations:
23282
23283@itemize @bullet
23284@item C types package (@code{C_TYPES})
23285
23286@item C strings (@code{C_TYPES.NULL_TERMINATED})
23287
23288@item Other_types (@code{SHORT_INT})
23289@end itemize
23290
23291@noindent
23292Interfacing to C with GNAT, you can use the above approach
23293described for HP Ada or the facilities of Annex B of
23294the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23295@code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23296information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
23297
23298The @option{-gnatF} qualifier forces default and explicit
23299@code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23300to be uppercased for compatibility with the default behavior
23301of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23302
23303@node Main Program Definition
23304@section Main Program Definition
23305
23306@noindent
23307The following section discusses differences in the
23308definition of main programs on HP Ada and GNAT.
23309On HP Ada, main programs are defined to meet the
23310following conditions:
23311@itemize @bullet
23312@item  Procedure with no formal parameters (returns @code{0} upon
23313normal completion)
23314
23315@item  Procedure with no formal parameters (returns @code{42} when
23316an unhandled exception is raised)
23317
23318@item  Function with no formal parameters whose returned value
23319is of a discrete type
23320
23321@item  Procedure with one @code{out} formal of a discrete type for
23322which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
23323
23324@end itemize
23325
23326@noindent
23327When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23328a main function or main procedure returns a discrete
23329value whose size is less than 64 bits (32 on VAX systems),
23330the value is zero- or sign-extended as appropriate.
23331On GNAT, main programs are defined as follows:
23332@itemize @bullet
23333@item  Must be a non-generic, parameterless subprogram that
23334is either a procedure or function returning an Ada
23335@code{STANDARD.INTEGER} (the predefined type)
23336
23337@item  Cannot be a generic subprogram or an instantiation of a
23338generic subprogram
23339@end itemize
23340
23341@node Implementation-Defined Attributes
23342@section Implementation-Defined Attributes
23343
23344@noindent
23345GNAT provides all HP Ada implementation-defined
23346attributes.
23347
23348@node Compiler and Run-Time Interfacing
23349@section Compiler and Run-Time Interfacing
23350
23351@noindent
23352HP Ada provides the following qualifiers to pass options to the linker
23353(ACS LINK):
23354@itemize @bullet
23355@item  @option{/WAIT} and @option{/SUBMIT}
23356
23357@item  @option{/COMMAND}
23358
23359@item  @option{/@r{[}NO@r{]}MAP}
23360
23361@item  @option{/OUTPUT=@var{file-spec}}
23362
23363@item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23364@end itemize
23365
23366@noindent
23367To pass options to the linker, GNAT provides the following
23368switches:
23369
23370@itemize @bullet
23371@item   @option{/EXECUTABLE=@var{exec-name}}
23372
23373@item   @option{/VERBOSE}
23374
23375@item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23376@end itemize
23377
23378@noindent
23379For more information on these switches, see
23380@ref{Switches for gnatlink}.
23381In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23382to control optimization. HP Ada also supplies the
23383following pragmas:
23384@itemize @bullet
23385@item  @code{OPTIMIZE}
23386
23387@item  @code{INLINE}
23388
23389@item  @code{INLINE_GENERIC}
23390
23391@item  @code{SUPPRESS_ALL}
23392
23393@item  @code{PASSIVE}
23394@end itemize
23395
23396@noindent
23397In GNAT, optimization is controlled strictly by command
23398line parameters, as described in the corresponding section of this guide.
23399The HP pragmas for control of optimization are
23400recognized but ignored.
23401
23402Note that in GNAT, the default is optimization off, whereas in HP Ada
23403the default is that optimization is turned on.
23404
23405@node Program Compilation and Library Management
23406@section Program Compilation and Library Management
23407
23408@noindent
23409HP Ada and GNAT provide a comparable set of commands to
23410build programs. HP Ada also provides a program library,
23411which is a concept that does not exist on GNAT. Instead,
23412GNAT provides directories of sources that are compiled as
23413needed.
23414
23415The following table summarizes
23416the HP Ada commands and provides
23417equivalent GNAT commands. In this table, some GNAT
23418equivalents reflect the fact that GNAT does not use the
23419concept of a program library. Instead, it uses a model
23420in which collections of source and object files are used
23421in a manner consistent with other languages like C and
23422Fortran. Therefore, standard system file commands are used
23423to manipulate these elements. Those GNAT commands are marked with
23424an asterisk.
23425Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23426
23427@need 1500
23428@multitable @columnfractions .35 .65
23429
23430@item @emph{HP Ada Command}
23431@tab @emph{GNAT Equivalent / Description}
23432
23433@item @command{ADA}
23434@tab @command{GNAT COMPILE}@*
23435Invokes the compiler to compile one or more Ada source files.
23436
23437@item @command{ACS ATTACH}@*
23438@tab [No equivalent]@*
23439Switches control of terminal from current process running the program
23440library manager.
23441
23442@item @command{ACS CHECK}
23443@tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23444Forms the execution closure of one
23445or more compiled units and checks completeness and currency.
23446
23447@item @command{ACS COMPILE}
23448@tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23449Forms the execution closure of one or
23450more specified units, checks completeness and currency,
23451identifies units that have revised source files, compiles same,
23452and recompiles units that are or will become obsolete.
23453Also completes incomplete generic instantiations.
23454
23455@item @command{ACS COPY FOREIGN}
23456@tab Copy (*)@*
23457Copies a foreign object file into the program library as a
23458library unit body.
23459
23460@item @command{ACS COPY UNIT}
23461@tab Copy (*)@*
23462Copies a compiled unit from one program library to another.
23463
23464@item @command{ACS CREATE LIBRARY}
23465@tab Create /directory (*)@*
23466Creates a program library.
23467
23468@item @command{ACS CREATE SUBLIBRARY}
23469@tab Create /directory (*)@*
23470Creates a program sublibrary.
23471
23472@item @command{ACS DELETE LIBRARY}
23473@tab @*
23474Deletes a program library and its contents.
23475
23476@item @command{ACS DELETE SUBLIBRARY}
23477@tab @*
23478Deletes a program sublibrary and its contents.
23479
23480@item @command{ACS DELETE UNIT}
23481@tab Delete file (*)@*
23482On OpenVMS systems, deletes one or more compiled units from
23483the current program library.
23484
23485@item @command{ACS DIRECTORY}
23486@tab Directory (*)@*
23487On OpenVMS systems, lists units contained in the current
23488program library.
23489
23490@item @command{ACS ENTER FOREIGN}
23491@tab Copy (*)@*
23492Allows the import of a foreign body as an Ada library
23493spec and enters a reference to a pointer.
23494
23495@item @command{ACS ENTER UNIT}
23496@tab Copy (*)@*
23497Enters a reference (pointer) from the current program library to
23498a unit compiled into another program library.
23499
23500@item @command{ACS EXIT}
23501@tab [No equivalent]@*
23502Exits from the program library manager.
23503
23504@item @command{ACS EXPORT}
23505@tab Copy (*)@*
23506Creates an object file that contains system-specific object code
23507for one or more units. With GNAT, object files can simply be copied
23508into the desired directory.
23509
23510@item @command{ACS EXTRACT SOURCE}
23511@tab Copy (*)@*
23512Allows access to the copied source file for each Ada compilation unit
23513
23514@item @command{ACS HELP}
23515@tab @command{HELP GNAT}@*
23516Provides online help.
23517
23518@item @command{ACS LINK}
23519@tab @command{GNAT LINK}@*
23520Links an object file containing Ada units into an executable file.
23521
23522@item @command{ACS LOAD}
23523@tab Copy (*)@*
23524Loads (partially compiles) Ada units into the program library.
23525Allows loading a program from a collection of files into a library
23526without knowing the relationship among units.
23527
23528@item @command{ACS MERGE}
23529@tab Copy (*)@*
23530Merges into the current program library, one or more units from
23531another library where they were modified.
23532
23533@item @command{ACS RECOMPILE}
23534@tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23535Recompiles from   external or copied source files any obsolete
23536unit in the closure. Also, completes any incomplete generic
23537instantiations.
23538
23539@item @command{ACS REENTER}
23540@tab @command{GNAT MAKE}@*
23541Reenters current references to units compiled after last entered
23542with the @command{ACS ENTER UNIT} command.
23543
23544@item @command{ACS SET LIBRARY}
23545@tab Set default (*)@*
23546Defines a program library to be the compilation context as well
23547as the target library for compiler output and commands in general.
23548
23549@item @command{ACS SET PRAGMA}
23550@tab Edit @file{gnat.adc} (*)@*
23551Redefines specified  values of the library characteristics
23552@code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23553and @code{Float_Representation}.
23554
23555@item @command{ACS SET SOURCE}
23556@tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23557Defines the source file search list for the @command{ACS COMPILE} command.
23558
23559@item @command{ACS SHOW LIBRARY}
23560@tab Directory (*)@*
23561Lists information about one or more program libraries.
23562
23563@item @command{ACS SHOW PROGRAM}
23564@tab [No equivalent]@*
23565Lists information about the execution closure of one or
23566more units in the program library.
23567
23568@item @command{ACS SHOW SOURCE}
23569@tab Show logical @code{ADA_INCLUDE_PATH}@*
23570Shows the source file search used when compiling units.
23571
23572@item @command{ACS SHOW VERSION}
23573@tab Compile with @option{VERBOSE} option
23574Displays the version number of the compiler and program library
23575manager used.
23576
23577@item @command{ACS SPAWN}
23578@tab [No equivalent]@*
23579Creates a subprocess of the current process (same as @command{DCL SPAWN}
23580command).
23581
23582@item @command{ACS VERIFY}
23583@tab [No equivalent]@*
23584Performs a series of consistency checks on a program library to
23585determine whether the library structure and library files are in
23586valid form.
23587@end multitable
23588
23589@noindent
23590
23591@node Input-Output
23592@section Input-Output
23593
23594@noindent
23595On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23596Management Services (RMS) to perform operations on
23597external files.
23598
23599@noindent
23600HP Ada and GNAT predefine an identical set of input-
23601output packages. To make the use of the
23602generic @code{TEXT_IO} operations more convenient, HP Ada
23603provides predefined library packages that instantiate the
23604integer and floating-point operations for the predefined
23605integer and floating-point types as shown in the following table.
23606
23607@multitable @columnfractions .45 .55
23608@item @emph{Package Name} @tab Instantiation
23609
23610@item @code{INTEGER_TEXT_IO}
23611@tab @code{INTEGER_IO(INTEGER)}
23612
23613@item @code{SHORT_INTEGER_TEXT_IO}
23614@tab @code{INTEGER_IO(SHORT_INTEGER)}
23615
23616@item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23617@tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23618
23619@item @code{FLOAT_TEXT_IO}
23620@tab @code{FLOAT_IO(FLOAT)}
23621
23622@item @code{LONG_FLOAT_TEXT_IO}
23623@tab @code{FLOAT_IO(LONG_FLOAT)}
23624@end multitable
23625
23626@noindent
23627The HP Ada predefined packages and their operations
23628are implemented using OpenVMS Alpha files and input-output
23629facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23630Familiarity with the following is recommended:
23631@itemize @bullet
23632@item  RMS file organizations and access methods
23633
23634@item  OpenVMS file specifications and directories
23635
23636@item  OpenVMS File Definition Language (FDL)
23637@end itemize
23638
23639@noindent
23640GNAT provides I/O facilities that are completely
23641compatible with HP Ada. The distribution includes the
23642standard HP Ada versions of all I/O packages, operating
23643in a manner compatible with HP Ada. In particular, the
23644following packages are by default the HP Ada (Ada 83)
23645versions of these packages rather than the renamings
23646suggested in Annex J of the Ada Reference Manual:
23647@itemize @bullet
23648@item  @code{TEXT_IO}
23649
23650@item  @code{SEQUENTIAL_IO}
23651
23652@item  @code{DIRECT_IO}
23653@end itemize
23654
23655@noindent
23656The use of the standard child package syntax (for
23657example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23658packages.
23659GNAT provides HP-compatible predefined instantiations
23660of the @code{TEXT_IO} packages, and also
23661provides the standard predefined instantiations required
23662by the @cite{Ada Reference Manual}.
23663
23664For further information on how GNAT interfaces to the file
23665system or how I/O is implemented in programs written in
23666mixed languages, see @ref{Implementation of the Standard I/O,,,
23667gnat_rm, GNAT Reference Manual}.
23668This chapter covers the following:
23669@itemize @bullet
23670@item  Standard I/O packages
23671
23672@item  @code{FORM} strings
23673
23674@item  @code{ADA.DIRECT_IO}
23675
23676@item  @code{ADA.SEQUENTIAL_IO}
23677
23678@item  @code{ADA.TEXT_IO}
23679
23680@item  Stream pointer positioning
23681
23682@item  Reading and writing non-regular files
23683
23684@item  @code{GET_IMMEDIATE}
23685
23686@item  Treating @code{TEXT_IO} files as streams
23687
23688@item  Shared files
23689
23690@item  Open modes
23691@end itemize
23692
23693@node Implementation Limits
23694@section Implementation Limits
23695
23696@noindent
23697The following table lists implementation limits for HP Ada
23698and GNAT systems.
23699@multitable @columnfractions .60 .20 .20
23700@sp 1
23701@item  @emph{Compilation Parameter}
23702@tab   @emph{HP Ada}
23703@tab   @emph{GNAT}
23704@sp 1
23705
23706@item  In a subprogram or entry  declaration, maximum number of
23707formal parameters that are of an unconstrained record type
23708@tab   32
23709@tab   No set limit
23710@sp 1
23711
23712@item  Maximum identifier length (number of characters)
23713@tab   255
23714@tab   32766
23715@sp 1
23716
23717@item  Maximum number of characters in a source line
23718@tab   255
23719@tab   32766
23720@sp 1
23721
23722@item  Maximum collection size   (number of bytes)
23723@tab   2**31-1
23724@tab   2**31-1
23725@sp 1
23726
23727@item  Maximum number of discriminants for a record type
23728@tab   245
23729@tab   No set limit
23730@sp 1
23731
23732@item  Maximum number of formal parameters in an entry or
23733subprogram declaration
23734@tab   246
23735@tab    No set limit
23736@sp 1
23737
23738@item  Maximum number of dimensions in an array type
23739@tab   255
23740@tab   No set limit
23741@sp 1
23742
23743@item  Maximum number of library  units and subunits in a compilation.
23744@tab   4095
23745@tab   No set limit
23746@sp 1
23747
23748@item  Maximum number of library units and subunits in an execution.
23749@tab   16383
23750@tab   No set limit
23751@sp 1
23752
23753@item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23754or @code{PSECT_OBJECT}
23755@tab   32757
23756@tab   No set limit
23757@sp 1
23758
23759@item  Maximum number of enumeration literals in an enumeration type
23760definition
23761@tab   65535
23762@tab   No set limit
23763@sp 1
23764
23765@item  Maximum number of lines in a source file
23766@tab   65534
23767@tab   No set limit
23768@sp 1
23769
23770@item  Maximum number of bits in any object
23771@tab   2**31-1
23772@tab   2**31-1
23773@sp 1
23774
23775@item  Maximum size of the static portion of a stack frame (approximate)
23776@tab   2**31-1
23777@tab   2**31-1
23778@end multitable
23779
23780@node Tools and Utilities
23781@section Tools and Utilities
23782
23783@noindent
23784The following table lists some of the OpenVMS development tools
23785available for HP Ada, and the corresponding tools for
23786use with @value{EDITION} on Alpha and I64 platforms.
23787Aside from the debugger, all the OpenVMS tools identified are part
23788of the DECset package.
23789
23790@iftex
23791@c Specify table in TeX since Texinfo does a poor job
23792@tex
23793\smallskip
23794\smallskip
23795\settabs\+Language-Sensitive Editor\quad
23796   &Product with HP Ada\quad
23797   &\cr
23798\+\it Tool
23799   &\it Product with HP Ada
23800   & \it Product with @value{EDITION}\cr
23801\smallskip
23802\+Code Management System
23803   &HP CMS
23804   & HP CMS\cr
23805\smallskip
23806\+Language-Sensitive Editor
23807   &HP LSE
23808   & emacs or HP LSE (Alpha)\cr
23809\+
23810   &
23811   & HP LSE (I64)\cr
23812\smallskip
23813\+Debugger
23814   &OpenVMS Debug
23815   & gdb (Alpha),\cr
23816\+
23817   &
23818   & OpenVMS Debug (I64)\cr
23819\smallskip
23820\+Source Code Analyzer /
23821   &HP SCA
23822   & GNAT XREF\cr
23823\+Cross Referencer
23824   &
23825   &\cr
23826\smallskip
23827\+Test Manager
23828   &HP Digital Test
23829   & HP DTM\cr
23830\+
23831   &Manager (DTM)
23832   &\cr
23833\smallskip
23834\+Performance and
23835   & HP PCA
23836   & HP PCA\cr
23837\+Coverage Analyzer
23838   &
23839   &\cr
23840\smallskip
23841\+Module Management
23842   & HP MMS
23843   & Not applicable\cr
23844\+ System
23845   &
23846   &\cr
23847\smallskip
23848\smallskip
23849@end tex
23850@end iftex
23851
23852@ifnottex
23853@c This is the Texinfo version of the table.  It renders poorly in pdf, hence
23854@c the TeX version above for the printed version
23855@flushleft
23856@c @multitable @columnfractions .3 .4 .4
23857@multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23858@item @i{Tool}
23859@tab @i{Tool with HP Ada}
23860@tab @i{Tool with @value{EDITION}}
23861@item Code Management@*System
23862@tab HP CMS
23863@tab HP CMS
23864@item Language-Sensitive@*Editor
23865@tab HP LSE
23866@tab emacs or HP LSE (Alpha)
23867@item
23868@tab
23869@tab HP LSE (I64)
23870@item Debugger
23871@tab OpenVMS Debug
23872@tab gdb (Alpha),
23873@item
23874@tab
23875@tab OpenVMS Debug (I64)
23876@item Source Code Analyzer /@*Cross Referencer
23877@tab HP SCA
23878@tab GNAT XREF
23879@item Test Manager
23880@tab HP Digital Test@*Manager (DTM)
23881@tab HP DTM
23882@item Performance and@*Coverage Analyzer
23883@tab HP PCA
23884@tab HP PCA
23885@item Module Management@*System
23886@tab HP MMS
23887@tab Not applicable
23888@end multitable
23889@end flushleft
23890@end ifnottex
23891
23892@end ifset
23893
23894@c **************************************
23895@node Platform-Specific Information for the Run-Time Libraries
23896@appendix Platform-Specific Information for the Run-Time Libraries
23897@cindex Tasking and threads libraries
23898@cindex Threads libraries and tasking
23899@cindex Run-time libraries (platform-specific information)
23900
23901@noindent
23902The GNAT run-time implementation may vary with respect to both the
23903underlying threads library and the exception handling scheme.
23904For threads support, one or more of the following are supplied:
23905@itemize @bullet
23906@item @b{native threads library}, a binding to the thread package from
23907the underlying operating system
23908
23909@item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23910POSIX thread package
23911@end itemize
23912
23913@noindent
23914For exception handling, either or both of two models are supplied:
23915@itemize @bullet
23916@item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23917Most programs should experience a substantial speed improvement by
23918being compiled with a ZCX run-time.
23919This is especially true for
23920tasking applications or applications with many exception handlers.}
23921@cindex Zero-Cost Exceptions
23922@cindex ZCX (Zero-Cost Exceptions)
23923which uses binder-generated tables that
23924are interrogated at run time to locate a handler
23925
23926@item @b{setjmp / longjmp} (``SJLJ''),
23927@cindex setjmp/longjmp Exception Model
23928@cindex SJLJ (setjmp/longjmp Exception Model)
23929which uses dynamically-set data to establish
23930the set of handlers
23931@end itemize
23932
23933@noindent
23934This appendix summarizes which combinations of threads and exception support
23935are supplied on various GNAT platforms.
23936It then shows how to select a particular library either
23937permanently or temporarily,
23938explains the properties of (and tradeoffs among) the various threads
23939libraries, and provides some additional
23940information about several specific platforms.
23941
23942@menu
23943* Summary of Run-Time Configurations::
23944* Specifying a Run-Time Library::
23945* Choosing the Scheduling Policy::
23946* Solaris-Specific Considerations::
23947* Linux-Specific Considerations::
23948* AIX-Specific Considerations::
23949* RTX-Specific Considerations::
23950* HP-UX-Specific Considerations::
23951@end menu
23952
23953@node Summary of Run-Time Configurations
23954@section Summary of Run-Time Configurations
23955
23956@multitable @columnfractions .30 .70
23957@item @b{alpha-openvms}
23958@item @code{@ @ }@i{rts-native (default)}
23959@item @code{@ @ @ @ }Tasking    @tab native VMS threads
23960@item @code{@ @ @ @ }Exceptions @tab ZCX
23961@*
23962@item @code{@ @ }@i{rts-sjlj}
23963@item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
23964@item @code{@ @ @ @ }Exceptions @tab SJLJ
23965@*
23966@item @b{ia64-hp_linux}
23967@item @code{@ @ }@i{rts-native (default)}
23968@item @code{@ @ @ @ }Tasking    @tab pthread library
23969@item @code{@ @ @ @ }Exceptions @tab ZCX
23970@*
23971@item @b{ia64-hpux}
23972@item @code{@ @ }@i{rts-native (default)}
23973@item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23974@item @code{@ @ @ @ }Exceptions @tab SJLJ
23975@*
23976@item @b{ia64-openvms}
23977@item @code{@ @ }@i{rts-native (default)}
23978@item @code{@ @ @ @ }Tasking    @tab native VMS threads
23979@item @code{@ @ @ @ }Exceptions @tab ZCX
23980@*
23981@item @b{ia64-sgi_linux}
23982@item @code{@ @ }@i{rts-native (default)}
23983@item @code{@ @ @ @ }Tasking    @tab pthread library
23984@item @code{@ @ @ @ }Exceptions @tab ZCX
23985@*
23986@item @b{pa-hpux}
23987@item @code{@ @ }@i{rts-native (default)}
23988@item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23989@item @code{@ @ @ @ }Exceptions @tab ZCX
23990@*
23991@item @code{@ @ }@i{rts-sjlj}
23992@item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23993@item @code{@ @ @ @ }Exceptions @tab SJLJ
23994@*
23995@item @b{ppc-aix}
23996@item @code{@ @ }@i{rts-native (default)}
23997@item @code{@ @ @ @ }Tasking    @tab native AIX threads
23998@item @code{@ @ @ @ }Exceptions @tab ZCX
23999@*
24000@item @code{@ @ }@i{rts-sjlj}
24001@item @code{@ @ @ @ }Tasking    @tab native AIX threads
24002@item @code{@ @ @ @ }Exceptions @tab SJLJ
24003@*
24004@item @b{ppc-darwin}
24005@item @code{@ @ }@i{rts-native (default)}
24006@item @code{@ @ @ @ }Tasking    @tab native MacOS threads
24007@item @code{@ @ @ @ }Exceptions @tab ZCX
24008@*
24009@item @b{sparc-solaris}  @tab
24010@item @code{@ @ }@i{rts-native (default)}
24011@item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24012@item @code{@ @ @ @ }Exceptions @tab ZCX
24013@*
24014@item @code{@ @ }@i{rts-pthread}
24015@item @code{@ @ @ @ }Tasking    @tab pthread library
24016@item @code{@ @ @ @ }Exceptions @tab ZCX
24017@*
24018@item @code{@ @ }@i{rts-sjlj}
24019@item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24020@item @code{@ @ @ @ }Exceptions @tab SJLJ
24021@*
24022@item @b{sparc64-solaris}  @tab
24023@item @code{@ @ }@i{rts-native (default)}
24024@item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24025@item @code{@ @ @ @ }Exceptions @tab ZCX
24026@*
24027@item @b{x86-linux}
24028@item @code{@ @ }@i{rts-native (default)}
24029@item @code{@ @ @ @ }Tasking    @tab pthread library
24030@item @code{@ @ @ @ }Exceptions @tab ZCX
24031@*
24032@item @code{@ @ }@i{rts-sjlj}
24033@item @code{@ @ @ @ }Tasking    @tab pthread library
24034@item @code{@ @ @ @ }Exceptions @tab SJLJ
24035@*
24036@item @b{x86-lynx}
24037@item @code{@ @ }@i{rts-native (default)}
24038@item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
24039@item @code{@ @ @ @ }Exceptions @tab SJLJ
24040@*
24041@item @b{x86-solaris}
24042@item @code{@ @ }@i{rts-native (default)}
24043@item @code{@ @ @ @ }Tasking    @tab native Solaris threads
24044@item @code{@ @ @ @ }Exceptions @tab ZCX
24045@*
24046@item @code{@ @ }@i{rts-sjlj}
24047@item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24048@item @code{@ @ @ @ }Exceptions @tab SJLJ
24049@*
24050@item @b{x86-windows}
24051@item @code{@ @ }@i{rts-native (default)}
24052@item @code{@ @ @ @ }Tasking    @tab native Win32 threads
24053@item @code{@ @ @ @ }Exceptions @tab ZCX
24054@*
24055@item @code{@ @ }@i{rts-sjlj}
24056@item @code{@ @ @ @ }Tasking    @tab native Win32 threads
24057@item @code{@ @ @ @ }Exceptions @tab SJLJ
24058@*
24059@item @b{x86-windows-rtx}
24060@item @code{@ @ }@i{rts-rtx-rtss (default)}
24061@item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
24062@item @code{@ @ @ @ }Exceptions @tab SJLJ
24063@*
24064@item @code{@ @ }@i{rts-rtx-w32}
24065@item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
24066@item @code{@ @ @ @ }Exceptions @tab ZCX
24067@*
24068@item @b{x86_64-linux}
24069@item @code{@ @ }@i{rts-native (default)}
24070@item @code{@ @ @ @ }Tasking    @tab pthread library
24071@item @code{@ @ @ @ }Exceptions @tab ZCX
24072@*
24073@item @code{@ @ }@i{rts-sjlj}
24074@item @code{@ @ @ @ }Tasking    @tab pthread library
24075@item @code{@ @ @ @ }Exceptions @tab SJLJ
24076@*
24077@end multitable
24078
24079@node Specifying a Run-Time Library
24080@section Specifying a Run-Time Library
24081
24082@noindent
24083The @file{adainclude} subdirectory containing the sources of the GNAT
24084run-time library, and the @file{adalib} subdirectory containing the
24085@file{ALI} files and the static and/or shared GNAT library, are located
24086in the gcc target-dependent area:
24087
24088@smallexample
24089target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24090@end smallexample
24091
24092@noindent
24093As indicated above, on some platforms several run-time libraries are supplied.
24094These libraries are installed in the target dependent area and
24095contain a complete source and binary subdirectory. The detailed description
24096below explains the differences between the different libraries in terms of
24097their thread support.
24098
24099The default run-time library (when GNAT is installed) is @emph{rts-native}.
24100This default run time is selected by the means of soft links.
24101For example on x86-linux:
24102
24103@smallexample
24104@group
24105 $(target-dir)
24106     |
24107     +--- adainclude----------+
24108     |                        |
24109     +--- adalib-----------+  |
24110     |                     |  |
24111     +--- rts-native       |  |
24112     |    |                |  |
24113     |    +--- adainclude <---+
24114     |    |                |
24115     |    +--- adalib <----+
24116     |
24117     +--- rts-sjlj
24118          |
24119          +--- adainclude
24120          |
24121          +--- adalib
24122@end group
24123@end smallexample
24124
24125@noindent
24126If the @i{rts-sjlj} library is to be selected on a permanent basis,
24127these soft links can be modified with the following commands:
24128
24129@smallexample
24130$ cd $target
24131$ rm -f adainclude adalib
24132$ ln -s rts-sjlj/adainclude adainclude
24133$ ln -s rts-sjlj/adalib adalib
24134@end smallexample
24135
24136@noindent
24137Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24138@file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24139@file{$target/ada_object_path}.
24140
24141Selecting another run-time library temporarily can be
24142achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24143@cindex @option{--RTS} option
24144
24145@node Choosing the Scheduling Policy
24146@section Choosing the Scheduling Policy
24147
24148@noindent
24149When using a POSIX threads implementation, you have a choice of several
24150scheduling policies: @code{SCHED_FIFO},
24151@cindex @code{SCHED_FIFO} scheduling policy
24152@code{SCHED_RR}
24153@cindex @code{SCHED_RR} scheduling policy
24154and @code{SCHED_OTHER}.
24155@cindex @code{SCHED_OTHER} scheduling policy
24156Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24157or @code{SCHED_RR} requires special (e.g., root) privileges.
24158
24159By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24160@code{SCHED_FIFO},
24161@cindex @code{SCHED_FIFO} scheduling policy
24162you can use one of the following:
24163
24164@itemize @bullet
24165@item
24166@code{pragma Time_Slice (0.0)}
24167@cindex pragma Time_Slice
24168@item
24169the corresponding binder option @option{-T0}
24170@cindex @option{-T0} option
24171@item
24172@code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24173@cindex pragma Task_Dispatching_Policy
24174@end itemize
24175
24176@noindent
24177To specify @code{SCHED_RR},
24178@cindex @code{SCHED_RR} scheduling policy
24179you should use @code{pragma Time_Slice} with a
24180value greater than @code{0.0}, or else use the corresponding @option{-T}
24181binder option.
24182
24183@node Solaris-Specific Considerations
24184@section Solaris-Specific Considerations
24185@cindex Solaris Sparc threads libraries
24186
24187@noindent
24188This section addresses some topics related to the various threads libraries
24189on Sparc Solaris.
24190
24191@menu
24192* Solaris Threads Issues::
24193@end menu
24194
24195@node Solaris Threads Issues
24196@subsection Solaris Threads Issues
24197
24198@noindent
24199GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24200library based on POSIX threads --- @emph{rts-pthread}.
24201@cindex rts-pthread threads library
24202This run-time library has the advantage of being mostly shared across all
24203POSIX-compliant thread implementations, and it also provides under
24204@w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24205@cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24206and @code{PTHREAD_PRIO_PROTECT}
24207@cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24208semantics that can be selected using the predefined pragma
24209@code{Locking_Policy}
24210@cindex pragma Locking_Policy (under rts-pthread)
24211with respectively
24212@code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24213@cindex @code{Inheritance_Locking} (under rts-pthread)
24214@cindex @code{Ceiling_Locking} (under rts-pthread)
24215
24216As explained above, the native run-time library is based on the Solaris thread
24217library (@code{libthread}) and is the default library.
24218
24219When the Solaris threads library is used (this is the default), programs
24220compiled with GNAT can automatically take advantage of
24221and can thus execute on multiple processors.
24222The user can alternatively specify a processor on which the program should run
24223to emulate a single-processor system. The multiprocessor / uniprocessor choice
24224is made by
24225setting the environment variable @env{GNAT_PROCESSOR}
24226@cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24227to one of the following:
24228
24229@table @code
24230@item -2
24231Use the default configuration (run the program on all
24232available processors) - this is the same as having @code{GNAT_PROCESSOR}
24233unset
24234
24235@item -1
24236Let the run-time implementation choose one processor and run the program on
24237that processor
24238
24239@item 0 .. Last_Proc
24240Run the program on the specified processor.
24241@code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24242(where @code{_SC_NPROCESSORS_CONF} is a system variable).
24243@end table
24244
24245@node Linux-Specific Considerations
24246@section Linux-Specific Considerations
24247@cindex Linux threads libraries
24248
24249@noindent
24250On GNU/Linux without NPTL support (usually system with GNU C Library
24251older than 2.3), the signal model is not POSIX compliant, which means
24252that to send a signal to the process, you need to send the signal to all
24253threads, e.g.@: by using @code{killpg()}.
24254
24255@node AIX-Specific Considerations
24256@section AIX-Specific Considerations
24257@cindex AIX resolver library
24258
24259@noindent
24260On AIX, the resolver library initializes some internal structure on
24261the first call to @code{get*by*} functions, which are used to implement
24262@code{GNAT.Sockets.Get_Host_By_Name} and
24263@code{GNAT.Sockets.Get_Host_By_Address}.
24264If such initialization occurs within an Ada task, and the stack size for
24265the task is the default size, a stack overflow may occur.
24266
24267To avoid this overflow, the user should either ensure that the first call
24268to @code{GNAT.Sockets.Get_Host_By_Name} or
24269@code{GNAT.Sockets.Get_Host_By_Addrss}
24270occurs in the environment task, or use @code{pragma Storage_Size} to
24271specify a sufficiently large size for the stack of the task that contains
24272this call.
24273
24274@node RTX-Specific Considerations
24275@section RTX-Specific Considerations
24276@cindex RTX libraries
24277
24278@noindent
24279The Real-time Extension (RTX) to Windows is based on the Windows Win32
24280API. Applications can be built to work in two different modes:
24281
24282@itemize @bullet
24283@item
24284Windows executables that run in Ring 3 to utilize memory protection
24285(@emph{rts-rtx-w32}).
24286
24287@item
24288Real-time subsystem (RTSS) executables that run in Ring 0, where
24289performance can be optimized with RTSS applications taking precedent
24290over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
24291the Microsoft linker to handle RTSS libraries.
24292
24293@end itemize
24294
24295@node HP-UX-Specific Considerations
24296@section HP-UX-Specific Considerations
24297@cindex HP-UX Scheduling
24298
24299@noindent
24300On HP-UX, appropriate privileges are required to change the scheduling
24301parameters of a task. The calling process must have appropriate
24302privileges or be a member of a group having @code{PRIV_RTSCHED} access to
24303successfully change the scheduling parameters.
24304
24305By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
24306priority range 0-31 either the @code{FIFO_Within_Priorities} or the
24307@code{Round_Robin_Within_Priorities} scheduling policies need to be set.
24308
24309To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
24310one of the following:
24311
24312@itemize @bullet
24313@item
24314@code{pragma Time_Slice (0.0)}
24315@cindex pragma Time_Slice
24316@item
24317the corresponding binder option @option{-T0}
24318@cindex @option{-T0} option
24319@item
24320@code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24321@cindex pragma Task_Dispatching_Policy
24322@end itemize
24323
24324@noindent
24325To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
24326you should use @code{pragma Time_Slice} with a
24327value greater than @code{0.0}, or use the corresponding @option{-T}
24328binder option, or set the @code{pragma Task_Dispatching_Policy
24329(Round_Robin_Within_Priorities)}.
24330
24331@c *******************************
24332@node Example of Binder Output File
24333@appendix Example of Binder Output File
24334
24335@noindent
24336This Appendix displays the source code for @command{gnatbind}'s output
24337file generated for a simple ``Hello World'' program.
24338Comments have been added for clarification purposes.
24339
24340@smallexample @c adanocomment
24341@iftex
24342@leftskip=0cm
24343@end iftex
24344--  The package is called Ada_Main unless this name is actually used
24345--  as a unit name in the partition, in which case some other unique
24346--  name is used.
24347
24348with System;
24349package ada_main is
24350
24351   Elab_Final_Code : Integer;
24352   pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24353
24354   --  The main program saves the parameters (argument count,
24355   --  argument values, environment pointer) in global variables
24356   --  for later access by other units including
24357   --  Ada.Command_Line.
24358
24359   gnat_argc : Integer;
24360   gnat_argv : System.Address;
24361   gnat_envp : System.Address;
24362
24363   --  The actual variables are stored in a library routine. This
24364   --  is useful for some shared library situations, where there
24365   --  are problems if variables are not in the library.
24366
24367   pragma Import (C, gnat_argc);
24368   pragma Import (C, gnat_argv);
24369   pragma Import (C, gnat_envp);
24370
24371   --  The exit status is similarly an external location
24372
24373   gnat_exit_status : Integer;
24374   pragma Import (C, gnat_exit_status);
24375
24376   GNAT_Version : constant String :=
24377                    "GNAT Version: 6.0.0w (20061115)";
24378   pragma Export (C, GNAT_Version, "__gnat_version");
24379
24380   --  This is the generated adafinal routine that performs
24381   --  finalization at the end of execution. In the case where
24382   --  Ada is the main program, this main program makes a call
24383   --  to adafinal at program termination.
24384
24385   procedure adafinal;
24386   pragma Export (C, adafinal, "adafinal");
24387
24388   --  This is the generated adainit routine that performs
24389   --  initialization at the start of execution. In the case
24390   --  where Ada is the main program, this main program makes
24391   --  a call to adainit at program startup.
24392
24393   procedure adainit;
24394   pragma Export (C, adainit, "adainit");
24395
24396   --  This routine is called at the start of execution. It is
24397   --  a dummy routine that is used by the debugger to breakpoint
24398   --  at the start of execution.
24399
24400   procedure Break_Start;
24401   pragma Import (C, Break_Start, "__gnat_break_start");
24402
24403   --  This is the actual generated main program (it would be
24404   --  suppressed if the no main program switch were used). As
24405   --  required by standard system conventions, this program has
24406   --  the external name main.
24407
24408   function main
24409     (argc : Integer;
24410      argv : System.Address;
24411      envp : System.Address)
24412      return Integer;
24413   pragma Export (C, main, "main");
24414
24415   --  The following set of constants give the version
24416   --  identification values for every unit in the bound
24417   --  partition. This identification is computed from all
24418   --  dependent semantic units, and corresponds to the
24419   --  string that would be returned by use of the
24420   --  Body_Version or Version attributes.
24421
24422   type Version_32 is mod 2 ** 32;
24423   u00001 : constant Version_32 := 16#7880BEB3#;
24424   u00002 : constant Version_32 := 16#0D24CBD0#;
24425   u00003 : constant Version_32 := 16#3283DBEB#;
24426   u00004 : constant Version_32 := 16#2359F9ED#;
24427   u00005 : constant Version_32 := 16#664FB847#;
24428   u00006 : constant Version_32 := 16#68E803DF#;
24429   u00007 : constant Version_32 := 16#5572E604#;
24430   u00008 : constant Version_32 := 16#46B173D8#;
24431   u00009 : constant Version_32 := 16#156A40CF#;
24432   u00010 : constant Version_32 := 16#033DABE0#;
24433   u00011 : constant Version_32 := 16#6AB38FEA#;
24434   u00012 : constant Version_32 := 16#22B6217D#;
24435   u00013 : constant Version_32 := 16#68A22947#;
24436   u00014 : constant Version_32 := 16#18CC4A56#;
24437   u00015 : constant Version_32 := 16#08258E1B#;
24438   u00016 : constant Version_32 := 16#367D5222#;
24439   u00017 : constant Version_32 := 16#20C9ECA4#;
24440   u00018 : constant Version_32 := 16#50D32CB6#;
24441   u00019 : constant Version_32 := 16#39A8BB77#;
24442   u00020 : constant Version_32 := 16#5CF8FA2B#;
24443   u00021 : constant Version_32 := 16#2F1EB794#;
24444   u00022 : constant Version_32 := 16#31AB6444#;
24445   u00023 : constant Version_32 := 16#1574B6E9#;
24446   u00024 : constant Version_32 := 16#5109C189#;
24447   u00025 : constant Version_32 := 16#56D770CD#;
24448   u00026 : constant Version_32 := 16#02F9DE3D#;
24449   u00027 : constant Version_32 := 16#08AB6B2C#;
24450   u00028 : constant Version_32 := 16#3FA37670#;
24451   u00029 : constant Version_32 := 16#476457A0#;
24452   u00030 : constant Version_32 := 16#731E1B6E#;
24453   u00031 : constant Version_32 := 16#23C2E789#;
24454   u00032 : constant Version_32 := 16#0F1BD6A1#;
24455   u00033 : constant Version_32 := 16#7C25DE96#;
24456   u00034 : constant Version_32 := 16#39ADFFA2#;
24457   u00035 : constant Version_32 := 16#571DE3E7#;
24458   u00036 : constant Version_32 := 16#5EB646AB#;
24459   u00037 : constant Version_32 := 16#4249379B#;
24460   u00038 : constant Version_32 := 16#0357E00A#;
24461   u00039 : constant Version_32 := 16#3784FB72#;
24462   u00040 : constant Version_32 := 16#2E723019#;
24463   u00041 : constant Version_32 := 16#623358EA#;
24464   u00042 : constant Version_32 := 16#107F9465#;
24465   u00043 : constant Version_32 := 16#6843F68A#;
24466   u00044 : constant Version_32 := 16#63305874#;
24467   u00045 : constant Version_32 := 16#31E56CE1#;
24468   u00046 : constant Version_32 := 16#02917970#;
24469   u00047 : constant Version_32 := 16#6CCBA70E#;
24470   u00048 : constant Version_32 := 16#41CD4204#;
24471   u00049 : constant Version_32 := 16#572E3F58#;
24472   u00050 : constant Version_32 := 16#20729FF5#;
24473   u00051 : constant Version_32 := 16#1D4F93E8#;
24474   u00052 : constant Version_32 := 16#30B2EC3D#;
24475   u00053 : constant Version_32 := 16#34054F96#;
24476   u00054 : constant Version_32 := 16#5A199860#;
24477   u00055 : constant Version_32 := 16#0E7F912B#;
24478   u00056 : constant Version_32 := 16#5760634A#;
24479   u00057 : constant Version_32 := 16#5D851835#;
24480
24481   --  The following Export pragmas export the version numbers
24482   --  with symbolic names ending in B (for body) or S
24483   --  (for spec) so that they can be located in a link. The
24484   --  information provided here is sufficient to track down
24485   --  the exact versions of units used in a given build.
24486
24487   pragma Export (C, u00001, "helloB");
24488   pragma Export (C, u00002, "system__standard_libraryB");
24489   pragma Export (C, u00003, "system__standard_libraryS");
24490   pragma Export (C, u00004, "adaS");
24491   pragma Export (C, u00005, "ada__text_ioB");
24492   pragma Export (C, u00006, "ada__text_ioS");
24493   pragma Export (C, u00007, "ada__exceptionsB");
24494   pragma Export (C, u00008, "ada__exceptionsS");
24495   pragma Export (C, u00009, "gnatS");
24496   pragma Export (C, u00010, "gnat__heap_sort_aB");
24497   pragma Export (C, u00011, "gnat__heap_sort_aS");
24498   pragma Export (C, u00012, "systemS");
24499   pragma Export (C, u00013, "system__exception_tableB");
24500   pragma Export (C, u00014, "system__exception_tableS");
24501   pragma Export (C, u00015, "gnat__htableB");
24502   pragma Export (C, u00016, "gnat__htableS");
24503   pragma Export (C, u00017, "system__exceptionsS");
24504   pragma Export (C, u00018, "system__machine_state_operationsB");
24505   pragma Export (C, u00019, "system__machine_state_operationsS");
24506   pragma Export (C, u00020, "system__machine_codeS");
24507   pragma Export (C, u00021, "system__storage_elementsB");
24508   pragma Export (C, u00022, "system__storage_elementsS");
24509   pragma Export (C, u00023, "system__secondary_stackB");
24510   pragma Export (C, u00024, "system__secondary_stackS");
24511   pragma Export (C, u00025, "system__parametersB");
24512   pragma Export (C, u00026, "system__parametersS");
24513   pragma Export (C, u00027, "system__soft_linksB");
24514   pragma Export (C, u00028, "system__soft_linksS");
24515   pragma Export (C, u00029, "system__stack_checkingB");
24516   pragma Export (C, u00030, "system__stack_checkingS");
24517   pragma Export (C, u00031, "system__tracebackB");
24518   pragma Export (C, u00032, "system__tracebackS");
24519   pragma Export (C, u00033, "ada__streamsS");
24520   pragma Export (C, u00034, "ada__tagsB");
24521   pragma Export (C, u00035, "ada__tagsS");
24522   pragma Export (C, u00036, "system__string_opsB");
24523   pragma Export (C, u00037, "system__string_opsS");
24524   pragma Export (C, u00038, "interfacesS");
24525   pragma Export (C, u00039, "interfaces__c_streamsB");
24526   pragma Export (C, u00040, "interfaces__c_streamsS");
24527   pragma Export (C, u00041, "system__file_ioB");
24528   pragma Export (C, u00042, "system__file_ioS");
24529   pragma Export (C, u00043, "ada__finalizationB");
24530   pragma Export (C, u00044, "ada__finalizationS");
24531   pragma Export (C, u00045, "system__finalization_rootB");
24532   pragma Export (C, u00046, "system__finalization_rootS");
24533   pragma Export (C, u00047, "system__finalization_implementationB");
24534   pragma Export (C, u00048, "system__finalization_implementationS");
24535   pragma Export (C, u00049, "system__string_ops_concat_3B");
24536   pragma Export (C, u00050, "system__string_ops_concat_3S");
24537   pragma Export (C, u00051, "system__stream_attributesB");
24538   pragma Export (C, u00052, "system__stream_attributesS");
24539   pragma Export (C, u00053, "ada__io_exceptionsS");
24540   pragma Export (C, u00054, "system__unsigned_typesS");
24541   pragma Export (C, u00055, "system__file_control_blockS");
24542   pragma Export (C, u00056, "ada__finalization__list_controllerB");
24543   pragma Export (C, u00057, "ada__finalization__list_controllerS");
24544
24545   -- BEGIN ELABORATION ORDER
24546   -- ada (spec)
24547   -- gnat (spec)
24548   -- gnat.heap_sort_a (spec)
24549   -- gnat.heap_sort_a (body)
24550   -- gnat.htable (spec)
24551   -- gnat.htable (body)
24552   -- interfaces (spec)
24553   -- system (spec)
24554   -- system.machine_code (spec)
24555   -- system.parameters (spec)
24556   -- system.parameters (body)
24557   -- interfaces.c_streams (spec)
24558   -- interfaces.c_streams (body)
24559   -- system.standard_library (spec)
24560   -- ada.exceptions (spec)
24561   -- system.exception_table (spec)
24562   -- system.exception_table (body)
24563   -- ada.io_exceptions (spec)
24564   -- system.exceptions (spec)
24565   -- system.storage_elements (spec)
24566   -- system.storage_elements (body)
24567   -- system.machine_state_operations (spec)
24568   -- system.machine_state_operations (body)
24569   -- system.secondary_stack (spec)
24570   -- system.stack_checking (spec)
24571   -- system.soft_links (spec)
24572   -- system.soft_links (body)
24573   -- system.stack_checking (body)
24574   -- system.secondary_stack (body)
24575   -- system.standard_library (body)
24576   -- system.string_ops (spec)
24577   -- system.string_ops (body)
24578   -- ada.tags (spec)
24579   -- ada.tags (body)
24580   -- ada.streams (spec)
24581   -- system.finalization_root (spec)
24582   -- system.finalization_root (body)
24583   -- system.string_ops_concat_3 (spec)
24584   -- system.string_ops_concat_3 (body)
24585   -- system.traceback (spec)
24586   -- system.traceback (body)
24587   -- ada.exceptions (body)
24588   -- system.unsigned_types (spec)
24589   -- system.stream_attributes (spec)
24590   -- system.stream_attributes (body)
24591   -- system.finalization_implementation (spec)
24592   -- system.finalization_implementation (body)
24593   -- ada.finalization (spec)
24594   -- ada.finalization (body)
24595   -- ada.finalization.list_controller (spec)
24596   -- ada.finalization.list_controller (body)
24597   -- system.file_control_block (spec)
24598   -- system.file_io (spec)
24599   -- system.file_io (body)
24600   -- ada.text_io (spec)
24601   -- ada.text_io (body)
24602   -- hello (body)
24603   -- END ELABORATION ORDER
24604
24605end ada_main;
24606
24607--  The following source file name pragmas allow the generated file
24608--  names to be unique for different main programs. They are needed
24609--  since the package name will always be Ada_Main.
24610
24611pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24612pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24613
24614--  Generated package body for Ada_Main starts here
24615
24616package body ada_main is
24617
24618   --  The actual finalization is performed by calling the
24619   --  library routine in System.Standard_Library.Adafinal
24620
24621   procedure Do_Finalize;
24622   pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24623
24624   -------------
24625   -- adainit --
24626   -------------
24627
24628@findex adainit
24629   procedure adainit is
24630
24631      --  These booleans are set to True once the associated unit has
24632      --  been elaborated. It is also used to avoid elaborating the
24633      --  same unit twice.
24634
24635      E040 : Boolean;
24636      pragma Import (Ada, E040, "interfaces__c_streams_E");
24637
24638      E008 : Boolean;
24639      pragma Import (Ada, E008, "ada__exceptions_E");
24640
24641      E014 : Boolean;
24642      pragma Import (Ada, E014, "system__exception_table_E");
24643
24644      E053 : Boolean;
24645      pragma Import (Ada, E053, "ada__io_exceptions_E");
24646
24647      E017 : Boolean;
24648      pragma Import (Ada, E017, "system__exceptions_E");
24649
24650      E024 : Boolean;
24651      pragma Import (Ada, E024, "system__secondary_stack_E");
24652
24653      E030 : Boolean;
24654      pragma Import (Ada, E030, "system__stack_checking_E");
24655
24656      E028 : Boolean;
24657      pragma Import (Ada, E028, "system__soft_links_E");
24658
24659      E035 : Boolean;
24660      pragma Import (Ada, E035, "ada__tags_E");
24661
24662      E033 : Boolean;
24663      pragma Import (Ada, E033, "ada__streams_E");
24664
24665      E046 : Boolean;
24666      pragma Import (Ada, E046, "system__finalization_root_E");
24667
24668      E048 : Boolean;
24669      pragma Import (Ada, E048, "system__finalization_implementation_E");
24670
24671      E044 : Boolean;
24672      pragma Import (Ada, E044, "ada__finalization_E");
24673
24674      E057 : Boolean;
24675      pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24676
24677      E055 : Boolean;
24678      pragma Import (Ada, E055, "system__file_control_block_E");
24679
24680      E042 : Boolean;
24681      pragma Import (Ada, E042, "system__file_io_E");
24682
24683      E006 : Boolean;
24684      pragma Import (Ada, E006, "ada__text_io_E");
24685
24686      --  Set_Globals is a library routine that stores away the
24687      --  value of the indicated set of global values in global
24688      --  variables within the library.
24689
24690      procedure Set_Globals
24691        (Main_Priority            : Integer;
24692         Time_Slice_Value         : Integer;
24693         WC_Encoding              : Character;
24694         Locking_Policy           : Character;
24695         Queuing_Policy           : Character;
24696         Task_Dispatching_Policy  : Character;
24697         Adafinal                 : System.Address;
24698         Unreserve_All_Interrupts : Integer;
24699         Exception_Tracebacks     : Integer);
24700@findex __gnat_set_globals
24701      pragma Import (C, Set_Globals, "__gnat_set_globals");
24702
24703      --  SDP_Table_Build is a library routine used to build the
24704      --  exception tables. See unit Ada.Exceptions in files
24705      --  a-except.ads/adb for full details of how zero cost
24706      --  exception handling works. This procedure, the call to
24707      --  it, and the two following tables are all omitted if the
24708      --  build is in longjmp/setjmp exception mode.
24709
24710@findex SDP_Table_Build
24711@findex Zero Cost Exceptions
24712      procedure SDP_Table_Build
24713        (SDP_Addresses   : System.Address;
24714         SDP_Count       : Natural;
24715         Elab_Addresses  : System.Address;
24716         Elab_Addr_Count : Natural);
24717      pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24718
24719      --  Table of Unit_Exception_Table addresses. Used for zero
24720      --  cost exception handling to build the top level table.
24721
24722      ST : aliased constant array (1 .. 23) of System.Address := (
24723        Hello'UET_Address,
24724        Ada.Text_Io'UET_Address,
24725        Ada.Exceptions'UET_Address,
24726        Gnat.Heap_Sort_A'UET_Address,
24727        System.Exception_Table'UET_Address,
24728        System.Machine_State_Operations'UET_Address,
24729        System.Secondary_Stack'UET_Address,
24730        System.Parameters'UET_Address,
24731        System.Soft_Links'UET_Address,
24732        System.Stack_Checking'UET_Address,
24733        System.Traceback'UET_Address,
24734        Ada.Streams'UET_Address,
24735        Ada.Tags'UET_Address,
24736        System.String_Ops'UET_Address,
24737        Interfaces.C_Streams'UET_Address,
24738        System.File_Io'UET_Address,
24739        Ada.Finalization'UET_Address,
24740        System.Finalization_Root'UET_Address,
24741        System.Finalization_Implementation'UET_Address,
24742        System.String_Ops_Concat_3'UET_Address,
24743        System.Stream_Attributes'UET_Address,
24744        System.File_Control_Block'UET_Address,
24745        Ada.Finalization.List_Controller'UET_Address);
24746
24747      --  Table of addresses of elaboration routines. Used for
24748      --  zero cost exception handling to make sure these
24749      --  addresses are included in the top level procedure
24750      --  address table.
24751
24752      EA : aliased constant array (1 .. 23) of System.Address := (
24753        adainit'Code_Address,
24754        Do_Finalize'Code_Address,
24755        Ada.Exceptions'Elab_Spec'Address,
24756        System.Exceptions'Elab_Spec'Address,
24757        Interfaces.C_Streams'Elab_Spec'Address,
24758        System.Exception_Table'Elab_Body'Address,
24759        Ada.Io_Exceptions'Elab_Spec'Address,
24760        System.Stack_Checking'Elab_Spec'Address,
24761        System.Soft_Links'Elab_Body'Address,
24762        System.Secondary_Stack'Elab_Body'Address,
24763        Ada.Tags'Elab_Spec'Address,
24764        Ada.Tags'Elab_Body'Address,
24765        Ada.Streams'Elab_Spec'Address,
24766        System.Finalization_Root'Elab_Spec'Address,
24767        Ada.Exceptions'Elab_Body'Address,
24768        System.Finalization_Implementation'Elab_Spec'Address,
24769        System.Finalization_Implementation'Elab_Body'Address,
24770        Ada.Finalization'Elab_Spec'Address,
24771        Ada.Finalization.List_Controller'Elab_Spec'Address,
24772        System.File_Control_Block'Elab_Spec'Address,
24773        System.File_Io'Elab_Body'Address,
24774        Ada.Text_Io'Elab_Spec'Address,
24775        Ada.Text_Io'Elab_Body'Address);
24776
24777   --  Start of processing for adainit
24778
24779   begin
24780
24781      --  Call SDP_Table_Build to build the top level procedure
24782      --  table for zero cost exception handling (omitted in
24783      --  longjmp/setjmp mode).
24784
24785      SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24786
24787      --  Call Set_Globals to record various information for
24788      --  this partition.  The values are derived by the binder
24789      --  from information stored in the ali files by the compiler.
24790
24791@findex __gnat_set_globals
24792      Set_Globals
24793        (Main_Priority            => -1,
24794         --  Priority of main program, -1 if no pragma Priority used
24795
24796         Time_Slice_Value         => -1,
24797         --  Time slice from Time_Slice pragma, -1 if none used
24798
24799         WC_Encoding              => 'b',
24800         --  Wide_Character encoding used, default is brackets
24801
24802         Locking_Policy           => ' ',
24803         --  Locking_Policy used, default of space means not
24804         --  specified, otherwise it is the first character of
24805         --  the policy name.
24806
24807         Queuing_Policy           => ' ',
24808         --  Queuing_Policy used, default of space means not
24809         --  specified, otherwise it is the first character of
24810         --  the policy name.
24811
24812         Task_Dispatching_Policy  => ' ',
24813         --  Task_Dispatching_Policy used, default of space means
24814         --  not specified, otherwise first character of the
24815         --  policy name.
24816
24817         Adafinal                 => System.Null_Address,
24818         --  Address of Adafinal routine, not used anymore
24819
24820         Unreserve_All_Interrupts => 0,
24821         --  Set true if pragma Unreserve_All_Interrupts was used
24822
24823         Exception_Tracebacks     => 0);
24824         --  Indicates if exception tracebacks are enabled
24825
24826      Elab_Final_Code := 1;
24827
24828      --  Now we have the elaboration calls for all units in the partition.
24829      --  The Elab_Spec and Elab_Body attributes generate references to the
24830      --  implicit elaboration procedures generated by the compiler for
24831      --  each unit that requires elaboration.
24832
24833      if not E040 then
24834         Interfaces.C_Streams'Elab_Spec;
24835      end if;
24836      E040 := True;
24837      if not E008 then
24838         Ada.Exceptions'Elab_Spec;
24839      end if;
24840      if not E014 then
24841         System.Exception_Table'Elab_Body;
24842         E014 := True;
24843      end if;
24844      if not E053 then
24845         Ada.Io_Exceptions'Elab_Spec;
24846         E053 := True;
24847      end if;
24848      if not E017 then
24849         System.Exceptions'Elab_Spec;
24850         E017 := True;
24851      end if;
24852      if not E030 then
24853         System.Stack_Checking'Elab_Spec;
24854      end if;
24855      if not E028 then
24856         System.Soft_Links'Elab_Body;
24857         E028 := True;
24858      end if;
24859      E030 := True;
24860      if not E024 then
24861         System.Secondary_Stack'Elab_Body;
24862         E024 := True;
24863      end if;
24864      if not E035 then
24865         Ada.Tags'Elab_Spec;
24866      end if;
24867      if not E035 then
24868         Ada.Tags'Elab_Body;
24869         E035 := True;
24870      end if;
24871      if not E033 then
24872         Ada.Streams'Elab_Spec;
24873         E033 := True;
24874      end if;
24875      if not E046 then
24876         System.Finalization_Root'Elab_Spec;
24877      end if;
24878      E046 := True;
24879      if not E008 then
24880         Ada.Exceptions'Elab_Body;
24881         E008 := True;
24882      end if;
24883      if not E048 then
24884         System.Finalization_Implementation'Elab_Spec;
24885      end if;
24886      if not E048 then
24887         System.Finalization_Implementation'Elab_Body;
24888         E048 := True;
24889      end if;
24890      if not E044 then
24891         Ada.Finalization'Elab_Spec;
24892      end if;
24893      E044 := True;
24894      if not E057 then
24895         Ada.Finalization.List_Controller'Elab_Spec;
24896      end if;
24897      E057 := True;
24898      if not E055 then
24899         System.File_Control_Block'Elab_Spec;
24900         E055 := True;
24901      end if;
24902      if not E042 then
24903         System.File_Io'Elab_Body;
24904         E042 := True;
24905      end if;
24906      if not E006 then
24907         Ada.Text_Io'Elab_Spec;
24908      end if;
24909      if not E006 then
24910         Ada.Text_Io'Elab_Body;
24911         E006 := True;
24912      end if;
24913
24914      Elab_Final_Code := 0;
24915   end adainit;
24916
24917   --------------
24918   -- adafinal --
24919   --------------
24920
24921@findex adafinal
24922   procedure adafinal is
24923   begin
24924      Do_Finalize;
24925   end adafinal;
24926
24927   ----------
24928   -- main --
24929   ----------
24930
24931   --  main is actually a function, as in the ANSI C standard,
24932   --  defined to return the exit status. The three parameters
24933   --  are the argument count, argument values and environment
24934   --  pointer.
24935
24936@findex Main Program
24937   function main
24938     (argc : Integer;
24939      argv : System.Address;
24940      envp : System.Address)
24941      return Integer
24942   is
24943      --  The initialize routine performs low level system
24944      --  initialization using a standard library routine which
24945      --  sets up signal handling and performs any other
24946      --  required setup. The routine can be found in file
24947      --  a-init.c.
24948
24949@findex __gnat_initialize
24950      procedure initialize;
24951      pragma Import (C, initialize, "__gnat_initialize");
24952
24953      --  The finalize routine performs low level system
24954      --  finalization using a standard library routine. The
24955      --  routine is found in file a-final.c and in the standard
24956      --  distribution is a dummy routine that does nothing, so
24957      --  really this is a hook for special user finalization.
24958
24959@findex __gnat_finalize
24960      procedure finalize;
24961      pragma Import (C, finalize, "__gnat_finalize");
24962
24963      --  We get to the main program of the partition by using
24964      --  pragma Import because if we try to with the unit and
24965      --  call it Ada style, then not only do we waste time
24966      --  recompiling it, but also, we don't really know the right
24967      --  switches (e.g.@: identifier character set) to be used
24968      --  to compile it.
24969
24970      procedure Ada_Main_Program;
24971      pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24972
24973   --  Start of processing for main
24974
24975   begin
24976      --  Save global variables
24977
24978      gnat_argc := argc;
24979      gnat_argv := argv;
24980      gnat_envp := envp;
24981
24982      --  Call low level system initialization
24983
24984      Initialize;
24985
24986      --  Call our generated Ada initialization routine
24987
24988      adainit;
24989
24990      --  This is the point at which we want the debugger to get
24991      --  control
24992
24993      Break_Start;
24994
24995      --  Now we call the main program of the partition
24996
24997      Ada_Main_Program;
24998
24999      --  Perform Ada finalization
25000
25001      adafinal;
25002
25003      --  Perform low level system finalization
25004
25005      Finalize;
25006
25007      --  Return the proper exit status
25008      return (gnat_exit_status);
25009   end;
25010
25011--  This section is entirely comments, so it has no effect on the
25012--  compilation of the Ada_Main package. It provides the list of
25013--  object files and linker options, as well as some standard
25014--  libraries needed for the link. The gnatlink utility parses
25015--  this b~hello.adb file to read these comment lines to generate
25016--  the appropriate command line arguments for the call to the
25017--  system linker. The BEGIN/END lines are used for sentinels for
25018--  this parsing operation.
25019
25020--  The exact file names will of course depend on the environment,
25021--  host/target and location of files on the host system.
25022
25023@findex Object file list
25024-- BEGIN Object file/option list
25025   --   ./hello.o
25026   --   -L./
25027   --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25028   --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25029-- END Object file/option list
25030
25031end ada_main;
25032@end smallexample
25033
25034@noindent
25035The Ada code in the above example is exactly what is generated by the
25036binder. We have added comments to more clearly indicate the function
25037of each part of the generated @code{Ada_Main} package.
25038
25039The code is standard Ada in all respects, and can be processed by any
25040tools that handle Ada. In particular, it is possible to use the debugger
25041in Ada mode to debug the generated @code{Ada_Main} package. For example,
25042suppose that for reasons that you do not understand, your program is crashing
25043during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25044you can place a breakpoint on the call:
25045
25046@smallexample @c ada
25047Ada.Text_Io'Elab_Body;
25048@end smallexample
25049
25050@noindent
25051and trace the elaboration routine for this package to find out where
25052the problem might be (more usually of course you would be debugging
25053elaboration code in your own application).
25054
25055@node Elaboration Order Handling in GNAT
25056@appendix Elaboration Order Handling in GNAT
25057@cindex Order of elaboration
25058@cindex Elaboration control
25059
25060@menu
25061* Elaboration Code::
25062* Checking the Elaboration Order::
25063* Controlling the Elaboration Order::
25064* Controlling Elaboration in GNAT - Internal Calls::
25065* Controlling Elaboration in GNAT - External Calls::
25066* Default Behavior in GNAT - Ensuring Safety::
25067* Treatment of Pragma Elaborate::
25068* Elaboration Issues for Library Tasks::
25069* Mixing Elaboration Models::
25070* What to Do If the Default Elaboration Behavior Fails::
25071* Elaboration for Indirect Calls::
25072* Summary of Procedures for Elaboration Control::
25073* Other Elaboration Order Considerations::
25074* Determining the Chosen Elaboration Order::
25075@end menu
25076
25077@noindent
25078This chapter describes the handling of elaboration code in Ada and
25079in GNAT, and discusses how the order of elaboration of program units can
25080be controlled in GNAT, either automatically or with explicit programming
25081features.
25082
25083@node Elaboration Code
25084@section Elaboration Code
25085
25086@noindent
25087Ada provides rather general mechanisms for executing code at elaboration
25088time, that is to say before the main program starts executing. Such code arises
25089in three contexts:
25090
25091@table @asis
25092@item Initializers for variables.
25093Variables declared at the library level, in package specs or bodies, can
25094require initialization that is performed at elaboration time, as in:
25095@smallexample @c ada
25096@cartouche
25097Sqrt_Half : Float := Sqrt (0.5);
25098@end cartouche
25099@end smallexample
25100
25101@item Package initialization code
25102Code in a @code{BEGIN-END} section at the outer level of a package body is
25103executed as part of the package body elaboration code.
25104
25105@item Library level task allocators
25106Tasks that are declared using task allocators at the library level
25107start executing immediately and hence can execute at elaboration time.
25108@end table
25109
25110@noindent
25111Subprogram calls are possible in any of these contexts, which means that
25112any arbitrary part of the program may be executed as part of the elaboration
25113code. It is even possible to write a program which does all its work at
25114elaboration time, with a null main program, although stylistically this
25115would usually be considered an inappropriate way to structure
25116a program.
25117
25118An important concern arises in the context of elaboration code:
25119we have to be sure that it is executed in an appropriate order. What we
25120have is a series of elaboration code sections, potentially one section
25121for each unit in the program. It is important that these execute
25122in the correct order. Correctness here means that, taking the above
25123example of the declaration of @code{Sqrt_Half},
25124if some other piece of
25125elaboration code references @code{Sqrt_Half},
25126then it must run after the
25127section of elaboration code that contains the declaration of
25128@code{Sqrt_Half}.
25129
25130There would never be any order of elaboration problem if we made a rule
25131that whenever you @code{with} a unit, you must elaborate both the spec and body
25132of that unit before elaborating the unit doing the @code{with}'ing:
25133
25134@smallexample @c ada
25135@group
25136@cartouche
25137with Unit_1;
25138package Unit_2 is @dots{}
25139@end cartouche
25140@end group
25141@end smallexample
25142
25143@noindent
25144would require that both the body and spec of @code{Unit_1} be elaborated
25145before the spec of @code{Unit_2}. However, a rule like that would be far too
25146restrictive. In particular, it would make it impossible to have routines
25147in separate packages that were mutually recursive.
25148
25149You might think that a clever enough compiler could look at the actual
25150elaboration code and determine an appropriate correct order of elaboration,
25151but in the general case, this is not possible. Consider the following
25152example.
25153
25154In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25155that references
25156the variable @code{Sqrt_1}, which is declared in the elaboration code
25157of the body of @code{Unit_1}:
25158
25159@smallexample @c ada
25160@cartouche
25161Sqrt_1 : Float := Sqrt (0.1);
25162@end cartouche
25163@end smallexample
25164
25165@noindent
25166The elaboration code of the body of @code{Unit_1} also contains:
25167
25168@smallexample @c ada
25169@group
25170@cartouche
25171if expression_1 = 1 then
25172   Q := Unit_2.Func_2;
25173end if;
25174@end cartouche
25175@end group
25176@end smallexample
25177
25178@noindent
25179@code{Unit_2} is exactly parallel,
25180it has a procedure @code{Func_2} that references
25181the variable @code{Sqrt_2}, which is declared in the elaboration code of
25182the body @code{Unit_2}:
25183
25184@smallexample @c ada
25185@cartouche
25186Sqrt_2 : Float := Sqrt (0.1);
25187@end cartouche
25188@end smallexample
25189
25190@noindent
25191The elaboration code of the body of @code{Unit_2} also contains:
25192
25193@smallexample @c ada
25194@group
25195@cartouche
25196if expression_2 = 2 then
25197   Q := Unit_1.Func_1;
25198end if;
25199@end cartouche
25200@end group
25201@end smallexample
25202
25203@noindent
25204Now the question is, which of the following orders of elaboration is
25205acceptable:
25206
25207@smallexample
25208@group
25209Spec of Unit_1
25210Spec of Unit_2
25211Body of Unit_1
25212Body of Unit_2
25213@end group
25214@end smallexample
25215
25216@noindent
25217or
25218
25219@smallexample
25220@group
25221Spec of Unit_2
25222Spec of Unit_1
25223Body of Unit_2
25224Body of Unit_1
25225@end group
25226@end smallexample
25227
25228@noindent
25229If you carefully analyze the flow here, you will see that you cannot tell
25230at compile time the answer to this question.
25231If @code{expression_1} is not equal to 1,
25232and @code{expression_2} is not equal to 2,
25233then either order is acceptable, because neither of the function calls is
25234executed. If both tests evaluate to true, then neither order is acceptable
25235and in fact there is no correct order.
25236
25237If one of the two expressions is true, and the other is false, then one
25238of the above orders is correct, and the other is incorrect. For example,
25239if @code{expression_1} /= 1 and @code{expression_2} = 2,
25240then the call to @code{Func_1}
25241will occur, but not the call to @code{Func_2.}
25242This means that it is essential
25243to elaborate the body of @code{Unit_1} before
25244the body of @code{Unit_2}, so the first
25245order of elaboration is correct and the second is wrong.
25246
25247By making @code{expression_1} and @code{expression_2}
25248depend on input data, or perhaps
25249the time of day, we can make it impossible for the compiler or binder
25250to figure out which of these expressions will be true, and hence it
25251is impossible to guarantee a safe order of elaboration at run time.
25252
25253@node Checking the Elaboration Order
25254@section Checking the Elaboration Order
25255
25256@noindent
25257In some languages that involve the same kind of elaboration problems,
25258e.g.@: Java and C++, the programmer is expected to worry about these
25259ordering problems himself, and it is common to
25260write a program in which an incorrect elaboration order  gives
25261surprising results, because it references variables before they
25262are initialized.
25263Ada is designed to be a safe language, and a programmer-beware approach is
25264clearly not sufficient. Consequently, the language provides three lines
25265of defense:
25266
25267@table @asis
25268@item Standard rules
25269Some standard rules restrict the possible choice of elaboration
25270order. In particular, if you @code{with} a unit, then its spec is always
25271elaborated before the unit doing the @code{with}. Similarly, a parent
25272spec is always elaborated before the child spec, and finally
25273a spec is always elaborated before its corresponding body.
25274
25275@item Dynamic elaboration checks
25276@cindex Elaboration checks
25277@cindex Checks, elaboration
25278Dynamic checks are made at run time, so that if some entity is accessed
25279before it is elaborated (typically  by means of a subprogram call)
25280then the exception (@code{Program_Error}) is raised.
25281
25282@item Elaboration control
25283Facilities are provided for the programmer to specify the desired order
25284of elaboration.
25285@end table
25286
25287Let's look at these facilities in more detail. First, the rules for
25288dynamic checking. One possible rule would be simply to say that the
25289exception is raised if you access a variable which has not yet been
25290elaborated. The trouble with this approach is that it could require
25291expensive checks on every variable reference. Instead Ada has two
25292rules which are a little more restrictive, but easier to check, and
25293easier to state:
25294
25295@table @asis
25296@item Restrictions on calls
25297A subprogram can only be called at elaboration time if its body
25298has been elaborated. The rules for elaboration given above guarantee
25299that the spec of the subprogram has been elaborated before the
25300call, but not the body. If this rule is violated, then the
25301exception @code{Program_Error} is raised.
25302
25303@item Restrictions on instantiations
25304A generic unit can only be instantiated if the body of the generic
25305unit has been elaborated. Again, the rules for elaboration given above
25306guarantee that the spec of the generic unit has been elaborated
25307before the instantiation, but not the body. If this rule is
25308violated, then the exception @code{Program_Error} is raised.
25309@end table
25310
25311@noindent
25312The idea is that if the body has been elaborated, then any variables
25313it references must have been elaborated; by checking for the body being
25314elaborated we guarantee that none of its references causes any
25315trouble. As we noted above, this is a little too restrictive, because a
25316subprogram that has no non-local references in its body may in fact be safe
25317to call. However, it really would be unsafe to rely on this, because
25318it would mean that the caller was aware of details of the implementation
25319in the body. This goes against the basic tenets of Ada.
25320
25321A plausible implementation can be described as follows.
25322A Boolean variable is associated with each subprogram
25323and each generic unit. This variable is initialized to False, and is set to
25324True at the point body is elaborated. Every call or instantiation checks the
25325variable, and raises @code{Program_Error} if the variable is False.
25326
25327Note that one might think that it would be good enough to have one Boolean
25328variable for each package, but that would not deal with cases of trying
25329to call a body in the same package as the call
25330that has not been elaborated yet.
25331Of course a compiler may be able to do enough analysis to optimize away
25332some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25333does such optimizations, but still the easiest conceptual model is to
25334think of there being one variable per subprogram.
25335
25336@node Controlling the Elaboration Order
25337@section Controlling the Elaboration Order
25338
25339@noindent
25340In the previous section we discussed the rules in Ada which ensure
25341that @code{Program_Error} is raised if an incorrect elaboration order is
25342chosen. This prevents erroneous executions, but we need mechanisms to
25343specify a correct execution and avoid the exception altogether.
25344To achieve this, Ada provides a number of features for controlling
25345the order of elaboration. We discuss these features in this section.
25346
25347First, there are several ways of indicating to the compiler that a given
25348unit has no elaboration problems:
25349
25350@table @asis
25351@item packages that do not require a body
25352A library package that does not require a body does not permit
25353a body (this rule was introduced in Ada 95).
25354Thus if we have a such a package, as in:
25355
25356@smallexample @c ada
25357@group
25358@cartouche
25359package Definitions is
25360   generic
25361      type m is new integer;
25362   package Subp is
25363      type a is array (1 .. 10) of m;
25364      type b is array (1 .. 20) of m;
25365   end Subp;
25366end Definitions;
25367@end cartouche
25368@end group
25369@end smallexample
25370
25371@noindent
25372A package that @code{with}'s @code{Definitions} may safely instantiate
25373@code{Definitions.Subp} because the compiler can determine that there
25374definitely is no package body to worry about in this case
25375
25376@item pragma Pure
25377@cindex pragma Pure
25378@findex Pure
25379Places sufficient restrictions on a unit to guarantee that
25380no call to any subprogram in the unit can result in an
25381elaboration problem. This means that the compiler does not need
25382to worry about the point of elaboration of such units, and in
25383particular, does not need to check any calls to any subprograms
25384in this unit.
25385
25386@item pragma Preelaborate
25387@findex Preelaborate
25388@cindex pragma Preelaborate
25389This pragma places slightly less stringent restrictions on a unit than
25390does pragma Pure,
25391but these restrictions are still sufficient to ensure that there
25392are no elaboration problems with any calls to the unit.
25393
25394@item pragma Elaborate_Body
25395@findex Elaborate_Body
25396@cindex pragma Elaborate_Body
25397This pragma requires that the body of a unit be elaborated immediately
25398after its spec. Suppose a unit @code{A} has such a pragma,
25399and unit @code{B} does
25400a @code{with} of unit @code{A}. Recall that the standard rules require
25401the spec of unit @code{A}
25402to be elaborated before the @code{with}'ing unit; given the pragma in
25403@code{A}, we also know that the body of @code{A}
25404will be elaborated before @code{B}, so
25405that calls to @code{A} are safe and do not need a check.
25406@end table
25407
25408@noindent
25409Note that,
25410unlike pragma @code{Pure} and pragma @code{Preelaborate},
25411the use of
25412@code{Elaborate_Body} does not guarantee that the program is
25413free of elaboration problems, because it may not be possible
25414to satisfy the requested elaboration order.
25415Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25416If a programmer
25417marks @code{Unit_1} as @code{Elaborate_Body},
25418and not @code{Unit_2,} then the order of
25419elaboration will be:
25420
25421@smallexample
25422@group
25423Spec of Unit_2
25424Spec of Unit_1
25425Body of Unit_1
25426Body of Unit_2
25427@end group
25428@end smallexample
25429
25430@noindent
25431Now that means that the call to @code{Func_1} in @code{Unit_2}
25432need not be checked,
25433it must be safe. But the call to @code{Func_2} in
25434@code{Unit_1} may still fail if
25435@code{Expression_1} is equal to 1,
25436and the programmer must still take
25437responsibility for this not being the case.
25438
25439If all units carry a pragma @code{Elaborate_Body}, then all problems are
25440eliminated, except for calls entirely within a body, which are
25441in any case fully under programmer control. However, using the pragma
25442everywhere is not always possible.
25443In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25444we marked both of them as having pragma @code{Elaborate_Body}, then
25445clearly there would be no possible elaboration order.
25446
25447The above pragmas allow a server to guarantee safe use by clients, and
25448clearly this is the preferable approach. Consequently a good rule
25449is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25450and if this is not possible,
25451mark them as @code{Elaborate_Body} if possible.
25452As we have seen, there are situations where neither of these
25453three pragmas can be used.
25454So we also provide methods for clients to control the
25455order of elaboration of the servers on which they depend:
25456
25457@table @asis
25458@item pragma Elaborate (unit)
25459@findex Elaborate
25460@cindex pragma Elaborate
25461This pragma is placed in the context clause, after a @code{with} clause,
25462and it requires that the body of the named unit be elaborated before
25463the unit in which the pragma occurs. The idea is to use this pragma
25464if the current unit calls at elaboration time, directly or indirectly,
25465some subprogram in the named unit.
25466
25467@item pragma Elaborate_All (unit)
25468@findex Elaborate_All
25469@cindex pragma Elaborate_All
25470This is a stronger version of the Elaborate pragma. Consider the
25471following example:
25472
25473@smallexample
25474Unit A @code{with}'s unit B and calls B.Func in elab code
25475Unit B @code{with}'s unit C, and B.Func calls C.Func
25476@end smallexample
25477
25478@noindent
25479Now if we put a pragma @code{Elaborate (B)}
25480in unit @code{A}, this ensures that the
25481body of @code{B} is elaborated before the call, but not the
25482body of @code{C}, so
25483the call to @code{C.Func} could still cause @code{Program_Error} to
25484be raised.
25485
25486The effect of a pragma @code{Elaborate_All} is stronger, it requires
25487not only that the body of the named unit be elaborated before the
25488unit doing the @code{with}, but also the bodies of all units that the
25489named unit uses, following @code{with} links transitively. For example,
25490if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25491then it requires
25492not only that the body of @code{B} be elaborated before @code{A},
25493but also the
25494body of @code{C}, because @code{B} @code{with}'s @code{C}.
25495@end table
25496
25497@noindent
25498We are now in a position to give a usage rule in Ada for avoiding
25499elaboration problems, at least if dynamic dispatching and access to
25500subprogram values are not used. We will handle these cases separately
25501later.
25502
25503The rule is simple. If a unit has elaboration code that can directly or
25504indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25505a generic package in a @code{with}'ed unit,
25506then if the @code{with}'ed unit does not have
25507pragma @code{Pure} or @code{Preelaborate}, then the client should have
25508a pragma @code{Elaborate_All}
25509for the @code{with}'ed unit. By following this rule a client is
25510assured that calls can be made without risk of an exception.
25511
25512For generic subprogram instantiations, the rule can be relaxed to
25513require only a pragma @code{Elaborate} since elaborating the body
25514of a subprogram cannot cause any transitive elaboration (we are
25515not calling the subprogram in this case, just elaborating its
25516declaration).
25517
25518If this rule is not followed, then a program may be in one of four
25519states:
25520
25521@table @asis
25522@item No order exists
25523No order of elaboration exists which follows the rules, taking into
25524account any @code{Elaborate}, @code{Elaborate_All},
25525or @code{Elaborate_Body} pragmas. In
25526this case, an Ada compiler must diagnose the situation at bind
25527time, and refuse to build an executable program.
25528
25529@item One or more orders exist, all incorrect
25530One or more acceptable elaboration orders exist, and all of them
25531generate an elaboration order problem. In this case, the binder
25532can build an executable program, but @code{Program_Error} will be raised
25533when the program is run.
25534
25535@item Several orders exist, some right, some incorrect
25536One or more acceptable elaboration orders exists, and some of them
25537work, and some do not. The programmer has not controlled
25538the order of elaboration, so the binder may or may not pick one of
25539the correct orders, and the program may or may not raise an
25540exception when it is run. This is the worst case, because it means
25541that the program may fail when moved to another compiler, or even
25542another version of the same compiler.
25543
25544@item One or more orders exists, all correct
25545One ore more acceptable elaboration orders exist, and all of them
25546work. In this case the program runs successfully. This state of
25547affairs can be guaranteed by following the rule we gave above, but
25548may be true even if the rule is not followed.
25549@end table
25550
25551@noindent
25552Note that one additional advantage of following our rules on the use
25553of @code{Elaborate} and @code{Elaborate_All}
25554is that the program continues to stay in the ideal (all orders OK) state
25555even if maintenance
25556changes some bodies of some units. Conversely, if a program that does
25557not follow this rule happens to be safe at some point, this state of affairs
25558may deteriorate silently as a result of maintenance changes.
25559
25560You may have noticed that the above discussion did not mention
25561the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25562@code{with} an @code{Elaborate_Body} unit, it still may be the case that
25563code in the body makes calls to some other unit, so it is still necessary
25564to use @code{Elaborate_All} on such units.
25565
25566@node Controlling Elaboration in GNAT - Internal Calls
25567@section Controlling Elaboration in GNAT - Internal Calls
25568
25569@noindent
25570In the case of internal calls, i.e., calls within a single package, the
25571programmer has full control over the order of elaboration, and it is up
25572to the programmer to elaborate declarations in an appropriate order. For
25573example writing:
25574
25575@smallexample @c ada
25576@group
25577@cartouche
25578function One return Float;
25579
25580Q : Float := One;
25581
25582function One return Float is
25583begin
25584     return 1.0;
25585end One;
25586@end cartouche
25587@end group
25588@end smallexample
25589
25590@noindent
25591will obviously raise @code{Program_Error} at run time, because function
25592One will be called before its body is elaborated. In this case GNAT will
25593generate a warning that the call will raise @code{Program_Error}:
25594
25595@smallexample
25596@group
25597@cartouche
25598 1. procedure y is
25599 2.    function One return Float;
25600 3.
25601 4.    Q : Float := One;
25602                    |
25603    >>> warning: cannot call "One" before body is elaborated
25604    >>> warning: Program_Error will be raised at run time
25605
25606 5.
25607 6.    function One return Float is
25608 7.    begin
25609 8.         return 1.0;
25610 9.    end One;
2561110.
2561211. begin
2561312.    null;
2561413. end;
25615@end cartouche
25616@end group
25617@end smallexample
25618
25619@noindent
25620Note that in this particular case, it is likely that the call is safe, because
25621the function @code{One} does not access any global variables.
25622Nevertheless in Ada, we do not want the validity of the check to depend on
25623the contents of the body (think about the separate compilation case), so this
25624is still wrong, as we discussed in the previous sections.
25625
25626The error is easily corrected by rearranging the declarations so that the
25627body of @code{One} appears before the declaration containing the call
25628(note that in Ada 95 and Ada 2005,
25629declarations can appear in any order, so there is no restriction that
25630would prevent this reordering, and if we write:
25631
25632@smallexample @c ada
25633@group
25634@cartouche
25635function One return Float;
25636
25637function One return Float is
25638begin
25639     return 1.0;
25640end One;
25641
25642Q : Float := One;
25643@end cartouche
25644@end group
25645@end smallexample
25646
25647@noindent
25648then all is well, no warning is generated, and no
25649@code{Program_Error} exception
25650will be raised.
25651Things are more complicated when a chain of subprograms is executed:
25652
25653@smallexample @c ada
25654@group
25655@cartouche
25656function A return Integer;
25657function B return Integer;
25658function C return Integer;
25659
25660function B return Integer is begin return A; end;
25661function C return Integer is begin return B; end;
25662
25663X : Integer := C;
25664
25665function A return Integer is begin return 1; end;
25666@end cartouche
25667@end group
25668@end smallexample
25669
25670@noindent
25671Now the call to @code{C}
25672at elaboration time in the declaration of @code{X} is correct, because
25673the body of @code{C} is already elaborated,
25674and the call to @code{B} within the body of
25675@code{C} is correct, but the call
25676to @code{A} within the body of @code{B} is incorrect, because the body
25677of @code{A} has not been elaborated, so @code{Program_Error}
25678will be raised on the call to @code{A}.
25679In this case GNAT will generate a
25680warning that @code{Program_Error} may be
25681raised at the point of the call. Let's look at the warning:
25682
25683@smallexample
25684@group
25685@cartouche
25686 1. procedure x is
25687 2.    function A return Integer;
25688 3.    function B return Integer;
25689 4.    function C return Integer;
25690 5.
25691 6.    function B return Integer is begin return A; end;
25692                                                    |
25693    >>> warning: call to "A" before body is elaborated may
25694                 raise Program_Error
25695    >>> warning: "B" called at line 7
25696    >>> warning: "C" called at line 9
25697
25698 7.    function C return Integer is begin return B; end;
25699 8.
25700 9.    X : Integer := C;
2570110.
2570211.    function A return Integer is begin return 1; end;
2570312.
2570413. begin
2570514.    null;
2570615. end;
25707@end cartouche
25708@end group
25709@end smallexample
25710
25711@noindent
25712Note that the message here says ``may raise'', instead of the direct case,
25713where the message says ``will be raised''. That's because whether
25714@code{A} is
25715actually called depends in general on run-time flow of control.
25716For example, if the body of @code{B} said
25717
25718@smallexample @c ada
25719@group
25720@cartouche
25721function B return Integer is
25722begin
25723   if some-condition-depending-on-input-data then
25724      return A;
25725   else
25726      return 1;
25727   end if;
25728end B;
25729@end cartouche
25730@end group
25731@end smallexample
25732
25733@noindent
25734then we could not know until run time whether the incorrect call to A would
25735actually occur, so @code{Program_Error} might
25736or might not be raised. It is possible for a compiler to
25737do a better job of analyzing bodies, to
25738determine whether or not @code{Program_Error}
25739might be raised, but it certainly
25740couldn't do a perfect job (that would require solving the halting problem
25741and is provably impossible), and because this is a warning anyway, it does
25742not seem worth the effort to do the analysis. Cases in which it
25743would be relevant are rare.
25744
25745In practice, warnings of either of the forms given
25746above will usually correspond to
25747real errors, and should be examined carefully and eliminated.
25748In the rare case where a warning is bogus, it can be suppressed by any of
25749the following methods:
25750
25751@itemize @bullet
25752@item
25753Compile with the @option{-gnatws} switch set
25754
25755@item
25756Suppress @code{Elaboration_Check} for the called subprogram
25757
25758@item
25759Use pragma @code{Warnings_Off} to turn warnings off for the call
25760@end itemize
25761
25762@noindent
25763For the internal elaboration check case,
25764GNAT by default generates the
25765necessary run-time checks to ensure
25766that @code{Program_Error} is raised if any
25767call fails an elaboration check. Of course this can only happen if a
25768warning has been issued as described above. The use of pragma
25769@code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25770some of these checks, meaning that it may be possible (but is not
25771guaranteed) for a program to be able to call a subprogram whose body
25772is not yet elaborated, without raising a @code{Program_Error} exception.
25773
25774@node Controlling Elaboration in GNAT - External Calls
25775@section Controlling Elaboration in GNAT - External Calls
25776
25777@noindent
25778The previous section discussed the case in which the execution of a
25779particular thread of elaboration code occurred entirely within a
25780single unit. This is the easy case to handle, because a programmer
25781has direct and total control over the order of elaboration, and
25782furthermore, checks need only be generated in cases which are rare
25783and which the compiler can easily detect.
25784The situation is more complex when separate compilation is taken into account.
25785Consider the following:
25786
25787@smallexample @c ada
25788@cartouche
25789@group
25790package Math is
25791   function Sqrt (Arg : Float) return Float;
25792end Math;
25793
25794package body Math is
25795   function Sqrt (Arg : Float) return Float is
25796   begin
25797         @dots{}
25798   end Sqrt;
25799end Math;
25800@end group
25801@group
25802with Math;
25803package Stuff is
25804   X : Float := Math.Sqrt (0.5);
25805end Stuff;
25806
25807with Stuff;
25808procedure Main is
25809begin
25810   @dots{}
25811end Main;
25812@end group
25813@end cartouche
25814@end smallexample
25815
25816@noindent
25817where @code{Main} is the main program. When this program is executed, the
25818elaboration code must first be executed, and one of the jobs of the
25819binder is to determine the order in which the units of a program are
25820to be elaborated. In this case we have four units: the spec and body
25821of @code{Math},
25822the spec of @code{Stuff} and the body of @code{Main}).
25823In what order should the four separate sections of elaboration code
25824be executed?
25825
25826There are some restrictions in the order of elaboration that the binder
25827can choose. In particular, if unit U has a @code{with}
25828for a package @code{X}, then you
25829are assured that the spec of @code{X}
25830is elaborated before U , but you are
25831not assured that the body of @code{X}
25832is elaborated before U.
25833This means that in the above case, the binder is allowed to choose the
25834order:
25835
25836@smallexample
25837spec of Math
25838spec of Stuff
25839body of Math
25840body of Main
25841@end smallexample
25842
25843@noindent
25844but that's not good, because now the call to @code{Math.Sqrt}
25845that happens during
25846the elaboration of the @code{Stuff}
25847spec happens before the body of @code{Math.Sqrt} is
25848elaborated, and hence causes @code{Program_Error} exception to be raised.
25849At first glance, one might say that the binder is misbehaving, because
25850obviously you want to elaborate the body of something you @code{with}
25851first, but
25852that is not a general rule that can be followed in all cases. Consider
25853
25854@smallexample @c ada
25855@group
25856@cartouche
25857package X is @dots{}
25858
25859package Y is @dots{}
25860
25861with X;
25862package body Y is @dots{}
25863
25864with Y;
25865package body X is @dots{}
25866@end cartouche
25867@end group
25868@end smallexample
25869
25870@noindent
25871This is a common arrangement, and, apart from the order of elaboration
25872problems that might arise in connection with elaboration code, this works fine.
25873A rule that says that you must first elaborate the body of anything you
25874@code{with} cannot work in this case:
25875the body of @code{X} @code{with}'s @code{Y},
25876which means you would have to
25877elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
25878which means
25879you have to elaborate the body of @code{X} first, but @dots{} and we have a
25880loop that cannot be broken.
25881
25882It is true that the binder can in many cases guess an order of elaboration
25883that is unlikely to cause a @code{Program_Error}
25884exception to be raised, and it tries to do so (in the
25885above example of @code{Math/Stuff/Spec}, the GNAT binder will
25886by default
25887elaborate the body of @code{Math} right after its spec, so all will be well).
25888
25889However, a program that blindly relies on the binder to be helpful can
25890get into trouble, as we discussed in the previous sections, so
25891GNAT
25892provides a number of facilities for assisting the programmer in
25893developing programs that are robust with respect to elaboration order.
25894
25895@node Default Behavior in GNAT - Ensuring Safety
25896@section Default Behavior in GNAT - Ensuring Safety
25897
25898@noindent
25899The default behavior in GNAT ensures elaboration safety. In its
25900default mode GNAT implements the
25901rule we previously described as the right approach. Let's restate it:
25902
25903@itemize
25904@item
25905@emph{If a unit has elaboration code that can directly or indirectly make a
25906call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25907package in a @code{with}'ed unit, then if the @code{with}'ed unit
25908does not have pragma @code{Pure} or
25909@code{Preelaborate}, then the client should have an
25910@code{Elaborate_All} pragma for the @code{with}'ed unit.}
25911
25912@emph{In the case of instantiating a generic subprogram, it is always
25913sufficient to have only an @code{Elaborate} pragma for the
25914@code{with}'ed unit.}
25915@end itemize
25916
25917@noindent
25918By following this rule a client is assured that calls and instantiations
25919can be made without risk of an exception.
25920
25921In this mode GNAT traces all calls that are potentially made from
25922elaboration code, and puts in any missing implicit @code{Elaborate}
25923and @code{Elaborate_All} pragmas.
25924The advantage of this approach is that no elaboration problems
25925are possible if the binder can find an elaboration order that is
25926consistent with these implicit @code{Elaborate} and
25927@code{Elaborate_All} pragmas. The
25928disadvantage of this approach is that no such order may exist.
25929
25930If the binder does not generate any diagnostics, then it means that it has
25931found an elaboration order that is guaranteed to be safe. However, the binder
25932may still be relying on implicitly generated @code{Elaborate} and
25933@code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25934guaranteed.
25935
25936If it is important to guarantee portability, then the compilations should
25937use the
25938@option{-gnatel}
25939(info messages for elaboration prag mas) switch. This will cause info messages
25940to be generated indicating the missing @code{Elaborate} and
25941@code{Elaborate_All} pragmas.
25942Consider the following source program:
25943
25944@smallexample @c ada
25945@group
25946@cartouche
25947with k;
25948package j is
25949  m : integer := k.r;
25950end;
25951@end cartouche
25952@end group
25953@end smallexample
25954
25955@noindent
25956where it is clear that there
25957should be a pragma @code{Elaborate_All}
25958for unit @code{k}. An implicit pragma will be generated, and it is
25959likely that the binder will be able to honor it. However, if you want
25960to port this program to some other Ada compiler than GNAT.
25961it is safer to include the pragma explicitly in the source. If this
25962unit is compiled with the
25963@option{-gnatel}
25964switch, then the compiler outputs an information message:
25965
25966@smallexample
25967@group
25968@cartouche
259691. with k;
259702. package j is
259713.   m : integer := k.r;
25972                     |
25973   >>> info: call to "r" may raise Program_Error
25974   >>> info: missing pragma Elaborate_All for "k"
25975
259764. end;
25977@end cartouche
25978@end group
25979@end smallexample
25980
25981@noindent
25982and these messages can be used as a guide for supplying manually
25983the missing pragmas. It is usually a bad idea to use this
25984option during development. That's because it will tell you when
25985you need to put in a pragma, but cannot tell you when it is time
25986to take it out. So the use of pragma @code{Elaborate_All} may lead to
25987unnecessary dependencies and even false circularities.
25988
25989This default mode is more restrictive than the Ada Reference
25990Manual, and it is possible to construct programs which will compile
25991using the dynamic model described there, but will run into a
25992circularity using the safer static model we have described.
25993
25994Of course any Ada compiler must be able to operate in a mode
25995consistent with the requirements of the Ada Reference Manual,
25996and in particular must have the capability of implementing the
25997standard dynamic model of elaboration with run-time checks.
25998
25999In GNAT, this standard mode can be achieved either by the use of
26000the @option{-gnatE} switch on the compiler (@command{gcc} or
26001@command{gnatmake}) command, or by the use of the configuration pragma:
26002
26003@smallexample @c ada
26004pragma Elaboration_Checks (DYNAMIC);
26005@end smallexample
26006
26007@noindent
26008Either approach will cause the unit affected to be compiled using the
26009standard dynamic run-time elaboration checks described in the Ada
26010Reference Manual. The static model is generally preferable, since it
26011is clearly safer to rely on compile and link time checks rather than
26012run-time checks. However, in the case of legacy code, it may be
26013difficult to meet the requirements of the static model. This
26014issue is further discussed in
26015@ref{What to Do If the Default Elaboration Behavior Fails}.
26016
26017Note that the static model provides a strict subset of the allowed
26018behavior and programs of the Ada Reference Manual, so if you do
26019adhere to the static model and no circularities exist,
26020then you are assured that your program will
26021work using the dynamic model, providing that you remove any
26022pragma Elaborate statements from the source.
26023
26024@node Treatment of Pragma Elaborate
26025@section Treatment of Pragma Elaborate
26026@cindex Pragma Elaborate
26027
26028@noindent
26029The use of @code{pragma Elaborate}
26030should generally be avoided in Ada 95 and Ada 2005 programs,
26031since there is no guarantee that transitive calls
26032will be properly handled. Indeed at one point, this pragma was placed
26033in Annex J (Obsolescent Features), on the grounds that it is never useful.
26034
26035Now that's a bit restrictive. In practice, the case in which
26036@code{pragma Elaborate} is useful is when the caller knows that there
26037are no transitive calls, or that the called unit contains all necessary
26038transitive @code{pragma Elaborate} statements, and legacy code often
26039contains such uses.
26040
26041Strictly speaking the static mode in GNAT should ignore such pragmas,
26042since there is no assurance at compile time that the necessary safety
26043conditions are met. In practice, this would cause GNAT to be incompatible
26044with correctly written Ada 83 code that had all necessary
26045@code{pragma Elaborate} statements in place. Consequently, we made the
26046decision that GNAT in its default mode will believe that if it encounters
26047a @code{pragma Elaborate} then the programmer knows what they are doing,
26048and it will trust that no elaboration errors can occur.
26049
26050The result of this decision is two-fold. First to be safe using the
26051static mode, you should remove all @code{pragma Elaborate} statements.
26052Second, when fixing circularities in existing code, you can selectively
26053use @code{pragma Elaborate} statements to convince the static mode of
26054GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26055statement.
26056
26057When using the static mode with @option{-gnatwl}, any use of
26058@code{pragma Elaborate} will generate a warning about possible
26059problems.
26060
26061@node Elaboration Issues for Library Tasks
26062@section Elaboration Issues for Library Tasks
26063@cindex Library tasks, elaboration issues
26064@cindex Elaboration of library tasks
26065
26066@noindent
26067In this section we examine special elaboration issues that arise for
26068programs that declare library level tasks.
26069
26070Generally the model of execution of an Ada program is that all units are
26071elaborated, and then execution of the program starts. However, the
26072declaration of library tasks definitely does not fit this model. The
26073reason for this is that library tasks start as soon as they are declared
26074(more precisely, as soon as the statement part of the enclosing package
26075body is reached), that is to say before elaboration
26076of the program is complete. This means that if such a task calls a
26077subprogram, or an entry in another task, the callee may or may not be
26078elaborated yet, and in the standard
26079Reference Manual model of dynamic elaboration checks, you can even
26080get timing dependent Program_Error exceptions, since there can be
26081a race between the elaboration code and the task code.
26082
26083The static model of elaboration in GNAT seeks to avoid all such
26084dynamic behavior, by being conservative, and the conservative
26085approach in this particular case is to assume that all the code
26086in a task body is potentially executed at elaboration time if
26087a task is declared at the library level.
26088
26089This can definitely result in unexpected circularities. Consider
26090the following example
26091
26092@smallexample @c ada
26093package Decls is
26094  task Lib_Task is
26095     entry Start;
26096  end Lib_Task;
26097
26098  type My_Int is new Integer;
26099
26100  function Ident (M : My_Int) return My_Int;
26101end Decls;
26102
26103with Utils;
26104package body Decls is
26105  task body Lib_Task is
26106  begin
26107     accept Start;
26108     Utils.Put_Val (2);
26109  end Lib_Task;
26110
26111  function Ident (M : My_Int) return My_Int is
26112  begin
26113     return M;
26114  end Ident;
26115end Decls;
26116
26117with Decls;
26118package Utils is
26119  procedure Put_Val (Arg : Decls.My_Int);
26120end Utils;
26121
26122with Text_IO;
26123package body Utils is
26124  procedure Put_Val (Arg : Decls.My_Int) is
26125  begin
26126     Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26127  end Put_Val;
26128end Utils;
26129
26130with Decls;
26131procedure Main is
26132begin
26133   Decls.Lib_Task.Start;
26134end;
26135@end smallexample
26136
26137@noindent
26138If the above example is compiled in the default static elaboration
26139mode, then a circularity occurs. The circularity comes from the call
26140@code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26141this call occurs in elaboration code, we need an implicit pragma
26142@code{Elaborate_All} for @code{Utils}. This means that not only must
26143the spec and body of @code{Utils} be elaborated before the body
26144of @code{Decls}, but also the spec and body of any unit that is
26145@code{with'ed} by the body of @code{Utils} must also be elaborated before
26146the body of @code{Decls}. This is the transitive implication of
26147pragma @code{Elaborate_All} and it makes sense, because in general
26148the body of @code{Put_Val} might have a call to something in a
26149@code{with'ed} unit.
26150
26151In this case, the body of Utils (actually its spec) @code{with's}
26152@code{Decls}. Unfortunately this means that the body of @code{Decls}
26153must be elaborated before itself, in case there is a call from the
26154body of @code{Utils}.
26155
26156Here is the exact chain of events we are worrying about:
26157
26158@enumerate
26159@item
26160In the body of @code{Decls} a call is made from within the body of a library
26161task to a subprogram in the package @code{Utils}. Since this call may
26162occur at elaboration time (given that the task is activated at elaboration
26163time), we have to assume the worst, i.e., that the
26164call does happen at elaboration time.
26165
26166@item
26167This means that the body and spec of @code{Util} must be elaborated before
26168the body of @code{Decls} so that this call does not cause an access before
26169elaboration.
26170
26171@item
26172Within the body of @code{Util}, specifically within the body of
26173@code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26174by this package.
26175
26176@item
26177One such @code{with}'ed package is package @code{Decls}, so there
26178might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26179In fact there is such a call in this example, but we would have to
26180assume that there was such a call even if it were not there, since
26181we are not supposed to write the body of @code{Decls} knowing what
26182is in the body of @code{Utils}; certainly in the case of the
26183static elaboration model, the compiler does not know what is in
26184other bodies and must assume the worst.
26185
26186@item
26187This means that the spec and body of @code{Decls} must also be
26188elaborated before we elaborate the unit containing the call, but
26189that unit is @code{Decls}! This means that the body of @code{Decls}
26190must be elaborated before itself, and that's a circularity.
26191@end enumerate
26192
26193@noindent
26194Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26195the body of @code{Decls} you will get a true Ada Reference Manual
26196circularity that makes the program illegal.
26197
26198In practice, we have found that problems with the static model of
26199elaboration in existing code often arise from library tasks, so
26200we must address this particular situation.
26201
26202Note that if we compile and run the program above, using the dynamic model of
26203elaboration (that is to say use the @option{-gnatE} switch),
26204then it compiles, binds,
26205links, and runs, printing the expected result of 2. Therefore in some sense
26206the circularity here is only apparent, and we need to capture
26207the properties of this program that  distinguish it from other library-level
26208tasks that have real elaboration problems.
26209
26210We have four possible answers to this question:
26211
26212@itemize @bullet
26213
26214@item
26215Use the dynamic model of elaboration.
26216
26217If we use the @option{-gnatE} switch, then as noted above, the program works.
26218Why is this? If we examine the task body, it is apparent that the task cannot
26219proceed past the
26220@code{accept} statement until after elaboration has been completed, because
26221the corresponding entry call comes from the main program, not earlier.
26222This is why the dynamic model works here. But that's really giving
26223up on a precise analysis, and we prefer to take this approach only if we cannot
26224solve the
26225problem in any other manner. So let us examine two ways to reorganize
26226the program to avoid the potential elaboration problem.
26227
26228@item
26229Split library tasks into separate packages.
26230
26231Write separate packages, so that library tasks are isolated from
26232other declarations as much as possible. Let us look at a variation on
26233the above program.
26234
26235@smallexample @c ada
26236package Decls1 is
26237  task Lib_Task is
26238     entry Start;
26239  end Lib_Task;
26240end Decls1;
26241
26242with Utils;
26243package body Decls1 is
26244  task body Lib_Task is
26245  begin
26246     accept Start;
26247     Utils.Put_Val (2);
26248  end Lib_Task;
26249end Decls1;
26250
26251package Decls2 is
26252  type My_Int is new Integer;
26253  function Ident (M : My_Int) return My_Int;
26254end Decls2;
26255
26256with Utils;
26257package body Decls2 is
26258  function Ident (M : My_Int) return My_Int is
26259  begin
26260     return M;
26261  end Ident;
26262end Decls2;
26263
26264with Decls2;
26265package Utils is
26266  procedure Put_Val (Arg : Decls2.My_Int);
26267end Utils;
26268
26269with Text_IO;
26270package body Utils is
26271  procedure Put_Val (Arg : Decls2.My_Int) is
26272  begin
26273     Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26274  end Put_Val;
26275end Utils;
26276
26277with Decls1;
26278procedure Main is
26279begin
26280   Decls1.Lib_Task.Start;
26281end;
26282@end smallexample
26283
26284@noindent
26285All we have done is to split @code{Decls} into two packages, one
26286containing the library task, and one containing everything else. Now
26287there is no cycle, and the program compiles, binds, links and executes
26288using the default static model of elaboration.
26289
26290@item
26291Declare separate task types.
26292
26293A significant part of the problem arises because of the use of the
26294single task declaration form. This means that the elaboration of
26295the task type, and the elaboration of the task itself (i.e.@: the
26296creation of the task) happen at the same time. A good rule
26297of style in Ada is to always create explicit task types. By
26298following the additional step of placing task objects in separate
26299packages from the task type declaration, many elaboration problems
26300are avoided. Here is another modified example of the example program:
26301
26302@smallexample @c ada
26303package Decls is
26304  task type Lib_Task_Type is
26305     entry Start;
26306  end Lib_Task_Type;
26307
26308  type My_Int is new Integer;
26309
26310  function Ident (M : My_Int) return My_Int;
26311end Decls;
26312
26313with Utils;
26314package body Decls is
26315  task body Lib_Task_Type is
26316  begin
26317     accept Start;
26318     Utils.Put_Val (2);
26319  end Lib_Task_Type;
26320
26321  function Ident (M : My_Int) return My_Int is
26322  begin
26323     return M;
26324  end Ident;
26325end Decls;
26326
26327with Decls;
26328package Utils is
26329  procedure Put_Val (Arg : Decls.My_Int);
26330end Utils;
26331
26332with Text_IO;
26333package body Utils is
26334  procedure Put_Val (Arg : Decls.My_Int) is
26335  begin
26336     Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26337  end Put_Val;
26338end Utils;
26339
26340with Decls;
26341package Declst is
26342   Lib_Task : Decls.Lib_Task_Type;
26343end Declst;
26344
26345with Declst;
26346procedure Main is
26347begin
26348   Declst.Lib_Task.Start;
26349end;
26350@end smallexample
26351
26352@noindent
26353What we have done here is to replace the @code{task} declaration in
26354package @code{Decls} with a @code{task type} declaration. Then we
26355introduce a separate package @code{Declst} to contain the actual
26356task object. This separates the elaboration issues for
26357the @code{task type}
26358declaration, which causes no trouble, from the elaboration issues
26359of the task object, which is also unproblematic, since it is now independent
26360of the elaboration of  @code{Utils}.
26361This separation of concerns also corresponds to
26362a generally sound engineering principle of separating declarations
26363from instances. This version of the program also compiles, binds, links,
26364and executes, generating the expected output.
26365
26366@item
26367Use No_Entry_Calls_In_Elaboration_Code restriction.
26368@cindex No_Entry_Calls_In_Elaboration_Code
26369
26370The previous two approaches described how a program can be restructured
26371to avoid the special problems caused by library task bodies. in practice,
26372however, such restructuring may be difficult to apply to existing legacy code,
26373so we must consider solutions that do not require massive rewriting.
26374
26375Let us consider more carefully why our original sample program works
26376under the dynamic model of elaboration. The reason is that the code
26377in the task body blocks immediately on the @code{accept}
26378statement. Now of course there is nothing to prohibit elaboration
26379code from making entry calls (for example from another library level task),
26380so we cannot tell in isolation that
26381the task will not execute the accept statement  during elaboration.
26382
26383However, in practice it is very unusual to see elaboration code
26384make any entry calls, and the pattern of tasks starting
26385at elaboration time and then immediately blocking on @code{accept} or
26386@code{select} statements is very common. What this means is that
26387the compiler is being too pessimistic when it analyzes the
26388whole package body as though it might be executed at elaboration
26389time.
26390
26391If we know that the elaboration code contains no entry calls, (a very safe
26392assumption most of the time, that could almost be made the default
26393behavior), then we can compile all units of the program under control
26394of the following configuration pragma:
26395
26396@smallexample
26397pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26398@end smallexample
26399
26400@noindent
26401This pragma can be placed in the @file{gnat.adc} file in the usual
26402manner. If we take our original unmodified program and compile it
26403in the presence of a @file{gnat.adc} containing the above pragma,
26404then once again, we can compile, bind, link, and execute, obtaining
26405the expected result. In the presence of this pragma, the compiler does
26406not trace calls in a task body, that appear after the first @code{accept}
26407or @code{select} statement, and therefore does not report a potential
26408circularity in the original program.
26409
26410The compiler will check to the extent it can that the above
26411restriction is not violated, but it is not always possible to do a
26412complete check at compile time, so it is important to use this
26413pragma only if the stated restriction is in fact met, that is to say
26414no task receives an entry call before elaboration of all units is completed.
26415
26416@end itemize
26417
26418@node Mixing Elaboration Models
26419@section Mixing Elaboration Models
26420@noindent
26421So far, we have assumed that the entire program is either compiled
26422using the dynamic model or static model, ensuring consistency. It
26423is possible to mix the two models, but rules have to be followed
26424if this mixing is done to ensure that elaboration checks are not
26425omitted.
26426
26427The basic rule is that @emph{a unit compiled with the static model cannot
26428be @code{with'ed} by a unit compiled with the dynamic model}. The
26429reason for this is that in the static model, a unit assumes that
26430its clients guarantee to use (the equivalent of) pragma
26431@code{Elaborate_All} so that no elaboration checks are required
26432in inner subprograms, and this assumption is violated if the
26433client is compiled with dynamic checks.
26434
26435The precise rule is as follows. A unit that is compiled with dynamic
26436checks can only @code{with} a unit that meets at least one of the
26437following criteria:
26438
26439@itemize @bullet
26440
26441@item
26442The @code{with'ed} unit is itself compiled with dynamic elaboration
26443checks (that is with the @option{-gnatE} switch.
26444
26445@item
26446The @code{with'ed} unit is an internal GNAT implementation unit from
26447the System, Interfaces, Ada, or GNAT hierarchies.
26448
26449@item
26450The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26451
26452@item
26453The @code{with'ing} unit (that is the client) has an explicit pragma
26454@code{Elaborate_All} for the @code{with'ed} unit.
26455
26456@end itemize
26457
26458@noindent
26459If this rule is violated, that is if a unit with dynamic elaboration
26460checks @code{with's} a unit that does not meet one of the above four
26461criteria, then the binder (@code{gnatbind}) will issue a warning
26462similar to that in the following example:
26463
26464@smallexample
26465warning: "x.ads" has dynamic elaboration checks and with's
26466warning:   "y.ads" which has static elaboration checks
26467@end smallexample
26468
26469@noindent
26470These warnings indicate that the rule has been violated, and that as a result
26471elaboration checks may be missed in the resulting executable file.
26472This warning may be suppressed using the @option{-ws} binder switch
26473in the usual manner.
26474
26475One useful application of this mixing rule is in the case of a subsystem
26476which does not itself @code{with} units from the remainder of the
26477application. In this case, the entire subsystem can be compiled with
26478dynamic checks to resolve a circularity in the subsystem, while
26479allowing the main application that uses this subsystem to be compiled
26480using the more reliable default static model.
26481
26482@node What to Do If the Default Elaboration Behavior Fails
26483@section What to Do If the Default Elaboration Behavior Fails
26484
26485@noindent
26486If the binder cannot find an acceptable order, it outputs detailed
26487diagnostics. For example:
26488@smallexample
26489@group
26490@iftex
26491@leftskip=0cm
26492@end iftex
26493error: elaboration circularity detected
26494info:   "proc (body)" must be elaborated before "pack (body)"
26495info:     reason: Elaborate_All probably needed in unit "pack (body)"
26496info:     recompile "pack (body)" with -gnatel
26497info:                             for full details
26498info:       "proc (body)"
26499info:         is needed by its spec:
26500info:       "proc (spec)"
26501info:         which is withed by:
26502info:       "pack (body)"
26503info:  "pack (body)" must be elaborated before "proc (body)"
26504info:     reason: pragma Elaborate in unit "proc (body)"
26505@end group
26506
26507@end smallexample
26508
26509@noindent
26510In this case we have a cycle that the binder cannot break. On the one
26511hand, there is an explicit pragma Elaborate in @code{proc} for
26512@code{pack}. This means that the body of @code{pack} must be elaborated
26513before the body of @code{proc}. On the other hand, there is elaboration
26514code in @code{pack} that calls a subprogram in @code{proc}. This means
26515that for maximum safety, there should really be a pragma
26516Elaborate_All in @code{pack} for @code{proc} which would require that
26517the body of @code{proc} be elaborated before the body of
26518@code{pack}. Clearly both requirements cannot be satisfied.
26519Faced with a circularity of this kind, you have three different options.
26520
26521@table @asis
26522@item Fix the program
26523The most desirable option from the point of view of long-term maintenance
26524is to rearrange the program so that the elaboration problems are avoided.
26525One useful technique is to place the elaboration code into separate
26526child packages. Another is to move some of the initialization code to
26527explicitly called subprograms, where the program controls the order
26528of initialization explicitly. Although this is the most desirable option,
26529it may be impractical and involve too much modification, especially in
26530the case of complex legacy code.
26531
26532@item Perform dynamic checks
26533If the compilations are done using the
26534@option{-gnatE}
26535(dynamic elaboration check) switch, then GNAT behaves in a quite different
26536manner. Dynamic checks are generated for all calls that could possibly result
26537in raising an exception. With this switch, the compiler does not generate
26538implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26539exactly as specified in the @cite{Ada Reference Manual}.
26540The binder will generate
26541an executable program that may or may not raise @code{Program_Error}, and then
26542it is the programmer's job to ensure that it does not raise an exception. Note
26543that it is important to compile all units with the switch, it cannot be used
26544selectively.
26545
26546@item Suppress checks
26547The drawback of dynamic checks is that they generate a
26548significant overhead at run time, both in space and time. If you
26549are absolutely sure that your program cannot raise any elaboration
26550exceptions, and you still want to use the dynamic elaboration model,
26551then you can use the configuration pragma
26552@code{Suppress (Elaboration_Check)} to suppress all such checks. For
26553example this pragma could be placed in the @file{gnat.adc} file.
26554
26555@item Suppress checks selectively
26556When you know that certain calls or instantiations in elaboration code cannot
26557possibly lead to an elaboration error, and the binder nevertheless complains
26558about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26559elaboration circularities, it is possible to remove those warnings locally and
26560obtain a program that will bind. Clearly this can be unsafe, and it is the
26561responsibility of the programmer to make sure that the resulting program has no
26562elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26563used with different granularity to suppress warnings and break elaboration
26564circularities:
26565
26566@itemize @bullet
26567@item
26568Place the pragma that names the called subprogram in the declarative part
26569that contains the call.
26570
26571@item
26572Place the pragma in the declarative part, without naming an entity. This
26573disables warnings on all calls in the corresponding  declarative region.
26574
26575@item
26576Place the pragma in the package spec that declares the called subprogram,
26577and name the subprogram. This disables warnings on all elaboration calls to
26578that subprogram.
26579
26580@item
26581Place the pragma in the package spec that declares the called subprogram,
26582without naming any entity. This disables warnings on all elaboration calls to
26583all subprograms declared in this spec.
26584
26585@item Use Pragma Elaborate
26586As previously described in section @xref{Treatment of Pragma Elaborate},
26587GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26588that no elaboration checks are required on calls to the designated unit.
26589There may be cases in which the caller knows that no transitive calls
26590can occur, so that a @code{pragma Elaborate} will be sufficient in a
26591case where @code{pragma Elaborate_All} would cause a circularity.
26592@end itemize
26593
26594@noindent
26595These five cases are listed in order of decreasing safety, and therefore
26596require increasing programmer care in their application. Consider the
26597following program:
26598
26599@smallexample @c adanocomment
26600package Pack1 is
26601  function F1 return Integer;
26602  X1 : Integer;
26603end Pack1;
26604
26605package Pack2 is
26606  function F2 return Integer;
26607  function Pure (x : integer) return integer;
26608  --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
26609  --  pragma Suppress (Elaboration_Check);              -- (4)
26610end Pack2;
26611
26612with Pack2;
26613package body Pack1 is
26614  function F1 return Integer is
26615  begin
26616    return 100;
26617  end F1;
26618  Val : integer := Pack2.Pure (11);    --  Elab. call (1)
26619begin
26620  declare
26621    --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
26622    --  pragma Suppress(Elaboration_Check);             -- (2)
26623  begin
26624    X1 := Pack2.F2 + 1;                --  Elab. call (2)
26625  end;
26626end Pack1;
26627
26628with Pack1;
26629package body Pack2 is
26630  function F2 return Integer is
26631  begin
26632     return Pack1.F1;
26633  end F2;
26634  function Pure (x : integer) return integer is
26635  begin
26636     return x ** 3 - 3 * x;
26637  end;
26638end Pack2;
26639
26640with Pack1, Ada.Text_IO;
26641procedure Proc3 is
26642begin
26643  Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26644end Proc3;
26645@end smallexample
26646In the absence of any pragmas, an attempt to bind this program produces
26647the following diagnostics:
26648@smallexample
26649@group
26650@iftex
26651@leftskip=.5cm
26652@end iftex
26653error: elaboration circularity detected
26654info:    "pack1 (body)" must be elaborated before "pack1 (body)"
26655info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
26656info:       recompile "pack1 (body)" with -gnatel for full details
26657info:          "pack1 (body)"
26658info:             must be elaborated along with its spec:
26659info:          "pack1 (spec)"
26660info:             which is withed by:
26661info:          "pack2 (body)"
26662info:             which must be elaborated along with its spec:
26663info:          "pack2 (spec)"
26664info:             which is withed by:
26665info:          "pack1 (body)"
26666@end group
26667@end smallexample
26668The sources of the circularity are the two calls to @code{Pack2.Pure} and
26669@code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26670F2 is safe, even though F2 calls F1, because the call appears after the
26671elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26672remove the warning on the call. It is also possible to use pragma (2)
26673because there are no other potentially unsafe calls in the block.
26674
26675@noindent
26676The call to @code{Pure} is safe because this function does not depend on the
26677state of @code{Pack2}. Therefore any call to this function is safe, and it
26678is correct to place pragma (3) in the corresponding package spec.
26679
26680@noindent
26681Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26682warnings on all calls to functions declared therein. Note that this is not
26683necessarily safe, and requires more detailed examination of the subprogram
26684bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26685be already elaborated.
26686@end table
26687
26688@noindent
26689It is hard to generalize on which of these four approaches should be
26690taken. Obviously if it is possible to fix the program so that the default
26691treatment works, this is preferable, but this may not always be practical.
26692It is certainly simple enough to use
26693@option{-gnatE}
26694but the danger in this case is that, even if the GNAT binder
26695finds a correct elaboration order, it may not always do so,
26696and certainly a binder from another Ada compiler might not. A
26697combination of testing and analysis (for which the
26698information messages generated with the
26699@option{-gnatel}
26700switch can be useful) must be used to ensure that the program is free
26701of errors. One switch that is useful in this testing is the
26702@option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26703switch for
26704@code{gnatbind}.
26705Normally the binder tries to find an order that has the best chance
26706of avoiding elaboration problems. However, if this switch is used, the binder
26707plays a devil's advocate role, and tries to choose the order that
26708has the best chance of failing. If your program works even with this
26709switch, then it has a better chance of being error free, but this is still
26710not a guarantee.
26711
26712For an example of this approach in action, consider the C-tests (executable
26713tests) from the ACVC suite. If these are compiled and run with the default
26714treatment, then all but one of them succeed without generating any error
26715diagnostics from the binder. However, there is one test that fails, and
26716this is not surprising, because the whole point of this test is to ensure
26717that the compiler can handle cases where it is impossible to determine
26718a correct order statically, and it checks that an exception is indeed
26719raised at run time.
26720
26721This one test must be compiled and run using the
26722@option{-gnatE}
26723switch, and then it passes. Alternatively, the entire suite can
26724be run using this switch. It is never wrong to run with the dynamic
26725elaboration switch if your code is correct, and we assume that the
26726C-tests are indeed correct (it is less efficient, but efficiency is
26727not a factor in running the ACVC tests.)
26728
26729@node Elaboration for Indirect Calls
26730@section Elaboration for Indirect Calls
26731@cindex Dispatching calls
26732@cindex Indirect calls
26733
26734@noindent
26735In rare cases, the static elaboration model fails to prevent
26736dispatching calls to not-yet-elaborated subprograms. In such cases, we
26737fall back to run-time checks; premature calls to any primitive
26738operation of a tagged type before the body of the operation has been
26739elaborated will raise @code{Program_Error}.
26740
26741Access-to-subprogram types, however, are handled conservatively, and
26742do not require run-time checks. This was not true in earlier versions
26743of the compiler; you can use the @option{-gnatd.U} debug switch to
26744revert to the old behavior if the new conservative behavior causes
26745elaboration cycles. Here, ``conservative'' means that if you do
26746@code{P'Access} during elaboration, the compiler will assume that you
26747might call @code{P} indirectly during elaboration, so it adds an
26748implicit @code{pragma Elaborate_All} on the library unit containing
26749@code{P}. The @option{-gnatd.U} switch is safe if you know there are
26750no such calls. If the program worked before, it will continue to work
26751with @option{-gnatd.U}. But beware that code modifications such as
26752adding an indirect call can cause erroneous behavior in the presence
26753of @option{-gnatd.U}.
26754
26755@node Summary of Procedures for Elaboration Control
26756@section Summary of Procedures for Elaboration Control
26757@cindex Elaboration control
26758
26759@noindent
26760First, compile your program with the default options, using none of
26761the special elaboration control switches. If the binder successfully
26762binds your program, then you can be confident that, apart from issues
26763raised by the use of access-to-subprogram types and dynamic dispatching,
26764the program is free of elaboration errors. If it is important that the
26765program be portable to other compilers than GNAT, then use the
26766@option{-gnatel}
26767switch to generate messages about missing @code{Elaborate} or
26768@code{Elaborate_All} pragmas, and supply the missing pragmas.
26769
26770If the program fails to bind using the default static elaboration
26771handling, then you can fix the program to eliminate the binder
26772message, or recompile the entire program with the
26773@option{-gnatE} switch to generate dynamic elaboration checks,
26774and, if you are sure there really are no elaboration problems,
26775use a global pragma @code{Suppress (Elaboration_Check)}.
26776
26777@node Other Elaboration Order Considerations
26778@section Other Elaboration Order Considerations
26779@noindent
26780This section has been entirely concerned with the issue of finding a valid
26781elaboration order, as defined by the Ada Reference Manual. In a case
26782where several elaboration orders are valid, the task is to find one
26783of the possible valid elaboration orders (and the static model in GNAT
26784will ensure that this is achieved).
26785
26786The purpose of the elaboration rules in the Ada Reference Manual is to
26787make sure that no entity is accessed before it has been elaborated. For
26788a subprogram, this means that the spec and body must have been elaborated
26789before the subprogram is called. For an object, this means that the object
26790must have been elaborated before its value is read or written. A violation
26791of either of these two requirements is an access before elaboration order,
26792and this section has been all about avoiding such errors.
26793
26794In the case where more than one order of elaboration is possible, in the
26795sense that access before elaboration errors are avoided, then any one of
26796the orders is ``correct'' in the sense that it meets the requirements of
26797the Ada Reference Manual, and no such error occurs.
26798
26799However, it may be the case for a given program, that there are
26800constraints on the order of elaboration that come not from consideration
26801of avoiding elaboration errors, but rather from extra-lingual logic
26802requirements. Consider this example:
26803
26804@smallexample @c ada
26805with Init_Constants;
26806package Constants is
26807   X : Integer := 0;
26808   Y : Integer := 0;
26809end Constants;
26810
26811package Init_Constants is
26812   procedure P; -- require a body
26813end Init_Constants;
26814
26815with Constants;
26816package body Init_Constants is
26817   procedure P is begin null; end;
26818begin
26819   Constants.X := 3;
26820   Constants.Y := 4;
26821end Init_Constants;
26822
26823with Constants;
26824package Calc is
26825   Z : Integer := Constants.X + Constants.Y;
26826end Calc;
26827
26828with Calc;
26829with Text_IO; use Text_IO;
26830procedure Main is
26831begin
26832   Put_Line (Calc.Z'Img);
26833end Main;
26834@end smallexample
26835
26836@noindent
26837In this example, there is more than one valid order of elaboration. For
26838example both the following are correct orders:
26839
26840@smallexample
26841Init_Constants spec
26842Constants spec
26843Calc spec
26844Init_Constants body
26845Main body
26846
26847  and
26848
26849Init_Constants spec
26850Init_Constants body
26851Constants spec
26852Calc spec
26853Main body
26854@end smallexample
26855
26856@noindent
26857There is no language rule to prefer one or the other, both are correct
26858from an order of elaboration point of view. But the programmatic effects
26859of the two orders are very different. In the first, the elaboration routine
26860of @code{Calc} initializes @code{Z} to zero, and then the main program
26861runs with this value of zero. But in the second order, the elaboration
26862routine of @code{Calc} runs after the body of Init_Constants has set
26863@code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26864runs.
26865
26866One could perhaps by applying pretty clever non-artificial intelligence
26867to the situation guess that it is more likely that the second order of
26868elaboration is the one desired, but there is no formal linguistic reason
26869to prefer one over the other. In fact in this particular case, GNAT will
26870prefer the second order, because of the rule that bodies are elaborated
26871as soon as possible, but it's just luck that this is what was wanted
26872(if indeed the second order was preferred).
26873
26874If the program cares about the order of elaboration routines in a case like
26875this, it is important to specify the order required. In this particular
26876case, that could have been achieved by adding to the spec of Calc:
26877
26878@smallexample @c ada
26879pragma Elaborate_All (Constants);
26880@end smallexample
26881
26882@noindent
26883which requires that the body (if any) and spec of @code{Constants},
26884as well as the body and spec of any unit @code{with}'ed by
26885@code{Constants} be elaborated before @code{Calc} is elaborated.
26886
26887Clearly no automatic method can always guess which alternative you require,
26888and if you are working with legacy code that had constraints of this kind
26889which were not properly specified by adding @code{Elaborate} or
26890@code{Elaborate_All} pragmas, then indeed it is possible that two different
26891compilers can choose different orders.
26892
26893However, GNAT does attempt to diagnose the common situation where there
26894are uninitialized variables in the visible part of a package spec, and the
26895corresponding package body has an elaboration block that directly or
26896indirectly initialized one or more of these variables. This is the situation
26897in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26898a warning that suggests this addition if it detects this situation.
26899
26900The @code{gnatbind}
26901@option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26902out problems. This switch causes bodies to be elaborated as late as possible
26903instead of as early as possible. In the example above, it would have forced
26904the choice of the first elaboration order. If you get different results
26905when using this switch, and particularly if one set of results is right,
26906and one is wrong as far as you are concerned, it shows that you have some
26907missing @code{Elaborate} pragmas. For the example above, we have the
26908following output:
26909
26910@smallexample
26911gnatmake -f -q main
26912main
26913 7
26914gnatmake -f -q main -bargs -p
26915main
26916 0
26917@end smallexample
26918
26919@noindent
26920It is of course quite unlikely that both these results are correct, so
26921it is up to you in a case like this to investigate the source of the
26922difference, by looking at the two elaboration orders that are chosen,
26923and figuring out which is correct, and then adding the necessary
26924@code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26925
26926@node Determining the Chosen Elaboration Order
26927@section Determining the Chosen Elaboration Order
26928@noindent
26929
26930To see the elaboration order that the binder chooses, you can look at
26931the last part of the b~xxx.adb binder output file. Here is an example:
26932
26933@smallexample @c ada
26934System.Soft_Links'Elab_Body;
26935E14 := True;
26936System.Secondary_Stack'Elab_Body;
26937E18 := True;
26938System.Exception_Table'Elab_Body;
26939E24 := True;
26940Ada.Io_Exceptions'Elab_Spec;
26941E67 := True;
26942Ada.Tags'Elab_Spec;
26943Ada.Streams'Elab_Spec;
26944E43 := True;
26945Interfaces.C'Elab_Spec;
26946E69 := True;
26947System.Finalization_Root'Elab_Spec;
26948E60 := True;
26949System.Os_Lib'Elab_Body;
26950E71 := True;
26951System.Finalization_Implementation'Elab_Spec;
26952System.Finalization_Implementation'Elab_Body;
26953E62 := True;
26954Ada.Finalization'Elab_Spec;
26955E58 := True;
26956Ada.Finalization.List_Controller'Elab_Spec;
26957E76 := True;
26958System.File_Control_Block'Elab_Spec;
26959E74 := True;
26960System.File_Io'Elab_Body;
26961E56 := True;
26962Ada.Tags'Elab_Body;
26963E45 := True;
26964Ada.Text_Io'Elab_Spec;
26965Ada.Text_Io'Elab_Body;
26966E07 := True;
26967@end smallexample
26968
26969@noindent
26970Here Elab_Spec elaborates the spec
26971and Elab_Body elaborates the body. The assignments to the Exx flags
26972flag that the corresponding body is now elaborated.
26973
26974You can also ask the binder to generate a more
26975readable list of the elaboration order using the
26976@code{-l} switch when invoking the binder. Here is
26977an example of the output generated by this switch:
26978
26979@smallexample
26980ada (spec)
26981interfaces (spec)
26982system (spec)
26983system.case_util (spec)
26984system.case_util (body)
26985system.concat_2 (spec)
26986system.concat_2 (body)
26987system.concat_3 (spec)
26988system.concat_3 (body)
26989system.htable (spec)
26990system.parameters (spec)
26991system.parameters (body)
26992system.crtl (spec)
26993interfaces.c_streams (spec)
26994interfaces.c_streams (body)
26995system.restrictions (spec)
26996system.restrictions (body)
26997system.standard_library (spec)
26998system.exceptions (spec)
26999system.exceptions (body)
27000system.storage_elements (spec)
27001system.storage_elements (body)
27002system.secondary_stack (spec)
27003system.stack_checking (spec)
27004system.stack_checking (body)
27005system.string_hash (spec)
27006system.string_hash (body)
27007system.htable (body)
27008system.strings (spec)
27009system.strings (body)
27010system.traceback (spec)
27011system.traceback (body)
27012system.traceback_entries (spec)
27013system.traceback_entries (body)
27014ada.exceptions (spec)
27015ada.exceptions.last_chance_handler (spec)
27016system.soft_links (spec)
27017system.soft_links (body)
27018ada.exceptions.last_chance_handler (body)
27019system.secondary_stack (body)
27020system.exception_table (spec)
27021system.exception_table (body)
27022ada.io_exceptions (spec)
27023ada.tags (spec)
27024ada.streams (spec)
27025interfaces.c (spec)
27026interfaces.c (body)
27027system.finalization_root (spec)
27028system.finalization_root (body)
27029system.memory (spec)
27030system.memory (body)
27031system.standard_library (body)
27032system.os_lib (spec)
27033system.os_lib (body)
27034system.unsigned_types (spec)
27035system.stream_attributes (spec)
27036system.stream_attributes (body)
27037system.finalization_implementation (spec)
27038system.finalization_implementation (body)
27039ada.finalization (spec)
27040ada.finalization (body)
27041ada.finalization.list_controller (spec)
27042ada.finalization.list_controller (body)
27043system.file_control_block (spec)
27044system.file_io (spec)
27045system.file_io (body)
27046system.val_uns (spec)
27047system.val_util (spec)
27048system.val_util (body)
27049system.val_uns (body)
27050system.wch_con (spec)
27051system.wch_con (body)
27052system.wch_cnv (spec)
27053system.wch_jis (spec)
27054system.wch_jis (body)
27055system.wch_cnv (body)
27056system.wch_stw (spec)
27057system.wch_stw (body)
27058ada.tags (body)
27059ada.exceptions (body)
27060ada.text_io (spec)
27061ada.text_io (body)
27062text_io (spec)
27063gdbstr (body)
27064@end smallexample
27065
27066@c **********************************
27067@node Overflow Check Handling in GNAT
27068@appendix Overflow Check Handling in GNAT
27069@cindex Overflow checks
27070@cindex Checks (overflow)
27071@c **********************************
27072
27073@menu
27074* Background::
27075* Overflow Checking Modes in GNAT::
27076* Specifying the Desired Mode::
27077* Default Settings::
27078* Implementation Notes::
27079@end menu
27080
27081
27082@node Background
27083@section Background
27084
27085@noindent
27086Overflow checks are checks that the compiler may make to ensure
27087that intermediate results are not out of range. For example:
27088
27089@smallexample @c ada
27090   A : Integer;
27091   ...
27092   A := A + 1;
27093@end smallexample
27094
27095@noindent
27096if @code{A} has the value @code{Integer'Last}, then the addition may cause
27097overflow since the result is out of range of the type @code{Integer}.
27098In this case @code{Constraint_Error} will be raised if checks are
27099enabled.
27100
27101A trickier situation arises in examples like the following:
27102
27103@smallexample @c ada
27104  A, C : Integer;
27105  ...
27106  A := (A + 1) + C;
27107@end smallexample
27108
27109@noindent
27110where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
27111Now the final result of the expression on the right hand side is
27112@code{Integer'Last} which is in range, but the question arises whether the
27113intermediate addition of @code{(A + 1)} raises an overflow error.
27114
27115The (perhaps surprising) answer is that the Ada language
27116definition does not answer this question. Instead it leaves
27117it up to the implementation to do one of two things if overflow
27118checks are enabled.
27119
27120@itemize @bullet
27121@item
27122raise an exception (@code{Constraint_Error}), or
27123
27124@item
27125yield the correct mathematical result which is then used in
27126subsequent operations.
27127@end itemize
27128
27129@noindent
27130If the compiler chooses the first approach, then the assignment of this
27131example will indeed raise @code{Constraint_Error} if overflow checking is
27132enabled, or result in erroneous execution if overflow checks are suppressed.
27133
27134But if the compiler
27135chooses the second approach, then it can perform both additions yielding
27136the correct mathematical result, which is in range, so no exception
27137will be raised, and the right result is obtained, regardless of whether
27138overflow checks are suppressed.
27139
27140Note that in the first example an
27141exception will be raised in either case, since if the compiler
27142gives the correct mathematical result for the addition, it will
27143be out of range of the target type of the assignment, and thus
27144fails the range check.
27145
27146This lack of specified behavior in the handling of overflow for
27147intermediate results is a source of non-portability, and can thus
27148be problematic when programs are ported. Most typically this arises
27149in a situation where the original compiler did not raise an exception,
27150and then the application is moved to a compiler where the check is
27151performed on the intermediate result and an unexpected exception is
27152raised.
27153
27154Furthermore, when using Ada 2012's preconditions and other
27155assertion forms, another issue arises. Consider:
27156
27157@smallexample @c ada
27158     procedure P (A, B : Integer) with
27159       Pre => A + B <= Integer'Last;
27160@end smallexample
27161
27162@noindent
27163One often wants to regard arithmetic in a context like this from
27164a mathematical point of view. So for example, if the two actual parameters
27165for a call to @code{P} are both @code{Integer'Last}, then
27166the precondition should be regarded as False. If we are executing
27167in a mode with run-time checks enabled for preconditions, then we would
27168like this precondition to fail, rather than raising an exception
27169because of the intermediate overflow.
27170
27171However, the language definition leaves the specification of
27172whether the above condition fails (raising @code{Assert_Error}) or
27173causes an intermediate overflow (raising @code{Constraint_Error})
27174up to the implementation.
27175
27176The situation is worse in a case such as the following:
27177
27178@smallexample @c ada
27179     procedure Q (A, B, C : Integer) with
27180       Pre => A + B + C <= Integer'Last;
27181@end smallexample
27182
27183@noindent
27184Consider the call
27185
27186@smallexample @c ada
27187     Q (A => Integer'Last, B => 1, C => -1);
27188@end smallexample
27189
27190@noindent
27191From a mathematical point of view the precondition
27192is True, but at run time we may (but are not guaranteed to) get an
27193exception raised because of the intermediate overflow (and we really
27194would prefer this precondition to be considered True at run time).
27195
27196@node Overflow Checking Modes in GNAT
27197@section Overflow Checking Modes in GNAT
27198
27199@noindent
27200To deal with the portability issue, and with the problem of
27201mathematical versus run-time interpretation of the expressions in
27202assertions, GNAT provides comprehensive control over the handling
27203of intermediate overflow. GNAT can operate in three modes, and
27204furthemore, permits separate selection of operating modes for
27205the expressions within assertions (here the term ``assertions''
27206is used in the technical sense, which includes preconditions and so forth)
27207and for expressions appearing outside assertions.
27208
27209The three modes are:
27210
27211@itemize @bullet
27212@item   @i{Use base type for intermediate operations} (@code{STRICT})
27213
27214     In this mode, all intermediate results for predefined arithmetic
27215     operators are computed using the base type, and the result must
27216     be in range of the base type. If this is not the
27217     case then either an exception is raised (if overflow checks are
27218     enabled) or the execution is erroneous (if overflow checks are suppressed).
27219     This is the normal default mode.
27220
27221@item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
27222
27223     In this mode, the compiler attempts to avoid intermediate overflows by
27224     using a larger integer type, typically @code{Long_Long_Integer},
27225     as the type in which arithmetic is
27226     performed for predefined arithmetic operators. This may be slightly more
27227     expensive at
27228     run time (compared to suppressing intermediate overflow checks), though
27229     the cost is negligible on modern 64-bit machines. For the examples given
27230     earlier, no intermediate overflows would have resulted in exceptions,
27231     since the intermediate results are all in the range of
27232     @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
27233     of GNAT). In addition, if checks are enabled, this reduces the number of
27234     checks that must be made, so this choice may actually result in an
27235     improvement in space and time behavior.
27236
27237     However, there are cases where @code{Long_Long_Integer} is not large
27238     enough, consider the following example:
27239
27240@smallexample @c ada
27241       procedure R (A, B, C, D : Integer) with
27242         Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
27243@end smallexample
27244
27245     where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
27246     Now the intermediate results are
27247     out of the range of @code{Long_Long_Integer} even though the final result
27248     is in range and the precondition is True (from a mathematical point
27249     of view). In such a case, operating in this mode, an overflow occurs
27250     for the intermediate computation (which is why this mode
27251     says @i{most} intermediate overflows are avoided). In this case,
27252     an exception is raised if overflow checks are enabled, and the
27253     execution is erroneous if overflow checks are suppressed.
27254
27255@item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
27256
27257     In this mode, the compiler  avoids all intermediate overflows
27258     by using arbitrary precision arithmetic as required. In this
27259     mode, the above example with @code{A**2 * B**2} would
27260     not cause intermediate overflow, because the intermediate result
27261     would be evaluated using sufficient precision, and the result
27262     of evaluating the precondition would be True.
27263
27264     This mode has the advantage of avoiding any intermediate
27265     overflows, but at the expense of significant run-time overhead,
27266     including the use of a library (included automatically in this
27267     mode) for multiple-precision arithmetic.
27268
27269     This mode provides cleaner semantics for assertions, since now
27270     the run-time behavior emulates true arithmetic behavior for the
27271     predefined arithmetic operators, meaning that there is never a
27272     conflict between the mathematical view of the assertion, and its
27273     run-time behavior.
27274
27275     Note that in this mode, the behavior is unaffected by whether or
27276     not overflow checks are suppressed, since overflow does not occur.
27277     It is possible for gigantic intermediate expressions to raise
27278     @code{Storage_Error} as a result of attempting to compute the
27279     results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
27280     but overflow is impossible.
27281
27282
27283@end itemize
27284
27285@noindent
27286  Note that these modes apply only to the evaluation of predefined
27287  arithmetic, membership, and comparison operators for signed integer
27288  aritmetic.
27289
27290  For fixed-point arithmetic, checks can be suppressed. But if checks
27291  are enabled
27292  then fixed-point values are always checked for overflow against the
27293  base type for intermediate expressions (that is such checks always
27294  operate in the equivalent of @code{STRICT} mode).
27295
27296  For floating-point, on nearly all architectures, @code{Machine_Overflows}
27297  is False, and IEEE infinities are generated, so overflow exceptions
27298  are never raised. If you want to avoid infinities, and check that
27299  final results of expressions are in range, then you can declare a
27300  constrained floating-point type, and range checks will be carried
27301  out in the normal manner (with infinite values always failing all
27302  range checks).
27303
27304
27305@c -------------------------
27306@node Specifying the Desired Mode
27307@section Specifying the Desired Mode
27308
27309@noindent
27310The desired mode of for handling intermediate overflow can be specified using
27311either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
27312The pragma has the form
27313@cindex pragma @code{Overflow_Mode}
27314
27315@smallexample @c ada
27316    pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
27317@end smallexample
27318
27319@noindent
27320where @code{MODE} is one of
27321
27322@itemize @bullet
27323@item   @code{STRICT}:  intermediate overflows checked (using base type)
27324@item   @code{MINIMIZED}: minimize intermediate overflows
27325@item   @code{ELIMINATED}: eliminate intermediate overflows
27326@end itemize
27327
27328@noindent
27329The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
27330@code{minimized} all have the same effect.
27331
27332If only the @code{General} parameter is present, then the given @code{MODE}
27333applies
27334to expressions both within and outside assertions. If both arguments
27335are present, then @code{General} applies to expressions outside assertions,
27336and @code{Assertions} applies to expressions within assertions. For example:
27337
27338@smallexample @c ada
27339   pragma Overflow_Mode
27340     (General => Minimized, Assertions => Eliminated);
27341@end smallexample
27342
27343@noindent
27344specifies that general expressions outside assertions be evaluated
27345in ``minimize intermediate overflows'' mode, and expressions within
27346assertions be evaluated in ``eliminate intermediate overflows'' mode.
27347This is often a reasonable choice, avoiding excessive overhead
27348outside assertions, but assuring a high degree of portability
27349when importing code from another compiler, while incurring
27350the extra overhead for assertion expressions to ensure that
27351the behavior at run time matches the expected mathematical
27352behavior.
27353
27354The @code{Overflow_Mode} pragma has the same scoping and placement
27355rules as pragma @code{Suppress}, so it can occur either as a
27356configuration pragma, specifying a default for the whole
27357program, or in a declarative scope, where it applies to the
27358remaining declarations and statements in that scope.
27359
27360Note that pragma @code{Overflow_Mode} does not affect whether
27361overflow checks are enabled or suppressed. It only controls the
27362method used to compute intermediate values. To control whether
27363overflow checking is enabled or suppressed, use pragma @code{Suppress}
27364or @code{Unsuppress} in the usual manner
27365
27366Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
27367can be used to control the checking mode default (which can be subsequently
27368overridden using pragmas).
27369@cindex @option{-gnato?} (gcc)
27370@cindex @option{-gnato??} (gcc)
27371
27372Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
27373
27374@itemize @bullet
27375@item   @code{1}:
27376use base type for intermediate operations (@code{STRICT})
27377@item   @code{2}:
27378minimize intermediate overflows (@code{MINIMIZED})
27379@item   @code{3}:
27380eliminate intermediate overflows (@code{ELIMINATED})
27381@end itemize
27382
27383@noindent
27384As with the pragma, if only one digit appears then it applies to all
27385cases; if two digits are given, then the first applies outside
27386assertions, and the second within assertions. Thus the equivalent
27387of the example pragma above would be
27388@option{^-gnato23^/OVERFLOW_CHECKS=23^}.
27389
27390If no digits follow the @option{-gnato}, then it is equivalent to
27391@option{^-gnato11^/OVERFLOW_CHECKS=11^},
27392causing all intermediate operations to be computed using the base
27393type (@code{STRICT} mode).
27394
27395In addition to setting the mode used for computation of intermediate
27396results, the @code{-gnato} switch also enables overflow checking (which
27397is suppressed by default). It thus combines the effect of using
27398a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
27399
27400
27401@c -------------------------
27402@node Default Settings
27403@section Default Settings
27404
27405The default mode for overflow checks is
27406
27407@smallexample
27408   General => Strict
27409@end smallexample
27410
27411@noindent
27412which causes all computations both inside and outside assertions to use
27413the base type. In addition overflow checks are suppressed.
27414
27415This retains compatibility with previous versions of
27416GNAT which suppressed overflow checks by default and always
27417used the base type for computation of intermediate results.
27418
27419The switch @option{-gnato} (with no digits following) is equivalent to
27420@cindex @option{-gnato} (gcc)
27421
27422@smallexample
27423   General => Strict
27424@end smallexample
27425
27426@noindent
27427which causes overflow checking of all intermediate overflows
27428both inside and outside assertions against the base type.
27429This provides compatibility
27430with this switch as implemented in previous versions of GNAT.
27431
27432The pragma @code{Suppress (Overflow_Check)} disables overflow
27433checking, but it has no effect on the method used for computing
27434intermediate results.
27435
27436The pragma @code{Unsuppress (Overflow_Check)} enables overflow
27437checking, but it has no effect on the method used for computing
27438intermediate results.
27439
27440@c -------------------------
27441@node Implementation Notes
27442@section Implementation Notes
27443
27444In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
27445reasonably efficient, and can be generally used. It also helps
27446to ensure compatibility with code imported from some other
27447compiler to GNAT.
27448
27449Setting all intermediate overflows checking (@code{CHECKED} mode)
27450makes sense if you want to
27451make sure that your code is compatible with any other possible
27452Ada implementation. This may be useful in ensuring portability
27453for code that is to be exported to some other compiler than GNAT.
27454
27455
27456The Ada standard allows the reassociation of expressions at
27457the same precedence level if no parentheses are present. For
27458example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
27459the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
27460introducing or eliminating an overflow exception. The GNAT
27461compiler never takes advantage of this freedom, and the
27462expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
27463If you need the other order, you can write the parentheses
27464explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
27465
27466The use of @code{ELIMINATED} mode will cause the compiler to
27467automatically include an appropriate arbitrary precision
27468integer arithmetic package. The compiler will make calls
27469to this package, though only in cases where it cannot be
27470sure that @code{Long_Long_Integer} is sufficient to guard against
27471intermediate overflows. This package does not use dynamic
27472alllocation, but it does use the secondary stack, so an
27473appropriate secondary stack package must be present (this
27474is always true for standard full Ada, but may require
27475specific steps for restricted run times such as ZFP).
27476
27477Although @code{ELIMINATED} mode causes expressions to use arbitrary
27478precision arithmetic, avoiding overflow, the final result
27479must be in an appropriate range. This is true even if the
27480final result is of type @code{[Long_[Long_]]Integer'Base}, which
27481still has the same bounds as its associated constrained
27482type at run-time.
27483
27484Currently, the @code{ELIMINATED} mode is only available on target
27485platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27486platforms).
27487
27488@c *******************************
27489@node Conditional Compilation
27490@appendix Conditional Compilation
27491@c *******************************
27492@cindex Conditional compilation
27493
27494@noindent
27495It is often necessary to arrange for a single source program
27496to serve multiple purposes, where it is compiled in different
27497ways to achieve these different goals. Some examples of the
27498need for this feature are
27499
27500@itemize @bullet
27501@item  Adapting a program to a different hardware environment
27502@item  Adapting a program to a different target architecture
27503@item  Turning debugging features on and off
27504@item  Arranging for a program to compile with different compilers
27505@end itemize
27506
27507@noindent
27508In C, or C++, the typical approach would be to use the preprocessor
27509that is defined as part of the language. The Ada language does not
27510contain such a feature. This is not an oversight, but rather a very
27511deliberate design decision, based on the experience that overuse of
27512the preprocessing features in C and C++ can result in programs that
27513are extremely difficult to maintain. For example, if we have ten
27514switches that can be on or off, this means that there are a thousand
27515separate programs, any one of which might not even be syntactically
27516correct, and even if syntactically correct, the resulting program
27517might not work correctly. Testing all combinations can quickly become
27518impossible.
27519
27520Nevertheless, the need to tailor programs certainly exists, and in
27521this Appendix we will discuss how this can
27522be achieved using Ada in general, and GNAT in particular.
27523
27524@menu
27525* Use of Boolean Constants::
27526* Debugging - A Special Case::
27527* Conditionalizing Declarations::
27528* Use of Alternative Implementations::
27529* Preprocessing::
27530@end menu
27531
27532@node Use of Boolean Constants
27533@section Use of Boolean Constants
27534
27535@noindent
27536In the case where the difference is simply which code
27537sequence is executed, the cleanest solution is to use Boolean
27538constants to control which code is executed.
27539
27540@smallexample @c ada
27541@group
27542FP_Initialize_Required : constant Boolean := True;
27543@dots{}
27544if FP_Initialize_Required then
27545@dots{}
27546end if;
27547@end group
27548@end smallexample
27549
27550@noindent
27551Not only will the code inside the @code{if} statement not be executed if
27552the constant Boolean is @code{False}, but it will also be completely
27553deleted from the program.
27554However, the code is only deleted after the @code{if} statement
27555has been checked for syntactic and semantic correctness.
27556(In contrast, with preprocessors the code is deleted before the
27557compiler ever gets to see it, so it is not checked until the switch
27558is turned on.)
27559@cindex Preprocessors (contrasted with conditional compilation)
27560
27561Typically the Boolean constants will be in a separate package,
27562something like:
27563
27564@smallexample @c ada
27565@group
27566package Config is
27567   FP_Initialize_Required : constant Boolean := True;
27568   Reset_Available        : constant Boolean := False;
27569   @dots{}
27570end Config;
27571@end group
27572@end smallexample
27573
27574@noindent
27575The @code{Config} package exists in multiple forms for the various targets,
27576with an appropriate script selecting the version of @code{Config} needed.
27577Then any other unit requiring conditional compilation can do a @code{with}
27578of @code{Config} to make the constants visible.
27579
27580
27581@node Debugging - A Special Case
27582@section Debugging - A Special Case
27583
27584@noindent
27585A common use of conditional code is to execute statements (for example
27586dynamic checks, or output of intermediate results) under control of a
27587debug switch, so that the debugging behavior can be turned on and off.
27588This can be done using a Boolean constant to control whether the code
27589is active:
27590
27591@smallexample @c ada
27592@group
27593if Debugging then
27594   Put_Line ("got to the first stage!");
27595end if;
27596@end group
27597@end smallexample
27598
27599@noindent
27600or
27601
27602@smallexample @c ada
27603@group
27604if Debugging and then Temperature > 999.0 then
27605   raise Temperature_Crazy;
27606end if;
27607@end group
27608@end smallexample
27609
27610@noindent
27611Since this is a common case, there are special features to deal with
27612this in a convenient manner. For the case of tests, Ada 2005 has added
27613a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27614@cindex pragma @code{Assert}
27615on the @code{Assert} pragma that has always been available in GNAT, so this
27616feature may be used with GNAT even if you are not using Ada 2005 features.
27617The use of pragma @code{Assert} is described in
27618@ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27619example, the last test could be written:
27620
27621@smallexample @c ada
27622pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27623@end smallexample
27624
27625@noindent
27626or simply
27627
27628@smallexample @c ada
27629pragma Assert (Temperature <= 999.0);
27630@end smallexample
27631
27632@noindent
27633In both cases, if assertions are active and the temperature is excessive,
27634the exception @code{Assert_Failure} will be raised, with the given string in
27635the first case or a string indicating the location of the pragma in the second
27636case used as the exception message.
27637
27638You can turn assertions on and off by using the @code{Assertion_Policy}
27639pragma.
27640@cindex pragma @code{Assertion_Policy}
27641This is an Ada 2005 pragma which is implemented in all modes by
27642GNAT, but only in the latest versions of GNAT which include Ada 2005
27643capability. Alternatively, you can use the @option{-gnata} switch
27644@cindex @option{-gnata} switch
27645to enable assertions from the command line (this is recognized by all versions
27646of GNAT).
27647
27648For the example above with the @code{Put_Line}, the GNAT-specific pragma
27649@code{Debug} can be used:
27650@cindex pragma @code{Debug}
27651
27652@smallexample @c ada
27653pragma Debug (Put_Line ("got to the first stage!"));
27654@end smallexample
27655
27656@noindent
27657If debug pragmas are enabled, the argument, which must be of the form of
27658a procedure call, is executed (in this case, @code{Put_Line} will be called).
27659Only one call can be present, but of course a special debugging procedure
27660containing any code you like can be included in the program and then
27661called in a pragma @code{Debug} argument as needed.
27662
27663One advantage of pragma @code{Debug} over the @code{if Debugging then}
27664construct is that pragma @code{Debug} can appear in declarative contexts,
27665such as at the very beginning of a procedure, before local declarations have
27666been elaborated.
27667
27668Debug pragmas are enabled using either the @option{-gnata} switch that also
27669controls assertions, or with a separate Debug_Policy pragma.
27670@cindex pragma @code{Debug_Policy}
27671The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27672in Ada 95 and Ada 83 programs as well), and is analogous to
27673pragma @code{Assertion_Policy} to control assertions.
27674
27675@code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27676and thus they can appear in @file{gnat.adc} if you are not using a
27677project file, or in the file designated to contain configuration pragmas
27678in a project file.
27679They then apply to all subsequent compilations. In practice the use of
27680the @option{-gnata} switch is often the most convenient method of controlling
27681the status of these pragmas.
27682
27683Note that a pragma is not a statement, so in contexts where a statement
27684sequence is required, you can't just write a pragma on its own. You have
27685to add a @code{null} statement.
27686
27687@smallexample @c ada
27688@group
27689if @dots{} then
27690   @dots{} -- some statements
27691else
27692   pragma Assert (Num_Cases < 10);
27693   null;
27694end if;
27695@end group
27696@end smallexample
27697
27698
27699@node Conditionalizing Declarations
27700@section Conditionalizing Declarations
27701
27702@noindent
27703In some cases, it may be necessary to conditionalize declarations to meet
27704different requirements. For example we might want a bit string whose length
27705is set to meet some hardware message requirement.
27706
27707In some cases, it may be possible to do this using declare blocks controlled
27708by conditional constants:
27709
27710@smallexample @c ada
27711@group
27712if Small_Machine then
27713   declare
27714      X : Bit_String (1 .. 10);
27715   begin
27716      @dots{}
27717   end;
27718else
27719   declare
27720      X : Large_Bit_String (1 .. 1000);
27721   begin
27722      @dots{}
27723   end;
27724end if;
27725@end group
27726@end smallexample
27727
27728@noindent
27729Note that in this approach, both declarations are analyzed by the
27730compiler so this can only be used where both declarations are legal,
27731even though one of them will not be used.
27732
27733Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27734or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27735that are parameterized by these constants. For example
27736
27737@smallexample @c ada
27738@group
27739for Rec use
27740  Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27741end record;
27742@end group
27743@end smallexample
27744
27745@noindent
27746If @code{Bits_Per_Word} is set to 32, this generates either
27747
27748@smallexample @c ada
27749@group
27750for Rec use
27751  Field1 at 0 range 0 .. 32;
27752end record;
27753@end group
27754@end smallexample
27755
27756@noindent
27757for the big endian case, or
27758
27759@smallexample @c ada
27760@group
27761for Rec use record
27762  Field1 at 0 range 10 .. 32;
27763end record;
27764@end group
27765@end smallexample
27766
27767@noindent
27768for the little endian case. Since a powerful subset of Ada expression
27769notation is usable for creating static constants, clever use of this
27770feature can often solve quite difficult problems in conditionalizing
27771compilation (note incidentally that in Ada 95, the little endian
27772constant was introduced as @code{System.Default_Bit_Order}, so you do not
27773need to define this one yourself).
27774
27775
27776@node Use of Alternative Implementations
27777@section Use of Alternative Implementations
27778
27779@noindent
27780In some cases, none of the approaches described above are adequate. This
27781can occur for example if the set of declarations required is radically
27782different for two different configurations.
27783
27784In this situation, the official Ada way of dealing with conditionalizing
27785such code is to write separate units for the different cases. As long as
27786this does not result in excessive duplication of code, this can be done
27787without creating maintenance problems. The approach is to share common
27788code as far as possible, and then isolate the code and declarations
27789that are different. Subunits are often a convenient method for breaking
27790out a piece of a unit that is to be conditionalized, with separate files
27791for different versions of the subunit for different targets, where the
27792build script selects the right one to give to the compiler.
27793@cindex Subunits (and conditional compilation)
27794
27795As an example, consider a situation where a new feature in Ada 2005
27796allows something to be done in a really nice way. But your code must be able
27797to compile with an Ada 95 compiler. Conceptually you want to say:
27798
27799@smallexample @c ada
27800@group
27801if Ada_2005 then
27802   @dots{} neat Ada 2005 code
27803else
27804   @dots{} not quite as neat Ada 95 code
27805end if;
27806@end group
27807@end smallexample
27808
27809@noindent
27810where @code{Ada_2005} is a Boolean constant.
27811
27812But this won't work when @code{Ada_2005} is set to @code{False},
27813since the @code{then} clause will be illegal for an Ada 95 compiler.
27814(Recall that although such unreachable code would eventually be deleted
27815by the compiler, it still needs to be legal.  If it uses features
27816introduced in Ada 2005, it will be illegal in Ada 95.)
27817
27818So instead we write
27819
27820@smallexample @c ada
27821procedure Insert is separate;
27822@end smallexample
27823
27824@noindent
27825Then we have two files for the subunit @code{Insert}, with the two sets of
27826code.
27827If the package containing this is called @code{File_Queries}, then we might
27828have two files
27829
27830@itemize @bullet
27831@item    @file{file_queries-insert-2005.adb}
27832@item    @file{file_queries-insert-95.adb}
27833@end itemize
27834
27835@noindent
27836and the build script renames the appropriate file to
27837
27838@smallexample
27839file_queries-insert.adb
27840@end smallexample
27841
27842@noindent
27843and then carries out the compilation.
27844
27845This can also be done with project files' naming schemes. For example:
27846
27847@smallexample @c project
27848For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27849@end smallexample
27850
27851@noindent
27852Note also that with project files it is desirable to use a different extension
27853than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27854conflict may arise through another commonly used feature: to declare as part
27855of the project a set of directories containing all the sources obeying the
27856default naming scheme.
27857
27858The use of alternative units is certainly feasible in all situations,
27859and for example the Ada part of the GNAT run-time is conditionalized
27860based on the target architecture using this approach. As a specific example,
27861consider the implementation of the AST feature in VMS. There is one
27862spec:
27863
27864@smallexample
27865s-asthan.ads
27866@end smallexample
27867
27868@noindent
27869which is the same for all architectures, and three bodies:
27870
27871@table @file
27872@item    s-asthan.adb
27873used for all non-VMS operating systems
27874@item    s-asthan-vms-alpha.adb
27875used for VMS on the Alpha
27876@item    s-asthan-vms-ia64.adb
27877used for VMS on the ia64
27878@end table
27879
27880@noindent
27881The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27882this operating system feature is not available, and the two remaining
27883versions interface with the corresponding versions of VMS to provide
27884VMS-compatible AST handling. The GNAT build script knows the architecture
27885and operating system, and automatically selects the right version,
27886renaming it if necessary to @file{s-asthan.adb} before the run-time build.
27887
27888Another style for arranging alternative implementations is through Ada's
27889access-to-subprogram facility.
27890In case some functionality is to be conditionally included,
27891you can declare an access-to-procedure variable @code{Ref} that is initialized
27892to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
27893when appropriate.
27894In some library package, set @code{Ref} to @code{Proc'Access} for some
27895procedure @code{Proc} that performs the relevant processing.
27896The initialization only occurs if the library package is included in the
27897program.
27898The same idea can also be implemented using tagged types and dispatching
27899calls.
27900
27901
27902@node Preprocessing
27903@section Preprocessing
27904@cindex Preprocessing
27905
27906@noindent
27907Although it is quite possible to conditionalize code without the use of
27908C-style preprocessing, as described earlier in this section, it is
27909nevertheless convenient in some cases to use the C approach. Moreover,
27910older Ada compilers have often provided some preprocessing capability,
27911so legacy code may depend on this approach, even though it is not
27912standard.
27913
27914To accommodate such use, GNAT provides a preprocessor (modeled to a large
27915extent on the various preprocessors that have been used
27916with legacy code on other compilers, to enable easier transition).
27917
27918The preprocessor may be used in two separate modes. It can be used quite
27919separately from the compiler, to generate a separate output source file
27920that is then fed to the compiler as a separate step. This is the
27921@code{gnatprep} utility, whose use is fully described in
27922@ref{Preprocessing with gnatprep}.
27923@cindex @code{gnatprep}
27924
27925The preprocessing language allows such constructs as
27926
27927@smallexample
27928@group
27929#if DEBUG or else (PRIORITY > 4) then
27930   bunch of declarations
27931#else
27932   completely different bunch of declarations
27933#end if;
27934@end group
27935@end smallexample
27936
27937@noindent
27938The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
27939defined either on the command line or in a separate file.
27940
27941The other way of running the preprocessor is even closer to the C style and
27942often more convenient. In this approach the preprocessing is integrated into
27943the compilation process. The compiler is fed the preprocessor input which
27944includes @code{#if} lines etc, and then the compiler carries out the
27945preprocessing internally and processes the resulting output.
27946For more details on this approach, see @ref{Integrated Preprocessing}.
27947
27948
27949@c *******************************
27950@node Inline Assembler
27951@appendix Inline Assembler
27952@c *******************************
27953
27954@noindent
27955If you need to write low-level software that interacts directly
27956with the hardware, Ada provides two ways to incorporate assembly
27957language code into your program.  First, you can import and invoke
27958external routines written in assembly language, an Ada feature fully
27959supported by GNAT@.  However, for small sections of code it may be simpler
27960or more efficient to include assembly language statements directly
27961in your Ada source program, using the facilities of the implementation-defined
27962package @code{System.Machine_Code}, which incorporates the gcc
27963Inline Assembler.  The Inline Assembler approach offers a number of advantages,
27964including the following:
27965
27966@itemize @bullet
27967@item No need to use non-Ada tools
27968@item Consistent interface over different targets
27969@item Automatic usage of the proper calling conventions
27970@item Access to Ada constants and variables
27971@item Definition of intrinsic routines
27972@item Possibility of inlining a subprogram comprising assembler code
27973@item Code optimizer can take Inline Assembler code into account
27974@end itemize
27975
27976This chapter presents a series of examples to show you how to use
27977the Inline Assembler.  Although it focuses on the Intel x86,
27978the general approach applies also to other processors.
27979It is assumed that you are familiar with Ada
27980and with assembly language programming.
27981
27982@menu
27983* Basic Assembler Syntax::
27984* A Simple Example of Inline Assembler::
27985* Output Variables in Inline Assembler::
27986* Input Variables in Inline Assembler::
27987* Inlining Inline Assembler Code::
27988* Other Asm Functionality::
27989@end menu
27990
27991@c ---------------------------------------------------------------------------
27992@node Basic Assembler Syntax
27993@section Basic Assembler Syntax
27994
27995@noindent
27996The assembler used by GNAT and gcc is based not on the Intel assembly
27997language, but rather on a language that descends from the AT&T Unix
27998assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
27999The following table summarizes the main features of @emph{as} syntax
28000and points out the differences from the Intel conventions.
28001See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28002pre-processor) documentation for further information.
28003
28004@table @asis
28005@item Register names
28006gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28007@*
28008Intel: No extra punctuation; for example @code{eax}
28009
28010@item Immediate operand
28011gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28012@*
28013Intel: No extra punctuation; for example @code{4}
28014
28015@item Address
28016gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28017@*
28018Intel: No extra punctuation; for example @code{loc}
28019
28020@item Memory contents
28021gcc / @emph{as}: No extra punctuation; for example @code{loc}
28022@*
28023Intel: Square brackets; for example @code{[loc]}
28024
28025@item Register contents
28026gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28027@*
28028Intel: Square brackets; for example @code{[eax]}
28029
28030@item Hexadecimal numbers
28031gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28032@*
28033Intel: Trailing ``h''; for example @code{A0h}
28034
28035@item Operand size
28036gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28037a 16-bit word
28038@*
28039Intel: Implicit, deduced by assembler; for example @code{mov}
28040
28041@item Instruction repetition
28042gcc / @emph{as}: Split into two lines; for example
28043@*
28044@code{rep}
28045@*
28046@code{stosl}
28047@*
28048Intel: Keep on one line; for example @code{rep stosl}
28049
28050@item Order of operands
28051gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28052@*
28053Intel: Destination first; for example @code{mov eax, 4}
28054@end table
28055
28056@c ---------------------------------------------------------------------------
28057@node A Simple Example of Inline Assembler
28058@section A Simple Example of Inline Assembler
28059
28060@noindent
28061The following example will generate a single assembly language statement,
28062@code{nop}, which does nothing.  Despite its lack of run-time effect,
28063the example will be useful in illustrating the basics of
28064the Inline Assembler facility.
28065
28066@smallexample @c ada
28067@group
28068with System.Machine_Code; use System.Machine_Code;
28069procedure Nothing is
28070begin
28071   Asm ("nop");
28072end Nothing;
28073@end group
28074@end smallexample
28075
28076@code{Asm} is a procedure declared in package @code{System.Machine_Code};
28077here it takes one parameter, a @emph{template string} that must be a static
28078expression and that will form the generated instruction.
28079@code{Asm} may be regarded as a compile-time procedure that parses
28080the template string and additional parameters (none here),
28081from which it generates a sequence of assembly language instructions.
28082
28083The examples in this chapter will illustrate several of the forms
28084for invoking @code{Asm}; a complete specification of the syntax
28085is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
28086Manual}.
28087
28088Under the standard GNAT conventions, the @code{Nothing} procedure
28089should be in a file named @file{nothing.adb}.
28090You can build the executable in the usual way:
28091@smallexample
28092gnatmake nothing
28093@end smallexample
28094However, the interesting aspect of this example is not its run-time behavior
28095but rather the generated assembly code.
28096To see this output, invoke the compiler as follows:
28097@smallexample
28098   gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28099@end smallexample
28100where the options are:
28101
28102@table @code
28103@item -c
28104compile only (no bind or link)
28105@item -S
28106generate assembler listing
28107@item -fomit-frame-pointer
28108do not set up separate stack frames
28109@item -gnatp
28110do not add runtime checks
28111@end table
28112
28113This gives a human-readable assembler version of the code. The resulting
28114file will have the same name as the Ada source file, but with a @code{.s}
28115extension. In our example, the file @file{nothing.s} has the following
28116contents:
28117
28118@smallexample
28119@group
28120.file "nothing.adb"
28121gcc2_compiled.:
28122___gnu_compiled_ada:
28123.text
28124   .align 4
28125.globl __ada_nothing
28126__ada_nothing:
28127#APP
28128   nop
28129#NO_APP
28130   jmp L1
28131   .align 2,0x90
28132L1:
28133   ret
28134@end group
28135@end smallexample
28136
28137The assembly code you included is clearly indicated by
28138the compiler, between the @code{#APP} and @code{#NO_APP}
28139delimiters. The character before the 'APP' and 'NOAPP'
28140can differ on different targets. For example, GNU/Linux uses '#APP' while
28141on NT you will see '/APP'.
28142
28143If you make a mistake in your assembler code (such as using the
28144wrong size modifier, or using a wrong operand for the instruction) GNAT
28145will report this error in a temporary file, which will be deleted when
28146the compilation is finished.  Generating an assembler file will help
28147in such cases, since you can assemble this file separately using the
28148@emph{as} assembler that comes with gcc.
28149
28150Assembling the file using the command
28151
28152@smallexample
28153as @file{nothing.s}
28154@end smallexample
28155@noindent
28156will give you error messages whose lines correspond to the assembler
28157input file, so you can easily find and correct any mistakes you made.
28158If there are no errors, @emph{as} will generate an object file
28159@file{nothing.out}.
28160
28161@c ---------------------------------------------------------------------------
28162@node Output Variables in Inline Assembler
28163@section Output Variables in Inline Assembler
28164
28165@noindent
28166The examples in this section, showing how to access the processor flags,
28167illustrate how to specify the destination operands for assembly language
28168statements.
28169
28170@smallexample @c ada
28171@group
28172with Interfaces; use Interfaces;
28173with Ada.Text_IO; use Ada.Text_IO;
28174with System.Machine_Code; use System.Machine_Code;
28175procedure Get_Flags is
28176   Flags : Unsigned_32;
28177   use ASCII;
28178begin
28179   Asm ("pushfl"          & LF & HT & -- push flags on stack
28180        "popl %%eax"      & LF & HT & -- load eax with flags
28181        "movl %%eax, %0",             -- store flags in variable
28182        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28183   Put_Line ("Flags register:" & Flags'Img);
28184end Get_Flags;
28185@end group
28186@end smallexample
28187
28188In order to have a nicely aligned assembly listing, we have separated
28189multiple assembler statements in the Asm template string with linefeed
28190(ASCII.LF) and horizontal tab (ASCII.HT) characters.
28191The resulting section of the assembly output file is:
28192
28193@smallexample
28194@group
28195#APP
28196   pushfl
28197   popl %eax
28198   movl %eax, -40(%ebp)
28199#NO_APP
28200@end group
28201@end smallexample
28202
28203It would have been legal to write the Asm invocation as:
28204
28205@smallexample
28206Asm ("pushfl popl %%eax movl %%eax, %0")
28207@end smallexample
28208
28209but in the generated assembler file, this would come out as:
28210
28211@smallexample
28212#APP
28213   pushfl popl %eax movl %eax, -40(%ebp)
28214#NO_APP
28215@end smallexample
28216
28217which is not so convenient for the human reader.
28218
28219We use Ada comments
28220at the end of each line to explain what the assembler instructions
28221actually do.  This is a useful convention.
28222
28223When writing Inline Assembler instructions, you need to precede each register
28224and variable name with a percent sign.  Since the assembler already requires
28225a percent sign at the beginning of a register name, you need two consecutive
28226percent signs for such names in the Asm template string, thus @code{%%eax}.
28227In the generated assembly code, one of the percent signs will be stripped off.
28228
28229Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28230variables: operands you later define using @code{Input} or @code{Output}
28231parameters to @code{Asm}.
28232An output variable is illustrated in
28233the third statement in the Asm template string:
28234@smallexample
28235movl %%eax, %0
28236@end smallexample
28237The intent is to store the contents of the eax register in a variable that can
28238be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28239necessarily work, since the compiler might optimize by using a register
28240to hold Flags, and the expansion of the @code{movl} instruction would not be
28241aware of this optimization.  The solution is not to store the result directly
28242but rather to advise the compiler to choose the correct operand form;
28243that is the purpose of the @code{%0} output variable.
28244
28245Information about the output variable is supplied in the @code{Outputs}
28246parameter to @code{Asm}:
28247@smallexample
28248Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28249@end smallexample
28250
28251The output is defined by the @code{Asm_Output} attribute of the target type;
28252the general format is
28253@smallexample
28254Type'Asm_Output (constraint_string, variable_name)
28255@end smallexample
28256
28257The constraint string directs the compiler how
28258to store/access the associated variable.  In the example
28259@smallexample
28260Unsigned_32'Asm_Output ("=m", Flags);
28261@end smallexample
28262the @code{"m"} (memory) constraint tells the compiler that the variable
28263@code{Flags} should be stored in a memory variable, thus preventing
28264the optimizer from keeping it in a register.  In contrast,
28265@smallexample
28266Unsigned_32'Asm_Output ("=r", Flags);
28267@end smallexample
28268uses the @code{"r"} (register) constraint, telling the compiler to
28269store the variable in a register.
28270
28271If the constraint is preceded by the equal character (@strong{=}), it tells
28272the compiler that the variable will be used to store data into it.
28273
28274In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28275allowing the optimizer to choose whatever it deems best.
28276
28277There are a fairly large number of constraints, but the ones that are
28278most useful (for the Intel x86 processor) are the following:
28279
28280@table @code
28281@item =
28282output constraint
28283@item g
28284global (i.e.@: can be stored anywhere)
28285@item m
28286in memory
28287@item I
28288a constant
28289@item a
28290use eax
28291@item b
28292use ebx
28293@item c
28294use ecx
28295@item d
28296use edx
28297@item S
28298use esi
28299@item D
28300use edi
28301@item r
28302use one of eax, ebx, ecx or edx
28303@item q
28304use one of eax, ebx, ecx, edx, esi or edi
28305@end table
28306
28307The full set of constraints is described in the gcc and @emph{as}
28308documentation; note that it is possible to combine certain constraints
28309in one constraint string.
28310
28311You specify the association of an output variable with an assembler operand
28312through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28313integer.  Thus in
28314@smallexample @c ada
28315@group
28316Asm ("pushfl"          & LF & HT & -- push flags on stack
28317     "popl %%eax"      & LF & HT & -- load eax with flags
28318     "movl %%eax, %0",             -- store flags in variable
28319     Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28320@end group
28321@end smallexample
28322@noindent
28323@code{%0} will be replaced in the expanded code by the appropriate operand,
28324whatever
28325the compiler decided for the @code{Flags} variable.
28326
28327In general, you may have any number of output variables:
28328@itemize @bullet
28329@item
28330Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28331@item
28332Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28333of @code{Asm_Output} attributes
28334@end itemize
28335
28336For example:
28337@smallexample @c ada
28338@group
28339Asm ("movl %%eax, %0" & LF & HT &
28340     "movl %%ebx, %1" & LF & HT &
28341     "movl %%ecx, %2",
28342     Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28343                 Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28344                 Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28345@end group
28346@end smallexample
28347@noindent
28348where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28349in the Ada program.
28350
28351As a variation on the @code{Get_Flags} example, we can use the constraints
28352string to direct the compiler to store the eax register into the @code{Flags}
28353variable, instead of including the store instruction explicitly in the
28354@code{Asm} template string:
28355
28356@smallexample @c ada
28357@group
28358with Interfaces; use Interfaces;
28359with Ada.Text_IO; use Ada.Text_IO;
28360with System.Machine_Code; use System.Machine_Code;
28361procedure Get_Flags_2 is
28362   Flags : Unsigned_32;
28363   use ASCII;
28364begin
28365   Asm ("pushfl"      & LF & HT & -- push flags on stack
28366        "popl %%eax",             -- save flags in eax
28367        Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28368   Put_Line ("Flags register:" & Flags'Img);
28369end Get_Flags_2;
28370@end group
28371@end smallexample
28372
28373@noindent
28374The @code{"a"} constraint tells the compiler that the @code{Flags}
28375variable will come from the eax register. Here is the resulting code:
28376
28377@smallexample
28378@group
28379#APP
28380   pushfl
28381   popl %eax
28382#NO_APP
28383   movl %eax,-40(%ebp)
28384@end group
28385@end smallexample
28386
28387@noindent
28388The compiler generated the store of eax into Flags after
28389expanding the assembler code.
28390
28391Actually, there was no need to pop the flags into the eax register;
28392more simply, we could just pop the flags directly into the program variable:
28393
28394@smallexample @c ada
28395@group
28396with Interfaces; use Interfaces;
28397with Ada.Text_IO; use Ada.Text_IO;
28398with System.Machine_Code; use System.Machine_Code;
28399procedure Get_Flags_3 is
28400   Flags : Unsigned_32;
28401   use ASCII;
28402begin
28403   Asm ("pushfl"  & LF & HT & -- push flags on stack
28404        "pop %0",             -- save flags in Flags
28405        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28406   Put_Line ("Flags register:" & Flags'Img);
28407end Get_Flags_3;
28408@end group
28409@end smallexample
28410
28411@c ---------------------------------------------------------------------------
28412@node Input Variables in Inline Assembler
28413@section Input Variables in Inline Assembler
28414
28415@noindent
28416The example in this section illustrates how to specify the source operands
28417for assembly language statements.
28418The program simply increments its input value by 1:
28419
28420@smallexample @c ada
28421@group
28422with Interfaces; use Interfaces;
28423with Ada.Text_IO; use Ada.Text_IO;
28424with System.Machine_Code; use System.Machine_Code;
28425procedure Increment is
28426
28427   function Incr (Value : Unsigned_32) return Unsigned_32 is
28428      Result : Unsigned_32;
28429   begin
28430      Asm ("incl %0",
28431           Outputs => Unsigned_32'Asm_Output ("=a", Result),
28432           Inputs  => Unsigned_32'Asm_Input ("a", Value));
28433      return Result;
28434   end Incr;
28435
28436   Value : Unsigned_32;
28437
28438begin
28439   Value := 5;
28440   Put_Line ("Value before is" & Value'Img);
28441   Value := Incr (Value);
28442   Put_Line ("Value after is" & Value'Img);
28443end Increment;
28444@end group
28445@end smallexample
28446
28447The @code{Outputs} parameter to @code{Asm} specifies
28448that the result will be in the eax register and that it is to be stored
28449in the @code{Result} variable.
28450
28451The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28452but with an @code{Asm_Input} attribute.
28453The @code{"="} constraint, indicating an output value, is not present.
28454
28455You can have multiple input variables, in the same way that you can have more
28456than one output variable.
28457
28458The parameter count (%0, %1) etc, still starts at the first output statement,
28459and continues with the input statements.
28460
28461Just as the @code{Outputs} parameter causes the register to be stored into the
28462target variable after execution of the assembler statements, so does the
28463@code{Inputs} parameter cause its variable to be loaded into the register
28464before execution of the assembler statements.
28465
28466Thus the effect of the @code{Asm} invocation is:
28467@enumerate
28468@item load the 32-bit value of @code{Value} into eax
28469@item execute the @code{incl %eax} instruction
28470@item store the contents of eax into the @code{Result} variable
28471@end enumerate
28472
28473The resulting assembler file (with @option{-O2} optimization) contains:
28474@smallexample
28475@group
28476_increment__incr.1:
28477   subl $4,%esp
28478   movl 8(%esp),%eax
28479#APP
28480   incl %eax
28481#NO_APP
28482   movl %eax,%edx
28483   movl %ecx,(%esp)
28484   addl $4,%esp
28485   ret
28486@end group
28487@end smallexample
28488
28489@c ---------------------------------------------------------------------------
28490@node Inlining Inline Assembler Code
28491@section Inlining Inline Assembler Code
28492
28493@noindent
28494For a short subprogram such as the @code{Incr} function in the previous
28495section, the overhead of the call and return (creating / deleting the stack
28496frame) can be significant, compared to the amount of code in the subprogram
28497body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28498which directs the compiler to expand invocations of the subprogram at the
28499point(s) of call, instead of setting up a stack frame for out-of-line calls.
28500Here is the resulting program:
28501
28502@smallexample @c ada
28503@group
28504with Interfaces; use Interfaces;
28505with Ada.Text_IO; use Ada.Text_IO;
28506with System.Machine_Code; use System.Machine_Code;
28507procedure Increment_2 is
28508
28509   function Incr (Value : Unsigned_32) return Unsigned_32 is
28510      Result : Unsigned_32;
28511   begin
28512      Asm ("incl %0",
28513           Outputs => Unsigned_32'Asm_Output ("=a", Result),
28514           Inputs  => Unsigned_32'Asm_Input ("a", Value));
28515      return Result;
28516   end Incr;
28517   pragma Inline (Increment);
28518
28519   Value : Unsigned_32;
28520
28521begin
28522   Value := 5;
28523   Put_Line ("Value before is" & Value'Img);
28524   Value := Increment (Value);
28525   Put_Line ("Value after is" & Value'Img);
28526end Increment_2;
28527@end group
28528@end smallexample
28529
28530Compile the program with both optimization (@option{-O2}) and inlining
28531(@option{-gnatn}) enabled.
28532
28533The @code{Incr} function is still compiled as usual, but at the
28534point in @code{Increment} where our function used to be called:
28535
28536@smallexample
28537@group
28538pushl %edi
28539call _increment__incr.1
28540@end group
28541@end smallexample
28542
28543@noindent
28544the code for the function body directly appears:
28545
28546@smallexample
28547@group
28548movl %esi,%eax
28549#APP
28550   incl %eax
28551#NO_APP
28552   movl %eax,%edx
28553@end group
28554@end smallexample
28555
28556@noindent
28557thus saving the overhead of stack frame setup and an out-of-line call.
28558
28559@c ---------------------------------------------------------------------------
28560@node Other Asm Functionality
28561@section Other @code{Asm} Functionality
28562
28563@noindent
28564This section describes two important parameters to the @code{Asm}
28565procedure: @code{Clobber}, which identifies register usage;
28566and @code{Volatile}, which inhibits unwanted optimizations.
28567
28568@menu
28569* The Clobber Parameter::
28570* The Volatile Parameter::
28571@end menu
28572
28573@c ---------------------------------------------------------------------------
28574@node The Clobber Parameter
28575@subsection The @code{Clobber} Parameter
28576
28577@noindent
28578One of the dangers of intermixing assembly language and a compiled language
28579such as Ada is that the compiler needs to be aware of which registers are
28580being used by the assembly code.  In some cases, such as the earlier examples,
28581the constraint string is sufficient to indicate register usage (e.g.,
28582@code{"a"} for
28583the eax register).  But more generally, the compiler needs an explicit
28584identification of the registers that are used by the Inline Assembly
28585statements.
28586
28587Using a register that the compiler doesn't know about
28588could be a side effect of an instruction (like @code{mull}
28589storing its result in both eax and edx).
28590It can also arise from explicit register usage in your
28591assembly code; for example:
28592@smallexample
28593@group
28594Asm ("movl %0, %%ebx" & LF & HT &
28595     "movl %%ebx, %1",
28596     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28597     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
28598@end group
28599@end smallexample
28600@noindent
28601where the compiler (since it does not analyze the @code{Asm} template string)
28602does not know you are using the ebx register.
28603
28604In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28605to identify the registers that will be used by your assembly code:
28606
28607@smallexample
28608@group
28609Asm ("movl %0, %%ebx" & LF & HT &
28610     "movl %%ebx, %1",
28611     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28612     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28613     Clobber => "ebx");
28614@end group
28615@end smallexample
28616
28617The Clobber parameter is a static string expression specifying the
28618register(s) you are using.  Note that register names are @emph{not} prefixed
28619by a percent sign. Also, if more than one register is used then their names
28620are separated by commas; e.g., @code{"eax, ebx"}
28621
28622The @code{Clobber} parameter has several additional uses:
28623@enumerate
28624@item Use ``register'' name @code{cc} to indicate that flags might have changed
28625@item Use ``register'' name @code{memory} if you changed a memory location
28626@end enumerate
28627
28628@c ---------------------------------------------------------------------------
28629@node The Volatile Parameter
28630@subsection The @code{Volatile} Parameter
28631@cindex Volatile parameter
28632
28633@noindent
28634Compiler optimizations in the presence of Inline Assembler may sometimes have
28635unwanted effects.  For example, when an @code{Asm} invocation with an input
28636variable is inside a loop, the compiler might move the loading of the input
28637variable outside the loop, regarding it as a one-time initialization.
28638
28639If this effect is not desired, you can disable such optimizations by setting
28640the @code{Volatile} parameter to @code{True}; for example:
28641
28642@smallexample @c ada
28643@group
28644Asm ("movl %0, %%ebx" & LF & HT &
28645     "movl %%ebx, %1",
28646     Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
28647     Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
28648     Clobber  => "ebx",
28649     Volatile => True);
28650@end group
28651@end smallexample
28652
28653By default, @code{Volatile} is set to @code{False} unless there is no
28654@code{Outputs} parameter.
28655
28656Although setting @code{Volatile} to @code{True} prevents unwanted
28657optimizations, it will also disable other optimizations that might be
28658important for efficiency. In general, you should set @code{Volatile}
28659to @code{True} only if the compiler's optimizations have created
28660problems.
28661@c END OF INLINE ASSEMBLER CHAPTER
28662@c ===============================
28663
28664@c ***********************************
28665@c * Compatibility and Porting Guide *
28666@c ***********************************
28667@node Compatibility and Porting Guide
28668@appendix Compatibility and Porting Guide
28669
28670@noindent
28671This chapter describes the compatibility issues that may arise between
28672GNAT and other Ada compilation systems (including those for Ada 83),
28673and shows how GNAT can expedite porting
28674applications developed in other Ada environments.
28675
28676@menu
28677* Compatibility with Ada 83::
28678* Compatibility between Ada 95 and Ada 2005::
28679* Implementation-dependent characteristics::
28680* Compatibility with Other Ada Systems::
28681* Representation Clauses::
28682@ifclear vms
28683@c Brief section is only in non-VMS version
28684@c Full chapter is in VMS version
28685* Compatibility with HP Ada 83::
28686@end ifclear
28687@ifset vms
28688* Transitioning to 64-Bit GNAT for OpenVMS::
28689@end ifset
28690@end menu
28691
28692@node Compatibility with Ada 83
28693@section Compatibility with Ada 83
28694@cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28695
28696@noindent
28697Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
28698particular, the design intention was that the difficulties associated
28699with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28700that occur when moving from one Ada 83 system to another.
28701
28702However, there are a number of points at which there are minor
28703incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
28704full details of these issues,
28705and should be consulted for a complete treatment.
28706In practice the
28707following subsections treat the most likely issues to be encountered.
28708
28709@menu
28710* Legal Ada 83 programs that are illegal in Ada 95::
28711* More deterministic semantics::
28712* Changed semantics::
28713* Other language compatibility issues::
28714@end menu
28715
28716@node Legal Ada 83 programs that are illegal in Ada 95
28717@subsection Legal Ada 83 programs that are illegal in Ada 95
28718
28719Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28720Ada 95 and thus also in Ada 2005:
28721
28722@table @emph
28723@item Character literals
28724Some uses of character literals are ambiguous.  Since Ada 95 has introduced
28725@code{Wide_Character} as a new predefined character type, some uses of
28726character literals that were legal in Ada 83 are illegal in Ada 95.
28727For example:
28728@smallexample @c ada
28729   for Char in 'A' .. 'Z' loop @dots{} end loop;
28730@end smallexample
28731
28732@noindent
28733The problem is that @code{'A'} and @code{'Z'} could be from either
28734@code{Character} or @code{Wide_Character}.  The simplest correction
28735is to make the type explicit; e.g.:
28736@smallexample @c ada
28737   for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28738@end smallexample
28739
28740@item New reserved words
28741The identifiers @code{abstract}, @code{aliased}, @code{protected},
28742@code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28743Existing Ada 83 code using any of these identifiers must be edited to
28744use some alternative name.
28745
28746@item Freezing rules
28747The rules in Ada 95 are slightly different with regard to the point at
28748which entities are frozen, and representation pragmas and clauses are
28749not permitted past the freeze point.  This shows up most typically in
28750the form of an error message complaining that a representation item
28751appears too late, and the appropriate corrective action is to move
28752the item nearer to the declaration of the entity to which it refers.
28753
28754A particular case is that representation pragmas
28755@ifset vms
28756(including the
28757extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28758@end ifset
28759cannot be applied to a subprogram body.  If necessary, a separate subprogram
28760declaration must be introduced to which the pragma can be applied.
28761
28762@item Optional bodies for library packages
28763In Ada 83, a package that did not require a package body was nevertheless
28764allowed to have one.  This lead to certain surprises in compiling large
28765systems (situations in which the body could be unexpectedly ignored by the
28766binder).  In Ada 95, if a package does not require a body then it is not
28767permitted to have a body.  To fix this problem, simply remove a redundant
28768body if it is empty, or, if it is non-empty, introduce a dummy declaration
28769into the spec that makes the body required.  One approach is to add a private
28770part to the package declaration (if necessary), and define a parameterless
28771procedure called @code{Requires_Body}, which must then be given a dummy
28772procedure body in the package body, which then becomes required.
28773Another approach (assuming that this does not introduce elaboration
28774circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28775since one effect of this pragma is to require the presence of a package body.
28776
28777@item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28778In Ada 95, the exception @code{Numeric_Error} is a renaming of
28779@code{Constraint_Error}.
28780This means that it is illegal to have separate exception handlers for
28781the two exceptions.  The fix is simply to remove the handler for the
28782@code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28783@code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28784
28785@item Indefinite subtypes in generics
28786In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28787as the actual for a generic formal private type, but then the instantiation
28788would be illegal if there were any instances of declarations of variables
28789of this type in the generic body.  In Ada 95, to avoid this clear violation
28790of the methodological principle known as the ``contract model'',
28791the generic declaration explicitly indicates whether
28792or not such instantiations are permitted.  If a generic formal parameter
28793has explicit unknown discriminants, indicated by using @code{(<>)} after the
28794subtype name, then it can be instantiated with indefinite types, but no
28795stand-alone variables can be declared of this type.  Any attempt to declare
28796such a variable will result in an illegality at the time the generic is
28797declared.  If the @code{(<>)} notation is not used, then it is illegal
28798to instantiate the generic with an indefinite type.
28799This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28800It will show up as a compile time error, and
28801the fix is usually simply to add the @code{(<>)} to the generic declaration.
28802@end table
28803
28804@node More deterministic semantics
28805@subsection More deterministic semantics
28806
28807@table @emph
28808@item Conversions
28809Conversions from real types to integer types round away from 0.  In Ada 83
28810the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
28811implementation freedom was intended to support unbiased rounding in
28812statistical applications, but in practice it interfered with portability.
28813In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28814is required.  Numeric code may be affected by this change in semantics.
28815Note, though, that this issue is no worse than already existed in Ada 83
28816when porting code from one vendor to another.
28817
28818@item Tasking
28819The Real-Time Annex introduces a set of policies that define the behavior of
28820features that were implementation dependent in Ada 83, such as the order in
28821which open select branches are executed.
28822@end table
28823
28824@node Changed semantics
28825@subsection Changed semantics
28826
28827@noindent
28828The worst kind of incompatibility is one where a program that is legal in
28829Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28830possible in Ada 83.  Fortunately this is extremely rare, but the one
28831situation that you should be alert to is the change in the predefined type
28832@code{Character} from 7-bit ASCII to 8-bit Latin-1.
28833
28834@table @emph
28835@item Range of type @code{Character}
28836The range of @code{Standard.Character} is now the full 256 characters
28837of Latin-1, whereas in most Ada 83 implementations it was restricted
28838to 128 characters. Although some of the effects of
28839this change will be manifest in compile-time rejection of legal
28840Ada 83 programs it is possible for a working Ada 83 program to have
28841a different effect in Ada 95, one that was not permitted in Ada 83.
28842As an example, the expression
28843@code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28844delivers @code{255} as its value.
28845In general, you should look at the logic of any
28846character-processing Ada 83 program and see whether it needs to be adapted
28847to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
28848character handling package that may be relevant if code needs to be adapted
28849to account for the additional Latin-1 elements.
28850The desirable fix is to
28851modify the program to accommodate the full character set, but in some cases
28852it may be convenient to define a subtype or derived type of Character that
28853covers only the restricted range.
28854@cindex Latin-1
28855@end table
28856
28857@node Other language compatibility issues
28858@subsection Other language compatibility issues
28859
28860@table @emph
28861@item @option{-gnat83} switch
28862All implementations of GNAT provide a switch that causes GNAT to operate
28863in Ada 83 mode.  In this mode, some but not all compatibility problems
28864of the type described above are handled automatically.  For example, the
28865new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28866as identifiers as in Ada 83.
28867However,
28868in practice, it is usually advisable to make the necessary modifications
28869to the program to remove the need for using this switch.
28870See @ref{Compiling Different Versions of Ada}.
28871
28872@item Support for removed Ada 83 pragmas and attributes
28873A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28874generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
28875compilers are allowed, but not required, to implement these missing
28876elements.  In contrast with some other compilers, GNAT implements all
28877such pragmas and attributes, eliminating this compatibility concern.  These
28878include @code{pragma Interface} and the floating point type attributes
28879(@code{Emax}, @code{Mantissa}, etc.), among other items.
28880@end table
28881
28882
28883@node Compatibility between Ada 95 and Ada 2005
28884@section Compatibility between Ada 95 and Ada 2005
28885@cindex Compatibility between Ada 95 and Ada 2005
28886
28887@noindent
28888Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28889a number of incompatibilities. Several are enumerated below;
28890for a complete description please see the
28891Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28892@cite{Rationale for Ada 2005}.
28893
28894@table @emph
28895@item New reserved words.
28896The words @code{interface}, @code{overriding} and @code{synchronized} are
28897reserved in Ada 2005.
28898A pre-Ada 2005 program that uses any of these as an identifier will be
28899illegal.
28900
28901@item New declarations in predefined packages.
28902A number of packages in the predefined environment contain new declarations:
28903@code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28904@code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28905@code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28906@code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28907@code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28908If an Ada 95 program does a @code{with} and @code{use} of any of these
28909packages, the new declarations may cause name clashes.
28910
28911@item Access parameters.
28912A nondispatching subprogram with an access parameter cannot be renamed
28913as a dispatching operation.  This was permitted in Ada 95.
28914
28915@item Access types, discriminants, and constraints.
28916Rule changes in this area have led to some incompatibilities; for example,
28917constrained subtypes of some access types are not permitted in Ada 2005.
28918
28919@item Aggregates for limited types.
28920The allowance of aggregates for limited types in Ada 2005 raises the
28921possibility of ambiguities in legal Ada 95 programs, since additional types
28922now need to be considered in expression resolution.
28923
28924@item Fixed-point multiplication and division.
28925Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28926were legal in Ada 95 and invoked the predefined versions of these operations,
28927are now ambiguous.
28928The ambiguity may be resolved either by applying a type conversion to the
28929expression, or by explicitly invoking the operation from package
28930@code{Standard}.
28931
28932@item Return-by-reference types.
28933The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
28934can declare a function returning a value from an anonymous access type.
28935@end table
28936
28937
28938@node Implementation-dependent characteristics
28939@section Implementation-dependent characteristics
28940@noindent
28941Although the Ada language defines the semantics of each construct as
28942precisely as practical, in some situations (for example for reasons of
28943efficiency, or where the effect is heavily dependent on the host or target
28944platform) the implementation is allowed some freedom.  In porting Ada 83
28945code to GNAT, you need to be aware of whether / how the existing code
28946exercised such implementation dependencies.  Such characteristics fall into
28947several categories, and GNAT offers specific support in assisting the
28948transition from certain Ada 83 compilers.
28949
28950@menu
28951* Implementation-defined pragmas::
28952* Implementation-defined attributes::
28953* Libraries::
28954* Elaboration order::
28955* Target-specific aspects::
28956@end menu
28957
28958@node Implementation-defined pragmas
28959@subsection Implementation-defined pragmas
28960
28961@noindent
28962Ada compilers are allowed to supplement the language-defined pragmas, and
28963these are a potential source of non-portability.  All GNAT-defined pragmas
28964are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
28965Reference Manual}, and these include several that are specifically
28966intended to correspond to other vendors' Ada 83 pragmas.
28967For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28968For compatibility with HP Ada 83, GNAT supplies the pragmas
28969@code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28970@code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28971and @code{Volatile}.
28972Other relevant pragmas include @code{External} and @code{Link_With}.
28973Some vendor-specific
28974Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28975recognized, thus
28976avoiding compiler rejection of units that contain such pragmas; they are not
28977relevant in a GNAT context and hence are not otherwise implemented.
28978
28979@node Implementation-defined attributes
28980@subsection Implementation-defined attributes
28981
28982Analogous to pragmas, the set of attributes may be extended by an
28983implementation.  All GNAT-defined attributes are described in
28984@ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
28985Manual}, and these include several that are specifically intended
28986to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
28987the attribute @code{VADS_Size} may be useful.  For compatibility with HP
28988Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
28989@code{Type_Class}.
28990
28991@node Libraries
28992@subsection Libraries
28993@noindent
28994Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
28995code uses vendor-specific libraries then there are several ways to manage
28996this in Ada 95 or Ada 2005:
28997@enumerate
28998@item
28999If the source code for the libraries (specs and bodies) are
29000available, then the libraries can be migrated in the same way as the
29001application.
29002@item
29003If the source code for the specs but not the bodies are
29004available, then you can reimplement the bodies.
29005@item
29006Some features introduced by Ada 95 obviate the need for library support.  For
29007example most Ada 83 vendors supplied a package for unsigned integers.  The
29008Ada 95 modular type feature is the preferred way to handle this need, so
29009instead of migrating or reimplementing the unsigned integer package it may
29010be preferable to retrofit the application using modular types.
29011@end enumerate
29012
29013@node Elaboration order
29014@subsection Elaboration order
29015@noindent
29016The implementation can choose any elaboration order consistent with the unit
29017dependency relationship.  This freedom means that some orders can result in
29018Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29019to invoke a subprogram its body has been elaborated, or to instantiate a
29020generic before the generic body has been elaborated.  By default GNAT
29021attempts to choose a safe order (one that will not encounter access before
29022elaboration problems) by implicitly inserting @code{Elaborate} or
29023@code{Elaborate_All} pragmas where
29024needed.  However, this can lead to the creation of elaboration circularities
29025and a resulting rejection of the program by gnatbind.  This issue is
29026thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29027In brief, there are several
29028ways to deal with this situation:
29029
29030@itemize @bullet
29031@item
29032Modify the program to eliminate the circularities, e.g.@: by moving
29033elaboration-time code into explicitly-invoked procedures
29034@item
29035Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29036@code{Elaborate} pragmas, and then inhibit the generation of implicit
29037@code{Elaborate_All}
29038pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29039(by selectively suppressing elaboration checks via pragma
29040@code{Suppress(Elaboration_Check)} when it is safe to do so).
29041@end itemize
29042
29043@node Target-specific aspects
29044@subsection Target-specific aspects
29045@noindent
29046Low-level applications need to deal with machine addresses, data
29047representations, interfacing with assembler code, and similar issues.  If
29048such an Ada 83 application is being ported to different target hardware (for
29049example where the byte endianness has changed) then you will need to
29050carefully examine the program logic; the porting effort will heavily depend
29051on the robustness of the original design.  Moreover, Ada 95 (and thus
29052Ada 2005) are sometimes
29053incompatible with typical Ada 83 compiler practices regarding implicit
29054packing, the meaning of the Size attribute, and the size of access values.
29055GNAT's approach to these issues is described in @ref{Representation Clauses}.
29056
29057@node Compatibility with Other Ada Systems
29058@section Compatibility with Other Ada Systems
29059
29060@noindent
29061If programs avoid the use of implementation dependent and
29062implementation defined features, as documented in the @cite{Ada
29063Reference Manual}, there should be a high degree of portability between
29064GNAT and other Ada systems.  The following are specific items which
29065have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29066compilers, but do not affect porting code to GNAT@.
29067(As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29068the following issues may or may not arise for Ada 2005 programs
29069when other compilers appear.)
29070
29071@table @emph
29072@item Ada 83 Pragmas and Attributes
29073Ada 95 compilers are allowed, but not required, to implement the missing
29074Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29075GNAT implements all such pragmas and attributes, eliminating this as
29076a compatibility concern, but some other Ada 95 compilers reject these
29077pragmas and attributes.
29078
29079@item Specialized Needs Annexes
29080GNAT implements the full set of special needs annexes.  At the
29081current time, it is the only Ada 95 compiler to do so.  This means that
29082programs making use of these features may not be portable to other Ada
2908395 compilation systems.
29084
29085@item Representation Clauses
29086Some other Ada 95 compilers implement only the minimal set of
29087representation clauses required by the Ada 95 reference manual.  GNAT goes
29088far beyond this minimal set, as described in the next section.
29089@end table
29090
29091@node Representation Clauses
29092@section Representation Clauses
29093
29094@noindent
29095The Ada 83 reference manual was quite vague in describing both the minimal
29096required implementation of representation clauses, and also their precise
29097effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
29098minimal set of capabilities required is still quite limited.
29099
29100GNAT implements the full required set of capabilities in
29101Ada 95 and Ada 2005, but also goes much further, and in particular
29102an effort has been made to be compatible with existing Ada 83 usage to the
29103greatest extent possible.
29104
29105A few cases exist in which Ada 83 compiler behavior is incompatible with
29106the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
29107intentional or accidental dependence on specific implementation dependent
29108characteristics of these Ada 83 compilers.  The following is a list of
29109the cases most likely to arise in existing Ada 83 code.
29110
29111@table @emph
29112@item Implicit Packing
29113Some Ada 83 compilers allowed a Size specification to cause implicit
29114packing of an array or record.  This could cause expensive implicit
29115conversions for change of representation in the presence of derived
29116types, and the Ada design intends to avoid this possibility.
29117Subsequent AI's were issued to make it clear that such implicit
29118change of representation in response to a Size clause is inadvisable,
29119and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29120Reference Manuals as implementation advice that is followed by GNAT@.
29121The problem will show up as an error
29122message rejecting the size clause.  The fix is simply to provide
29123the explicit pragma @code{Pack}, or for more fine tuned control, provide
29124a Component_Size clause.
29125
29126@item Meaning of Size Attribute
29127The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29128the minimal number of bits required to hold values of the type.  For example,
29129on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
2913032 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
29131some 32 in this situation.  This problem will usually show up as a compile
29132time error, but not always.  It is a good idea to check all uses of the
29133'Size attribute when porting Ada 83 code.  The GNAT specific attribute
29134Object_Size can provide a useful way of duplicating the behavior of
29135some Ada 83 compiler systems.
29136
29137@item Size of Access Types
29138A common assumption in Ada 83 code is that an access type is in fact a pointer,
29139and that therefore it will be the same size as a System.Address value.  This
29140assumption is true for GNAT in most cases with one exception.  For the case of
29141a pointer to an unconstrained array type (where the bounds may vary from one
29142value of the access type to another), the default is to use a ``fat pointer'',
29143which is represented as two separate pointers, one to the bounds, and one to
29144the array.  This representation has a number of advantages, including improved
29145efficiency.  However, it may cause some difficulties in porting existing Ada 83
29146code which makes the assumption that, for example, pointers fit in 32 bits on
29147a machine with 32-bit addressing.
29148
29149To get around this problem, GNAT also permits the use of ``thin pointers'' for
29150access types in this case (where the designated type is an unconstrained array
29151type).  These thin pointers are indeed the same size as a System.Address value.
29152To specify a thin pointer, use a size clause for the type, for example:
29153
29154@smallexample @c ada
29155type X is access all String;
29156for X'Size use Standard'Address_Size;
29157@end smallexample
29158
29159@noindent
29160which will cause the type X to be represented using a single pointer.
29161When using this representation, the bounds are right behind the array.
29162This representation is slightly less efficient, and does not allow quite
29163such flexibility in the use of foreign pointers or in using the
29164Unrestricted_Access attribute to create pointers to non-aliased objects.
29165But for any standard portable use of the access type it will work in
29166a functionally correct manner and allow porting of existing code.
29167Note that another way of forcing a thin pointer representation
29168is to use a component size clause for the element size in an array,
29169or a record representation clause for an access field in a record.
29170@end table
29171
29172@ifclear vms
29173@c This brief section is only in the non-VMS version
29174@c The complete chapter on HP Ada is in the VMS version
29175@node Compatibility with HP Ada 83
29176@section Compatibility with HP Ada 83
29177
29178@noindent
29179The VMS version of GNAT fully implements all the pragmas and attributes
29180provided by HP Ada 83, as well as providing the standard HP Ada 83
29181libraries, including Starlet.  In addition, data layouts and parameter
29182passing conventions are highly compatible.  This means that porting
29183existing HP Ada 83 code to GNAT in VMS systems should be easier than
29184most other porting efforts.  The following are some of the most
29185significant differences between GNAT and HP Ada 83.
29186
29187@table @emph
29188@item Default floating-point representation
29189In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29190it is VMS format.  GNAT does implement the necessary pragmas
29191(Long_Float, Float_Representation) for changing this default.
29192
29193@item System
29194The package System in GNAT exactly corresponds to the definition in the
29195Ada 95 reference manual, which means that it excludes many of the
29196HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
29197that contains the additional definitions, and a special pragma,
29198Extend_System allows this package to be treated transparently as an
29199extension of package System.
29200
29201@item To_Address
29202The definitions provided by Aux_DEC are exactly compatible with those
29203in the HP Ada 83 version of System, with one exception.
29204HP Ada provides the following declarations:
29205
29206@smallexample @c ada
29207TO_ADDRESS (INTEGER)
29208TO_ADDRESS (UNSIGNED_LONGWORD)
29209TO_ADDRESS (@i{universal_integer})
29210@end smallexample
29211
29212@noindent
29213The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29214an extension to Ada 83 not strictly compatible with the reference manual.
29215In GNAT, we are constrained to be exactly compatible with the standard,
29216and this means we cannot provide this capability.  In HP Ada 83, the
29217point of this definition is to deal with a call like:
29218
29219@smallexample @c ada
29220TO_ADDRESS (16#12777#);
29221@end smallexample
29222
29223@noindent
29224Normally, according to the Ada 83 standard, one would expect this to be
29225ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29226of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
29227definition using @i{universal_integer} takes precedence.
29228
29229In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29230is not possible to be 100% compatible.  Since there are many programs using
29231numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29232to change the name of the function in the UNSIGNED_LONGWORD case, so the
29233declarations provided in the GNAT version of AUX_Dec are:
29234
29235@smallexample @c ada
29236function To_Address (X : Integer) return Address;
29237pragma Pure_Function (To_Address);
29238
29239function To_Address_Long (X : Unsigned_Longword)
29240 return Address;
29241pragma Pure_Function (To_Address_Long);
29242@end smallexample
29243
29244@noindent
29245This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29246change the name to TO_ADDRESS_LONG@.
29247
29248@item Task_Id values
29249The Task_Id values assigned will be different in the two systems, and GNAT
29250does not provide a specified value for the Task_Id of the environment task,
29251which in GNAT is treated like any other declared task.
29252@end table
29253
29254@noindent
29255For full details on these and other less significant compatibility issues,
29256see appendix E of the HP publication entitled @cite{HP Ada, Technical
29257Overview and Comparison on HP Platforms}.
29258
29259For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29260attributes are recognized, although only a subset of them can sensibly
29261be implemented.  The description of pragmas in @ref{Implementation
29262Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
29263indicates whether or not they are applicable to non-VMS systems.
29264@end ifclear
29265
29266@ifset vms
29267@node Transitioning to 64-Bit GNAT for OpenVMS
29268@section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29269
29270@noindent
29271This section is meant to assist users of pre-2006 @value{EDITION}
29272for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29273the version of the GNAT technology supplied in 2006 and later for
29274OpenVMS on both Alpha and I64.
29275
29276@menu
29277* Introduction to transitioning::
29278* Migration of 32 bit code::
29279* Taking advantage of 64 bit addressing::
29280* Technical details::
29281@end menu
29282
29283@node Introduction to transitioning
29284@subsection Introduction
29285
29286@noindent
2928764-bit @value{EDITION} for Open VMS has been designed to meet
29288three main goals:
29289
29290@enumerate
29291@item
29292Providing a full conforming implementation of Ada 95 and Ada 2005
29293
29294@item
29295Allowing maximum backward compatibility, thus easing migration of existing
29296Ada source code
29297
29298@item
29299Supplying a path for exploiting the full 64-bit address range
29300@end enumerate
29301
29302@noindent
29303Ada's strong typing semantics has made it
29304impractical to have different 32-bit and 64-bit modes. As soon as
29305one object could possibly be outside the 32-bit address space, this
29306would make it necessary for the @code{System.Address} type to be 64 bits.
29307In particular, this would cause inconsistencies if 32-bit code is
29308called from 64-bit code that raises an exception.
29309
29310This issue has been resolved by always using 64-bit addressing
29311at the system level, but allowing for automatic conversions between
2931232-bit and 64-bit addresses where required. Thus users who
29313do not currently require 64-bit addressing capabilities, can
29314recompile their code with only minimal changes (and indeed
29315if the code is written in portable Ada, with no assumptions about
29316the size of the @code{Address} type, then no changes at all are necessary).
29317At the same time,
29318this approach provides a simple, gradual upgrade path to future
29319use of larger memories than available for 32-bit systems.
29320Also, newly written applications or libraries will by default
29321be fully compatible with future systems exploiting 64-bit
29322addressing capabilities.
29323
29324@ref{Migration of 32 bit code}, will focus on porting applications
29325that do not require more than 2 GB of
29326addressable memory. This code will be referred to as
29327@emph{32-bit code}.
29328For applications intending to exploit the full 64-bit address space,
29329@ref{Taking advantage of 64 bit addressing},
29330will consider further changes that may be required.
29331Such code will be referred to below as @emph{64-bit code}.
29332
29333@node Migration of 32 bit code
29334@subsection Migration of 32-bit code
29335
29336@menu
29337* Address types::
29338* Access types and 32/64-bit allocation::
29339* Unchecked conversions::
29340* Predefined constants::
29341* Interfacing with C::
29342* 32/64-bit descriptors::
29343* Experience with source compatibility::
29344@end menu
29345
29346@node Address types
29347@subsubsection Address types
29348
29349@noindent
29350To solve the problem of mixing 64-bit and 32-bit addressing,
29351while maintaining maximum backward compatibility, the following
29352approach has been taken:
29353
29354@itemize @bullet
29355@item
29356@code{System.Address} always has a size of 64 bits
29357@cindex @code{System.Address} size
29358@cindex @code{Address} size
29359
29360@item
29361@code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29362@cindex @code{System.Short_Address} size
29363@cindex @code{Short_Address} size
29364@end itemize
29365
29366@noindent
29367Since @code{System.Short_Address} is a subtype of @code{System.Address},
29368a @code{Short_Address}
29369may be used where an @code{Address} is required, and vice versa, without
29370needing explicit type conversions.
29371By virtue of the Open VMS parameter passing conventions,
29372even imported
29373and exported subprograms that have 32-bit address parameters are
29374compatible with those that have 64-bit address parameters.
29375(See @ref{Making code 64 bit clean} for details.)
29376
29377The areas that may need attention are those where record types have
29378been defined that contain components of the type @code{System.Address}, and
29379where objects of this type are passed to code expecting a record layout with
2938032-bit addresses.
29381
29382Different compilers on different platforms cannot be
29383expected to represent the same type in the same way,
29384since alignment constraints
29385and other system-dependent properties affect the compiler's decision.
29386For that reason, Ada code
29387generally uses representation clauses to specify the expected
29388layout where required.
29389
29390If such a representation clause uses 32 bits for a component having
29391the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29392will detect that error and produce a specific diagnostic message.
29393The developer should then determine whether the representation
29394should be 64 bits or not and make either of two changes:
29395change the size to 64 bits and leave the type as @code{System.Address}, or
29396leave the size as 32 bits and change the type to @code{System.Short_Address}.
29397Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29398required in any code setting or accessing the field; the compiler will
29399automatically perform any needed conversions between address
29400formats.
29401
29402@node Access types and 32/64-bit allocation
29403@subsubsection Access types and 32/64-bit allocation
29404@cindex 32-bit allocation
29405@cindex 64-bit allocation
29406
29407@noindent
29408By default, objects designated by access values are always allocated in
29409the 64-bit address space, and access values themselves are represented
29410in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
29411is required (for example if the address of an allocated object is assigned
29412to a @code{Short_Address} variable), then several alternatives are available:
29413
29414@itemize @bullet
29415@item
29416A pool-specific access type (ie, an @w{Ada 83} access type, whose
29417definition is @code{access T} versus @code{access all T} or
29418@code{access constant T}), may be declared with a @code{'Size} representation
29419clause that establishes the size as 32 bits.
29420In such circumstances allocations for that type will
29421be from the 32-bit heap.  Such a clause is not permitted
29422for a general access type (declared with @code{access all} or
29423@code{access constant}) as values of such types must be able to refer
29424to any object of the designated type, including objects residing outside
29425the 32-bit address range.  Existing @w{Ada 83} code will not contain such
29426type definitions, however, since general access types were introduced
29427in @w{Ada 95}.
29428
29429@item
29430Switches for @command{GNAT BIND} control whether the internal GNAT
29431allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
29432@cindex @code{__gnat_malloc}
29433The switches are respectively @option{-H64} (the default) and
29434@option{-H32}.
29435@cindex @option{-H32} (@command{gnatbind})
29436@cindex @option{-H64} (@command{gnatbind})
29437
29438@item
29439The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
29440@cindex @code{GNAT$NO_MALLOC_64} environment variable
29441may be used to force @code{__gnat_malloc} to use 32-bit allocation.
29442If this variable is left
29443undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
29444then the default (64-bit) allocation is used.
29445If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
29446then 32-bit allocation is used.  The gnatbind qualifiers described above
29447override this logical name.
29448
29449@item
29450A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
29451@cindex @option{-mno-malloc64} (^gcc^gcc^)
29452at a low level to convert explicit calls to @code{malloc} and related
29453functions from the C run-time library so that they perform allocations
29454in the 32-bit heap.
29455Since all internal allocations from GNAT use @code{__gnat_malloc},
29456this switch is not required unless the program makes explicit calls on
29457@code{malloc} (or related functions) from interfaced C code.
29458@end itemize
29459
29460
29461@node Unchecked conversions
29462@subsubsection Unchecked conversions
29463
29464@noindent
29465In the case of an @code{Unchecked_Conversion} where the source type is a
2946664-bit access type or the type @code{System.Address}, and the target
29467type is a 32-bit type, the compiler will generate a warning.
29468Even though the generated code will still perform the required
29469conversions, it is highly recommended in these cases to use
29470respectively a 32-bit access type or @code{System.Short_Address}
29471as the source type.
29472
29473@node Predefined constants
29474@subsubsection Predefined constants
29475
29476@noindent
29477The following table shows the correspondence between pre-2006 versions of
29478@value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29479(``New''):
29480
29481@multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29482@item   @b{Constant}                     @tab @b{Old} @tab @b{New}
29483@item   @code{System.Word_Size}          @tab 32      @tab 64
29484@item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
29485@item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
29486@item   @code{System.Address_Size}       @tab 32      @tab 64
29487@end multitable
29488
29489@noindent
29490If you need to refer to the specific
29491memory size of a 32-bit implementation, instead of the
29492actual memory size, use @code{System.Short_Memory_Size}
29493rather than @code{System.Memory_Size}.
29494Similarly, references to @code{System.Address_Size} may need
29495to be replaced by @code{System.Short_Address'Size}.
29496The program @command{gnatfind} may be useful for locating
29497references to the above constants, so that you can verify that they
29498are still correct.
29499
29500@node Interfacing with C
29501@subsubsection Interfacing with C
29502
29503@noindent
29504In order to minimize the impact of the transition to 64-bit addresses on
29505legacy programs, some fundamental types in the @code{Interfaces.C}
29506package hierarchy continue to be represented in 32 bits.
29507These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29508This eases integration with the default HP C layout choices, for example
29509as found in the system routines in @code{DECC$SHR.EXE}.
29510Because of this implementation choice, the type fully compatible with
29511@code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29512Depending on the context the compiler will issue a
29513warning or an error when type @code{Address} is used, alerting the user to a
29514potential problem. Otherwise 32-bit programs that use
29515@code{Interfaces.C} should normally not require code modifications
29516
29517The other issue arising with C interfacing concerns pragma @code{Convention}.
29518For VMS 64-bit systems, there is an issue of the appropriate default size
29519of C convention pointers in the absence of an explicit size clause. The HP
29520C compiler can choose either 32 or 64 bits depending on compiler options.
29521GNAT chooses 32-bits rather than 64-bits in the default case where no size
29522clause is given. This proves a better choice for porting 32-bit legacy
29523applications. In order to have a 64-bit representation, it is necessary to
29524specify a size representation clause. For example:
29525
29526@smallexample @c ada
29527type int_star is access Interfaces.C.int;
29528pragma Convention(C, int_star);
29529for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
29530@end smallexample
29531
29532@node 32/64-bit descriptors
29533@subsubsection 32/64-bit descriptors
29534
29535@noindent
29536By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
29537subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29538@code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29539@code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29540@cindex @code{Short_Descriptor} mechanism for imported subprograms
29541
29542If the configuration pragma @code{Short_Descriptors} is supplied, then
29543all descriptors will be 32 bits.
29544@cindex pragma @code{Short_Descriptors}
29545
29546@node Experience with source compatibility
29547@subsubsection Experience with source compatibility
29548
29549@noindent
29550The Security Server and STARLET on I64 provide an interesting ``test case''
29551for source compatibility issues, since it is in such system code
29552where assumptions about @code{Address} size might be expected to occur.
29553Indeed, there were a small number of occasions in the Security Server
29554file @file{jibdef.ads}
29555where a representation clause for a record type specified
2955632 bits for a component of type @code{Address}.
29557All of these errors were detected by the compiler.
29558The repair was obvious and immediate; to simply replace @code{Address} by
29559@code{Short_Address}.
29560
29561In the case of STARLET, there were several record types that should
29562have had representation clauses but did not.  In these record types
29563there was an implicit assumption that an @code{Address} value occupied
2956432 bits.
29565These compiled without error, but their usage resulted in run-time error
29566returns from STARLET system calls.
29567Future GNAT technology enhancements may include a tool that detects and flags
29568these sorts of potential source code porting problems.
29569
29570@c ****************************************
29571@node Taking advantage of 64 bit addressing
29572@subsection Taking advantage of 64-bit addressing
29573
29574@menu
29575* Making code 64 bit clean::
29576* Allocating memory from the 64 bit storage pool::
29577* Restrictions on use of 64 bit objects::
29578* STARLET and other predefined libraries::
29579@end menu
29580
29581@node Making code 64 bit clean
29582@subsubsection Making code 64-bit clean
29583
29584@noindent
29585In order to prevent problems that may occur when (parts of) a
29586system start using memory outside the 32-bit address range,
29587we recommend some additional guidelines:
29588
29589@itemize @bullet
29590@item
29591For imported subprograms that take parameters of the
29592type @code{System.Address}, ensure that these subprograms can
29593indeed handle 64-bit addresses. If not, or when in doubt,
29594change the subprogram declaration to specify
29595@code{System.Short_Address} instead.
29596
29597@item
29598Resolve all warnings related to size mismatches in
29599unchecked conversions. Failing to do so causes
29600erroneous execution if the source object is outside
29601the 32-bit address space.
29602
29603@item
29604(optional) Explicitly use the 32-bit storage pool
29605for access types used in a 32-bit context, or use
29606generic access types where possible
29607(@pxref{Restrictions on use of 64 bit objects}).
29608@end itemize
29609
29610@noindent
29611If these rules are followed, the compiler will automatically insert
29612any necessary checks to ensure that no addresses or access values
29613passed to 32-bit code ever refer to objects outside the 32-bit
29614address range.
29615Any attempt to do this will raise @code{Constraint_Error}.
29616
29617@node Allocating memory from the 64 bit storage pool
29618@subsubsection Allocating memory from the 64-bit storage pool
29619
29620@noindent
29621By default, all allocations -- for both pool-specific and general
29622access types -- use the 64-bit storage pool.  To override
29623this default, for an individual access type or globally, see
29624@ref{Access types and 32/64-bit allocation}.
29625
29626@node Restrictions on use of 64 bit objects
29627@subsubsection Restrictions on use of 64-bit objects
29628
29629@noindent
29630Taking the address of an object allocated from a 64-bit storage pool,
29631and then passing this address to a subprogram expecting
29632@code{System.Short_Address},
29633or assigning it to a variable of type @code{Short_Address}, will cause
29634@code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29635(@pxref{Making code 64 bit clean}), or checks are suppressed,
29636no exception is raised and execution
29637will become erroneous.
29638
29639@node STARLET and other predefined libraries
29640@subsubsection STARLET and other predefined libraries
29641
29642@noindent
29643All code that comes as part of GNAT is 64-bit clean, but the
29644restrictions given in @ref{Restrictions on use of 64 bit objects},
29645still apply. Look at the package
29646specs to see in which contexts objects allocated
29647in 64-bit address space are acceptable.
29648
29649@node Technical details
29650@subsection Technical details
29651
29652@noindent
2965364-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29654Ada standard with respect to the type of @code{System.Address}. Previous
29655versions of @value{EDITION} have defined this type as private and implemented it as a
29656modular type.
29657
29658In order to allow defining @code{System.Short_Address} as a proper subtype,
29659and to match the implicit sign extension in parameter passing,
29660in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29661visible (i.e., non-private) integer type.
29662Standard operations on the type, such as the binary operators ``+'', ``-'',
29663etc., that take @code{Address} operands and return an @code{Address} result,
29664have been hidden by declaring these
29665@code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29666ambiguities that would otherwise result from overloading.
29667(Note that, although @code{Address} is a visible integer type,
29668good programming practice dictates against exploiting the type's
29669integer properties such as literals, since this will compromise
29670code portability.)
29671
29672Defining @code{Address} as a visible integer type helps achieve
29673maximum compatibility for existing Ada code,
29674without sacrificing the capabilities of the 64-bit architecture.
29675@end ifset
29676
29677@c ************************************************
29678@node Microsoft Windows Topics
29679@appendix Microsoft Windows Topics
29680@cindex Windows NT
29681@cindex Windows 95
29682@cindex Windows 98
29683
29684@noindent
29685This chapter describes topics that are specific to the Microsoft Windows
29686platforms (NT, 2000, and XP Professional).
29687
29688@menu
29689@ifclear FSFEDITION
29690* Installing from the Command Line::
29691@end ifclear
29692* Using GNAT on Windows::
29693* Using a network installation of GNAT::
29694* CONSOLE and WINDOWS subsystems::
29695* Temporary Files::
29696* Mixed-Language Programming on Windows::
29697* Windows Calling Conventions::
29698* Introduction to Dynamic Link Libraries (DLLs)::
29699* Using DLLs with GNAT::
29700* Building DLLs with GNAT Project files::
29701* Building DLLs with GNAT::
29702* Building DLLs with gnatdll::
29703* GNAT and Windows Resources::
29704* Debugging a DLL::
29705* Setting Stack Size from gnatlink::
29706* Setting Heap Size from gnatlink::
29707@end menu
29708
29709@ifclear FSFEDITION
29710@node Installing from the Command Line
29711@section Installing from the Command Line
29712@cindex Batch installation
29713@cindex Silent installation
29714@cindex Unassisted installation
29715
29716@noindent
29717By default the @value{EDITION} installers display a GUI that prompts the user
29718to enter installation path and similar information, and guide him through the
29719installation process. It is also possible to perform silent installations
29720using the command-line interface.
29721
29722In order to install one of the @value{EDITION} installers from the command
29723line you should pass parameter @code{/S} (and, optionally,
29724@code{/D=<directory>}) as command-line arguments.
29725
29726@ifset PROEDITION
29727For example, for an unattended installation of
29728@value{EDITION} 7.0.2 into the default directory
29729@code{C:\GNATPRO\7.0.2} you would run:
29730
29731@smallexample
29732gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29733@end smallexample
29734
29735To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29736
29737@smallexample
29738gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29739@end smallexample
29740@end ifset
29741
29742@ifset GPLEDITION
29743For example, for an unattended installation of
29744@value{EDITION} 2012 into @code{C:\GNAT\2012}:
29745
29746@smallexample
29747gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29748@end smallexample
29749@end ifset
29750
29751You can use the same syntax for all installers.
29752
29753Note that unattended installations don't modify system path, nor create file
29754associations, so such activities need to be done by hand.
29755@end ifclear
29756
29757@node Using GNAT on Windows
29758@section Using GNAT on Windows
29759
29760@noindent
29761One of the strengths of the GNAT technology is that its tool set
29762(@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29763@code{gdb} debugger, etc.) is used in the same way regardless of the
29764platform.
29765
29766On Windows this tool set is complemented by a number of Microsoft-specific
29767tools that have been provided to facilitate interoperability with Windows
29768when this is required. With these tools:
29769
29770@itemize @bullet
29771
29772@item
29773You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29774subsystems.
29775
29776@item
29777You can use any Dynamically Linked Library (DLL) in your Ada code (both
29778relocatable and non-relocatable DLLs are supported).
29779
29780@item
29781You can build Ada DLLs for use in other applications. These applications
29782can be written in a language other than Ada (e.g., C, C++, etc). Again both
29783relocatable and non-relocatable Ada DLLs are supported.
29784
29785@item
29786You can include Windows resources in your Ada application.
29787
29788@item
29789You can use or create COM/DCOM objects.
29790@end itemize
29791
29792@noindent
29793Immediately below are listed all known general GNAT-for-Windows restrictions.
29794Other restrictions about specific features like Windows Resources and DLLs
29795are listed in separate sections below.
29796
29797@itemize @bullet
29798
29799@item
29800It is not possible to use @code{GetLastError} and @code{SetLastError}
29801when tasking, protected records, or exceptions are used. In these
29802cases, in order to implement Ada semantics, the GNAT run-time system
29803calls certain Win32 routines that set the last error variable to 0 upon
29804success. It should be possible to use @code{GetLastError} and
29805@code{SetLastError} when tasking, protected record, and exception
29806features are not used, but it is not guaranteed to work.
29807
29808@item
29809It is not possible to link against Microsoft C++ libraries except for
29810import libraries. Interfacing must be done by the mean of DLLs.
29811
29812@item
29813It is possible to link against Microsoft C libraries. Yet the preferred
29814solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29815doesn't require having two different development environments and makes the
29816inter-language debugging experience smoother.
29817
29818@item
29819When the compilation environment is located on FAT32 drives, users may
29820experience recompilations of the source files that have not changed if
29821Daylight Saving Time (DST) state has changed since the last time files
29822were compiled. NTFS drives do not have this problem.
29823
29824@item
29825No components of the GNAT toolset use any entries in the Windows
29826registry. The only entries that can be created are file associations and
29827PATH settings, provided the user has chosen to create them at installation
29828time, as well as some minimal book-keeping information needed to correctly
29829uninstall or integrate different GNAT products.
29830@end itemize
29831
29832@node Using a network installation of GNAT
29833@section Using a network installation of GNAT
29834
29835@noindent
29836Make sure the system on which GNAT is installed is accessible from the
29837current machine, i.e., the install location is shared over the network.
29838Shared resources are accessed on Windows by means of UNC paths, which
29839have the format @code{\\server\sharename\path}
29840
29841In order to use such a network installation, simply add the UNC path of the
29842@file{bin} directory of your GNAT installation in front of your PATH. For
29843example, if GNAT is installed in @file{\GNAT} directory of a share location
29844called @file{c-drive} on a machine @file{LOKI}, the following command will
29845make it available:
29846
29847@code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29848
29849Be aware that every compilation using the network installation results in the
29850transfer of large amounts of data across the network and will likely cause
29851serious performance penalty.
29852
29853@node CONSOLE and WINDOWS subsystems
29854@section CONSOLE and WINDOWS subsystems
29855@cindex CONSOLE Subsystem
29856@cindex WINDOWS Subsystem
29857@cindex -mwindows
29858
29859@noindent
29860There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29861(which is the default subsystem) will always create a console when
29862launching the application. This is not something desirable when the
29863application has a Windows GUI. To get rid of this console the
29864application must be using the @code{WINDOWS} subsystem. To do so
29865the @option{-mwindows} linker option must be specified.
29866
29867@smallexample
29868$ gnatmake winprog -largs -mwindows
29869@end smallexample
29870
29871@node Temporary Files
29872@section Temporary Files
29873@cindex Temporary files
29874
29875@noindent
29876It is possible to control where temporary files gets created by setting
29877the @env{TMP} environment variable. The file will be created:
29878
29879@itemize
29880@item Under the directory pointed to by the @env{TMP} environment variable if
29881this directory exists.
29882
29883@item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29884set (or not pointing to a directory) and if this directory exists.
29885
29886@item Under the current working directory otherwise.
29887@end itemize
29888
29889@noindent
29890This allows you to determine exactly where the temporary
29891file will be created. This is particularly useful in networked
29892environments where you may not have write access to some
29893directories.
29894
29895@node Mixed-Language Programming on Windows
29896@section Mixed-Language Programming on Windows
29897
29898@noindent
29899Developing pure Ada applications on Windows is no different than on
29900other GNAT-supported platforms. However, when developing or porting an
29901application that contains a mix of Ada and C/C++, the choice of your
29902Windows C/C++ development environment conditions your overall
29903interoperability strategy.
29904
29905If you use @command{gcc} or Microsoft C to compile the non-Ada part of
29906your application, there are no Windows-specific restrictions that
29907affect the overall interoperability with your Ada code. If you do want
29908to use the Microsoft tools for your C++ code, you have two choices:
29909
29910@enumerate
29911@item
29912Encapsulate your C++ code in a DLL to be linked with your Ada
29913application. In this case, use the Microsoft or whatever environment to
29914build the DLL and use GNAT to build your executable
29915(@pxref{Using DLLs with GNAT}).
29916
29917@item
29918Or you can encapsulate your Ada code in a DLL to be linked with the
29919other part of your application. In this case, use GNAT to build the DLL
29920(@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
29921or whatever environment to build your executable.
29922@end enumerate
29923
29924In addition to the description about C main in
29925@pxref{Mixed Language Programming} section, if the C main uses a
29926stand-alone library it is required on x86-windows to
29927setup the SEH context. For this the C main must looks like this:
29928
29929@smallexample
29930/* main.c */
29931extern void adainit (void);
29932extern void adafinal (void);
29933extern void __gnat_initialize(void*);
29934extern void call_to_ada (void);
29935
29936int main (int argc, char *argv[])
29937@{
29938  int SEH [2];
29939
29940  /* Initialize the SEH context */
29941  __gnat_initialize (&SEH);
29942
29943  adainit();
29944
29945  /* Then call Ada services in the stand-alone library */
29946
29947  call_to_ada();
29948
29949  adafinal();
29950@}
29951@end smallexample
29952
29953Note that this is not needed on x86_64-windows where the Windows
29954native SEH support is used.
29955
29956@node Windows Calling Conventions
29957@section Windows Calling Conventions
29958@findex Stdcall
29959@findex APIENTRY
29960
29961This section pertain only to Win32. On Win64 there is a single native
29962calling convention. All convention specifiers are ignored on this
29963platform.
29964
29965@menu
29966* C Calling Convention::
29967* Stdcall Calling Convention::
29968* Win32 Calling Convention::
29969* DLL Calling Convention::
29970@end menu
29971
29972@noindent
29973When a subprogram @code{F} (caller) calls a subprogram @code{G}
29974(callee), there are several ways to push @code{G}'s parameters on the
29975stack and there are several possible scenarios to clean up the stack
29976upon @code{G}'s return. A calling convention is an agreed upon software
29977protocol whereby the responsibilities between the caller (@code{F}) and
29978the callee (@code{G}) are clearly defined. Several calling conventions
29979are available for Windows:
29980
29981@itemize @bullet
29982@item
29983@code{C} (Microsoft defined)
29984
29985@item
29986@code{Stdcall} (Microsoft defined)
29987
29988@item
29989@code{Win32} (GNAT specific)
29990
29991@item
29992@code{DLL} (GNAT specific)
29993@end itemize
29994
29995@node C Calling Convention
29996@subsection @code{C} Calling Convention
29997
29998@noindent
29999This is the default calling convention used when interfacing to C/C++
30000routines compiled with either @command{gcc} or Microsoft Visual C++.
30001
30002In the @code{C} calling convention subprogram parameters are pushed on the
30003stack by the caller from right to left. The caller itself is in charge of
30004cleaning up the stack after the call. In addition, the name of a routine
30005with @code{C} calling convention is mangled by adding a leading underscore.
30006
30007The name to use on the Ada side when importing (or exporting) a routine
30008with @code{C} calling convention is the name of the routine. For
30009instance the C function:
30010
30011@smallexample
30012int get_val (long);
30013@end smallexample
30014
30015@noindent
30016should be imported from Ada as follows:
30017
30018@smallexample @c ada
30019@group
30020function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30021pragma Import (C, Get_Val, External_Name => "get_val");
30022@end group
30023@end smallexample
30024
30025@noindent
30026Note that in this particular case the @code{External_Name} parameter could
30027have been omitted since, when missing, this parameter is taken to be the
30028name of the Ada entity in lower case. When the @code{Link_Name} parameter
30029is missing, as in the above example, this parameter is set to be the
30030@code{External_Name} with a leading underscore.
30031
30032When importing a variable defined in C, you should always use the @code{C}
30033calling convention unless the object containing the variable is part of a
30034DLL (in which case you should use the @code{Stdcall} calling
30035convention, @pxref{Stdcall Calling Convention}).
30036
30037@node Stdcall Calling Convention
30038@subsection @code{Stdcall} Calling Convention
30039
30040@noindent
30041This convention, which was the calling convention used for Pascal
30042programs, is used by Microsoft for all the routines in the Win32 API for
30043efficiency reasons. It must be used to import any routine for which this
30044convention was specified.
30045
30046In the @code{Stdcall} calling convention subprogram parameters are pushed
30047on the stack by the caller from right to left. The callee (and not the
30048caller) is in charge of cleaning the stack on routine exit. In addition,
30049the name of a routine with @code{Stdcall} calling convention is mangled by
30050adding a leading underscore (as for the @code{C} calling convention) and a
30051trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
30052bytes) of the parameters passed to the routine.
30053
30054The name to use on the Ada side when importing a C routine with a
30055@code{Stdcall} calling convention is the name of the C routine. The leading
30056underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
30057the compiler. For instance the Win32 function:
30058
30059@smallexample
30060@b{APIENTRY} int get_val (long);
30061@end smallexample
30062
30063@noindent
30064should be imported from Ada as follows:
30065
30066@smallexample @c ada
30067@group
30068function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30069pragma Import (Stdcall, Get_Val);
30070--  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30071@end group
30072@end smallexample
30073
30074@noindent
30075As for the @code{C} calling convention, when the @code{External_Name}
30076parameter is missing, it is taken to be the name of the Ada entity in lower
30077case. If instead of writing the above import pragma you write:
30078
30079@smallexample @c ada
30080@group
30081function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30082pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30083@end group
30084@end smallexample
30085
30086@noindent
30087then the imported routine is @code{_retrieve_val@@4}. However, if instead
30088of specifying the @code{External_Name} parameter you specify the
30089@code{Link_Name} as in the following example:
30090
30091@smallexample @c ada
30092@group
30093function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30094pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30095@end group
30096@end smallexample
30097
30098@noindent
30099then the imported routine is @code{retrieve_val}, that is, there is no
30100decoration at all. No leading underscore and no Stdcall suffix
30101@code{@@}@code{@var{nn}}.
30102
30103@noindent
30104This is especially important as in some special cases a DLL's entry
30105point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
30106name generated for a call has it.
30107
30108@noindent
30109It is also possible to import variables defined in a DLL by using an
30110import pragma for a variable. As an example, if a DLL contains a
30111variable defined as:
30112
30113@smallexample
30114int my_var;
30115@end smallexample
30116
30117@noindent
30118then, to access this variable from Ada you should write:
30119
30120@smallexample @c ada
30121@group
30122My_Var : Interfaces.C.int;
30123pragma Import (Stdcall, My_Var);
30124@end group
30125@end smallexample
30126
30127@noindent
30128Note that to ease building cross-platform bindings this convention
30129will be handled as a @code{C} calling convention on non-Windows platforms.
30130
30131@node Win32 Calling Convention
30132@subsection @code{Win32} Calling Convention
30133
30134@noindent
30135This convention, which is GNAT-specific is fully equivalent to the
30136@code{Stdcall} calling convention described above.
30137
30138@node DLL Calling Convention
30139@subsection @code{DLL} Calling Convention
30140
30141@noindent
30142This convention, which is GNAT-specific is fully equivalent to the
30143@code{Stdcall} calling convention described above.
30144
30145@node Introduction to Dynamic Link Libraries (DLLs)
30146@section Introduction to Dynamic Link Libraries (DLLs)
30147@findex DLL
30148
30149@noindent
30150A Dynamically Linked Library (DLL) is a library that can be shared by
30151several applications running under Windows. A DLL can contain any number of
30152routines and variables.
30153
30154One advantage of DLLs is that you can change and enhance them without
30155forcing all the applications that depend on them to be relinked or
30156recompiled. However, you should be aware than all calls to DLL routines are
30157slower since, as you will understand below, such calls are indirect.
30158
30159To illustrate the remainder of this section, suppose that an application
30160wants to use the services of a DLL @file{API.dll}. To use the services
30161provided by @file{API.dll} you must statically link against the DLL or
30162an import library which contains a jump table with an entry for each
30163routine and variable exported by the DLL. In the Microsoft world this
30164import library is called @file{API.lib}. When using GNAT this import
30165library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30166@file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30167
30168After you have linked your application with the DLL or the import library
30169and you run your application, here is what happens:
30170
30171@enumerate
30172@item
30173Your application is loaded into memory.
30174
30175@item
30176The DLL @file{API.dll} is mapped into the address space of your
30177application. This means that:
30178
30179@itemize @bullet
30180@item
30181The DLL will use the stack of the calling thread.
30182
30183@item
30184The DLL will use the virtual address space of the calling process.
30185
30186@item
30187The DLL will allocate memory from the virtual address space of the calling
30188process.
30189
30190@item
30191Handles (pointers) can be safely exchanged between routines in the DLL
30192routines and routines in the application using the DLL.
30193@end itemize
30194
30195@item
30196The entries in the jump table (from the import library @file{libAPI.dll.a}
30197or @file{API.lib} or automatically created when linking against a DLL)
30198which is part of your application are initialized with the addresses
30199of the routines and variables in @file{API.dll}.
30200
30201@item
30202If present in @file{API.dll}, routines @code{DllMain} or
30203@code{DllMainCRTStartup} are invoked. These routines typically contain
30204the initialization code needed for the well-being of the routines and
30205variables exported by the DLL.
30206@end enumerate
30207
30208@noindent
30209There is an additional point which is worth mentioning. In the Windows
30210world there are two kind of DLLs: relocatable and non-relocatable
30211DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30212in the target application address space. If the addresses of two
30213non-relocatable DLLs overlap and these happen to be used by the same
30214application, a conflict will occur and the application will run
30215incorrectly. Hence, when possible, it is always preferable to use and
30216build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30217supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30218User's Guide) removes the debugging symbols from the DLL but the DLL can
30219still be relocated.
30220
30221As a side note, an interesting difference between Microsoft DLLs and
30222Unix shared libraries, is the fact that on most Unix systems all public
30223routines are exported by default in a Unix shared library, while under
30224Windows it is possible (but not required) to list exported routines in
30225a definition file (@pxref{The Definition File}).
30226
30227@node Using DLLs with GNAT
30228@section Using DLLs with GNAT
30229
30230@menu
30231* Creating an Ada Spec for the DLL Services::
30232* Creating an Import Library::
30233@end menu
30234
30235@noindent
30236To use the services of a DLL, say @file{API.dll}, in your Ada application
30237you must have:
30238
30239@enumerate
30240@item
30241The Ada spec for the routines and/or variables you want to access in
30242@file{API.dll}. If not available this Ada spec must be built from the C/C++
30243header files provided with the DLL.
30244
30245@item
30246The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30247mentioned an import library is a statically linked library containing the
30248import table which will be filled at load time to point to the actual
30249@file{API.dll} routines. Sometimes you don't have an import library for the
30250DLL you want to use. The following sections will explain how to build
30251one. Note that this is optional.
30252
30253@item
30254The actual DLL, @file{API.dll}.
30255@end enumerate
30256
30257@noindent
30258Once you have all the above, to compile an Ada application that uses the
30259services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30260you simply issue the command
30261
30262@smallexample
30263$ gnatmake my_ada_app -largs -lAPI
30264@end smallexample
30265
30266@noindent
30267The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30268tells the GNAT linker to look for an import library. The linker will
30269look for a library name in this specific order:
30270
30271@enumerate
30272@item @file{libAPI.dll.a}
30273@item @file{API.dll.a}
30274@item @file{libAPI.a}
30275@item @file{API.lib}
30276@item @file{libAPI.dll}
30277@item @file{API.dll}
30278@end enumerate
30279
30280The first three are the GNU style import libraries. The third is the
30281Microsoft style import libraries. The last two are the actual DLL names.
30282
30283Note that if the Ada package spec for @file{API.dll} contains the
30284following pragma
30285
30286@smallexample @c ada
30287pragma Linker_Options ("-lAPI");
30288@end smallexample
30289
30290@noindent
30291you do not have to add @option{-largs -lAPI} at the end of the
30292@command{gnatmake} command.
30293
30294If any one of the items above is missing you will have to create it
30295yourself. The following sections explain how to do so using as an
30296example a fictitious DLL called @file{API.dll}.
30297
30298@node Creating an Ada Spec for the DLL Services
30299@subsection Creating an Ada Spec for the DLL Services
30300
30301@noindent
30302A DLL typically comes with a C/C++ header file which provides the
30303definitions of the routines and variables exported by the DLL. The Ada
30304equivalent of this header file is a package spec that contains definitions
30305for the imported entities. If the DLL you intend to use does not come with
30306an Ada spec you have to generate one such spec yourself. For example if
30307the header file of @file{API.dll} is a file @file{api.h} containing the
30308following two definitions:
30309
30310@smallexample
30311@group
30312@cartouche
30313int some_var;
30314int get (char *);
30315@end cartouche
30316@end group
30317@end smallexample
30318
30319@noindent
30320then the equivalent Ada spec could be:
30321
30322@smallexample @c ada
30323@group
30324@cartouche
30325with Interfaces.C.Strings;
30326package API is
30327   use Interfaces;
30328
30329   Some_Var : C.int;
30330   function Get (Str : C.Strings.Chars_Ptr) return C.int;
30331
30332private
30333   pragma Import (C, Get);
30334   pragma Import (DLL, Some_Var);
30335end API;
30336@end cartouche
30337@end group
30338@end smallexample
30339
30340@node Creating an Import Library
30341@subsection Creating an Import Library
30342@cindex Import library
30343
30344@menu
30345* The Definition File::
30346* GNAT-Style Import Library::
30347* Microsoft-Style Import Library::
30348@end menu
30349
30350@noindent
30351If a Microsoft-style import library @file{API.lib} or a GNAT-style
30352import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30353with @file{API.dll} you can skip this section. You can also skip this
30354section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30355as in this case it is possible to link directly against the
30356DLL. Otherwise read on.
30357
30358@node The Definition File
30359@subsubsection The Definition File
30360@cindex Definition file
30361@findex .def
30362
30363@noindent
30364As previously mentioned, and unlike Unix systems, the list of symbols
30365that are exported from a DLL must be provided explicitly in Windows.
30366The main goal of a definition file is precisely that: list the symbols
30367exported by a DLL. A definition file (usually a file with a @code{.def}
30368suffix) has the following structure:
30369
30370@smallexample
30371@group
30372@cartouche
30373@r{[}LIBRARY @var{name}@r{]}
30374@r{[}DESCRIPTION @var{string}@r{]}
30375EXPORTS
30376   @var{symbol1}
30377   @var{symbol2}
30378   @dots{}
30379@end cartouche
30380@end group
30381@end smallexample
30382
30383@table @code
30384@item LIBRARY @var{name}
30385This section, which is optional, gives the name of the DLL.
30386
30387@item DESCRIPTION @var{string}
30388This section, which is optional, gives a description string that will be
30389embedded in the import library.
30390
30391@item EXPORTS
30392This section gives the list of exported symbols (procedures, functions or
30393variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30394section of @file{API.def} looks like:
30395
30396@smallexample
30397@group
30398@cartouche
30399EXPORTS
30400   some_var
30401   get
30402@end cartouche
30403@end group
30404@end smallexample
30405@end table
30406
30407@noindent
30408Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
30409(@pxref{Windows Calling Conventions}) for a Stdcall
30410calling convention function in the exported symbols list.
30411
30412@noindent
30413There can actually be other sections in a definition file, but these
30414sections are not relevant to the discussion at hand.
30415
30416@node GNAT-Style Import Library
30417@subsubsection GNAT-Style Import Library
30418
30419@noindent
30420To create a static import library from @file{API.dll} with the GNAT tools
30421you should proceed as follows:
30422
30423@enumerate
30424@item
30425Create the definition file @file{API.def} (@pxref{The Definition File}).
30426For that use the @code{dll2def} tool as follows:
30427
30428@smallexample
30429$ dll2def API.dll > API.def
30430@end smallexample
30431
30432@noindent
30433@code{dll2def} is a very simple tool: it takes as input a DLL and prints
30434to standard output the list of entry points in the DLL. Note that if
30435some routines in the DLL have the @code{Stdcall} convention
30436(@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
30437suffix then you'll have to edit @file{api.def} to add it, and specify
30438@option{-k} to @command{gnatdll} when creating the import library.
30439
30440@noindent
30441Here are some hints to find the right @code{@@}@var{nn} suffix.
30442
30443@enumerate
30444@item
30445If you have the Microsoft import library (.lib), it is possible to get
30446the right symbols by using Microsoft @code{dumpbin} tool (see the
30447corresponding Microsoft documentation for further details).
30448
30449@smallexample
30450$ dumpbin /exports api.lib
30451@end smallexample
30452
30453@item
30454If you have a message about a missing symbol at link time the compiler
30455tells you what symbol is expected. You just have to go back to the
30456definition file and add the right suffix.
30457@end enumerate
30458
30459@item
30460Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30461(@pxref{Using gnatdll}) as follows:
30462
30463@smallexample
30464$ gnatdll -e API.def -d API.dll
30465@end smallexample
30466
30467@noindent
30468@code{gnatdll} takes as input a definition file @file{API.def} and the
30469name of the DLL containing the services listed in the definition file
30470@file{API.dll}. The name of the static import library generated is
30471computed from the name of the definition file as follows: if the
30472definition file name is @var{xyz}@code{.def}, the import library name will
30473be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
30474@option{-e} could have been removed because the name of the definition
30475file (before the ``@code{.def}'' suffix) is the same as the name of the
30476DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30477@end enumerate
30478
30479@node Microsoft-Style Import Library
30480@subsubsection Microsoft-Style Import Library
30481
30482@noindent
30483With GNAT you can either use a GNAT-style or Microsoft-style import
30484library. A Microsoft import library is needed only if you plan to make an
30485Ada DLL available to applications developed with Microsoft
30486tools (@pxref{Mixed-Language Programming on Windows}).
30487
30488To create a Microsoft-style import library for @file{API.dll} you
30489should proceed as follows:
30490
30491@enumerate
30492@item
30493Create the definition file @file{API.def} from the DLL. For this use either
30494the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30495tool (see the corresponding Microsoft documentation for further details).
30496
30497@item
30498Build the actual import library using Microsoft's @code{lib} utility:
30499
30500@smallexample
30501$ lib -machine:IX86 -def:API.def -out:API.lib
30502@end smallexample
30503
30504@noindent
30505If you use the above command the definition file @file{API.def} must
30506contain a line giving the name of the DLL:
30507
30508@smallexample
30509LIBRARY      "API"
30510@end smallexample
30511
30512@noindent
30513See the Microsoft documentation for further details about the usage of
30514@code{lib}.
30515@end enumerate
30516
30517@node Building DLLs with GNAT Project files
30518@section Building DLLs with GNAT Project files
30519@cindex DLLs, building
30520
30521@noindent
30522There is nothing specific to Windows in the build process.
30523@pxref{Library Projects}.
30524
30525@noindent
30526Due to a system limitation, it is not possible under Windows to create threads
30527when inside the @code{DllMain} routine which is used for auto-initialization
30528of shared libraries, so it is not possible to have library level tasks in SALs.
30529
30530@node Building DLLs with GNAT
30531@section Building DLLs with GNAT
30532@cindex DLLs, building
30533
30534@noindent
30535This section explain how to build DLLs using the GNAT built-in DLL
30536support. With the following procedure it is straight forward to build
30537and use DLLs with GNAT.
30538
30539@enumerate
30540
30541@item building object files
30542
30543The first step is to build all objects files that are to be included
30544into the DLL. This is done by using the standard @command{gnatmake} tool.
30545
30546@item building the DLL
30547
30548To build the DLL you must use @command{gcc}'s @option{-shared} and
30549@option{-shared-libgcc} options. It is quite simple to use this method:
30550
30551@smallexample
30552$ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30553@end smallexample
30554
30555It is important to note that in this case all symbols found in the
30556object files are automatically exported. It is possible to restrict
30557the set of symbols to export by passing to @command{gcc} a definition
30558file, @pxref{The Definition File}. For example:
30559
30560@smallexample
30561$ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30562@end smallexample
30563
30564If you use a definition file you must export the elaboration procedures
30565for every package that required one. Elaboration procedures are named
30566using the package name followed by "_E".
30567
30568@item preparing DLL to be used
30569
30570For the DLL to be used by client programs the bodies must be hidden
30571from it and the .ali set with read-only attribute. This is very important
30572otherwise GNAT will recompile all packages and will not actually use
30573the code in the DLL. For example:
30574
30575@smallexample
30576$ mkdir apilib
30577$ copy *.ads *.ali api.dll apilib
30578$ attrib +R apilib\*.ali
30579@end smallexample
30580
30581@end enumerate
30582
30583At this point it is possible to use the DLL by directly linking
30584against it. Note that you must use the GNAT shared runtime when using
30585GNAT shared libraries. This is achieved by using @option{-shared} binder's
30586option.
30587
30588@smallexample
30589$ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30590@end smallexample
30591
30592@node Building DLLs with gnatdll
30593@section Building DLLs with gnatdll
30594@cindex DLLs, building
30595
30596@menu
30597* Limitations When Using Ada DLLs from Ada::
30598* Exporting Ada Entities::
30599* Ada DLLs and Elaboration::
30600* Ada DLLs and Finalization::
30601* Creating a Spec for Ada DLLs::
30602* Creating the Definition File::
30603* Using gnatdll::
30604@end menu
30605
30606@noindent
30607Note that it is preferred to use GNAT Project files
30608(@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30609DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30610
30611This section explains how to build DLLs containing Ada code using
30612@code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30613remainder of this section.
30614
30615The steps required to build an Ada DLL that is to be used by Ada as well as
30616non-Ada applications are as follows:
30617
30618@enumerate
30619@item
30620You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30621@code{Stdcall} calling convention to avoid any Ada name mangling for the
30622entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30623skip this step if you plan to use the Ada DLL only from Ada applications.
30624
30625@item
30626Your Ada code must export an initialization routine which calls the routine
30627@code{adainit} generated by @command{gnatbind} to perform the elaboration of
30628the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30629routine exported by the Ada DLL must be invoked by the clients of the DLL
30630to initialize the DLL.
30631
30632@item
30633When useful, the DLL should also export a finalization routine which calls
30634routine @code{adafinal} generated by @command{gnatbind} to perform the
30635finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30636The finalization routine exported by the Ada DLL must be invoked by the
30637clients of the DLL when the DLL services are no further needed.
30638
30639@item
30640You must provide a spec for the services exported by the Ada DLL in each
30641of the programming languages to which you plan to make the DLL available.
30642
30643@item
30644You must provide a definition file listing the exported entities
30645(@pxref{The Definition File}).
30646
30647@item
30648Finally you must use @code{gnatdll} to produce the DLL and the import
30649library (@pxref{Using gnatdll}).
30650@end enumerate
30651
30652@noindent
30653Note that a relocatable DLL stripped using the @code{strip}
30654binutils tool will not be relocatable anymore. To build a DLL without
30655debug information pass @code{-largs -s} to @code{gnatdll}. This
30656restriction does not apply to a DLL built using a Library Project.
30657@pxref{Library Projects}.
30658
30659@node Limitations When Using Ada DLLs from Ada
30660@subsection Limitations When Using Ada DLLs from Ada
30661
30662@noindent
30663When using Ada DLLs from Ada applications there is a limitation users
30664should be aware of. Because on Windows the GNAT run time is not in a DLL of
30665its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30666each Ada DLL includes the services of the GNAT run time that are necessary
30667to the Ada code inside the DLL. As a result, when an Ada program uses an
30668Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30669one in the main program.
30670
30671It is therefore not possible to exchange GNAT run-time objects between the
30672Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30673handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30674types, etc.
30675
30676It is completely safe to exchange plain elementary, array or record types,
30677Windows object handles, etc.
30678
30679@node Exporting Ada Entities
30680@subsection Exporting Ada Entities
30681@cindex Export table
30682
30683@noindent
30684Building a DLL is a way to encapsulate a set of services usable from any
30685application. As a result, the Ada entities exported by a DLL should be
30686exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30687any Ada name mangling. As an example here is an Ada package
30688@code{API}, spec and body, exporting two procedures, a function, and a
30689variable:
30690
30691@smallexample @c ada
30692@group
30693@cartouche
30694with Interfaces.C; use Interfaces;
30695package API is
30696   Count : C.int := 0;
30697   function Factorial (Val : C.int) return C.int;
30698
30699   procedure Initialize_API;
30700   procedure Finalize_API;
30701   --  Initialization & Finalization routines. More in the next section.
30702private
30703   pragma Export (C, Initialize_API);
30704   pragma Export (C, Finalize_API);
30705   pragma Export (C, Count);
30706   pragma Export (C, Factorial);
30707end API;
30708@end cartouche
30709@end group
30710@end smallexample
30711
30712@smallexample @c ada
30713@group
30714@cartouche
30715package body API is
30716   function Factorial (Val : C.int) return C.int is
30717      Fact : C.int := 1;
30718   begin
30719      Count := Count + 1;
30720      for K in 1 .. Val loop
30721         Fact := Fact * K;
30722      end loop;
30723      return Fact;
30724   end Factorial;
30725
30726   procedure Initialize_API is
30727      procedure Adainit;
30728      pragma Import (C, Adainit);
30729   begin
30730      Adainit;
30731   end Initialize_API;
30732
30733   procedure Finalize_API is
30734      procedure Adafinal;
30735      pragma Import (C, Adafinal);
30736   begin
30737      Adafinal;
30738   end Finalize_API;
30739end API;
30740@end cartouche
30741@end group
30742@end smallexample
30743
30744@noindent
30745If the Ada DLL you are building will only be used by Ada applications
30746you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30747convention. As an example, the previous package could be written as
30748follows:
30749
30750@smallexample @c ada
30751@group
30752@cartouche
30753package API is
30754   Count : Integer := 0;
30755   function Factorial (Val : Integer) return Integer;
30756
30757   procedure Initialize_API;
30758   procedure Finalize_API;
30759   --  Initialization and Finalization routines.
30760end API;
30761@end cartouche
30762@end group
30763@end smallexample
30764
30765@smallexample @c ada
30766@group
30767@cartouche
30768package body API is
30769   function Factorial (Val : Integer) return Integer is
30770      Fact : Integer := 1;
30771   begin
30772      Count := Count + 1;
30773      for K in 1 .. Val loop
30774         Fact := Fact * K;
30775      end loop;
30776      return Fact;
30777   end Factorial;
30778
30779   @dots{}
30780   --  The remainder of this package body is unchanged.
30781end API;
30782@end cartouche
30783@end group
30784@end smallexample
30785
30786@noindent
30787Note that if you do not export the Ada entities with a @code{C} or
30788@code{Stdcall} convention you will have to provide the mangled Ada names
30789in the definition file of the Ada DLL
30790(@pxref{Creating the Definition File}).
30791
30792@node Ada DLLs and Elaboration
30793@subsection Ada DLLs and Elaboration
30794@cindex DLLs and elaboration
30795
30796@noindent
30797The DLL that you are building contains your Ada code as well as all the
30798routines in the Ada library that are needed by it. The first thing a
30799user of your DLL must do is elaborate the Ada code
30800(@pxref{Elaboration Order Handling in GNAT}).
30801
30802To achieve this you must export an initialization routine
30803(@code{Initialize_API} in the previous example), which must be invoked
30804before using any of the DLL services. This elaboration routine must call
30805the Ada elaboration routine @code{adainit} generated by the GNAT binder
30806(@pxref{Binding with Non-Ada Main Programs}). See the body of
30807@code{Initialize_Api} for an example. Note that the GNAT binder is
30808automatically invoked during the DLL build process by the @code{gnatdll}
30809tool (@pxref{Using gnatdll}).
30810
30811When a DLL is loaded, Windows systematically invokes a routine called
30812@code{DllMain}. It would therefore be possible to call @code{adainit}
30813directly from @code{DllMain} without having to provide an explicit
30814initialization routine. Unfortunately, it is not possible to call
30815@code{adainit} from the @code{DllMain} if your program has library level
30816tasks because access to the @code{DllMain} entry point is serialized by
30817the system (that is, only a single thread can execute ``through'' it at a
30818time), which means that the GNAT run time will deadlock waiting for the
30819newly created task to complete its initialization.
30820
30821@node Ada DLLs and Finalization
30822@subsection Ada DLLs and Finalization
30823@cindex DLLs and finalization
30824
30825@noindent
30826When the services of an Ada DLL are no longer needed, the client code should
30827invoke the DLL finalization routine, if available. The DLL finalization
30828routine is in charge of releasing all resources acquired by the DLL. In the
30829case of the Ada code contained in the DLL, this is achieved by calling
30830routine @code{adafinal} generated by the GNAT binder
30831(@pxref{Binding with Non-Ada Main Programs}).
30832See the body of @code{Finalize_Api} for an
30833example. As already pointed out the GNAT binder is automatically invoked
30834during the DLL build process by the @code{gnatdll} tool
30835(@pxref{Using gnatdll}).
30836
30837@node Creating a Spec for Ada DLLs
30838@subsection Creating a Spec for Ada DLLs
30839
30840@noindent
30841To use the services exported by the Ada DLL from another programming
30842language (e.g.@: C), you have to translate the specs of the exported Ada
30843entities in that language. For instance in the case of @code{API.dll},
30844the corresponding C header file could look like:
30845
30846@smallexample
30847@group
30848@cartouche
30849extern int *_imp__count;
30850#define count (*_imp__count)
30851int factorial (int);
30852@end cartouche
30853@end group
30854@end smallexample
30855
30856@noindent
30857It is important to understand that when building an Ada DLL to be used by
30858other Ada applications, you need two different specs for the packages
30859contained in the DLL: one for building the DLL and the other for using
30860the DLL. This is because the @code{DLL} calling convention is needed to
30861use a variable defined in a DLL, but when building the DLL, the variable
30862must have either the @code{Ada} or @code{C} calling convention. As an
30863example consider a DLL comprising the following package @code{API}:
30864
30865@smallexample @c ada
30866@group
30867@cartouche
30868package API is
30869   Count : Integer := 0;
30870   @dots{}
30871   --  Remainder of the package omitted.
30872end API;
30873@end cartouche
30874@end group
30875@end smallexample
30876
30877@noindent
30878After producing a DLL containing package @code{API}, the spec that
30879must be used to import @code{API.Count} from Ada code outside of the
30880DLL is:
30881
30882@smallexample @c ada
30883@group
30884@cartouche
30885package API is
30886   Count : Integer;
30887   pragma Import (DLL, Count);
30888end API;
30889@end cartouche
30890@end group
30891@end smallexample
30892
30893@node Creating the Definition File
30894@subsection Creating the Definition File
30895
30896@noindent
30897The definition file is the last file needed to build the DLL. It lists
30898the exported symbols. As an example, the definition file for a DLL
30899containing only package @code{API} (where all the entities are exported
30900with a @code{C} calling convention) is:
30901
30902@smallexample
30903@group
30904@cartouche
30905EXPORTS
30906    count
30907    factorial
30908    finalize_api
30909    initialize_api
30910@end cartouche
30911@end group
30912@end smallexample
30913
30914@noindent
30915If the @code{C} calling convention is missing from package @code{API},
30916then the definition file contains the mangled Ada names of the above
30917entities, which in this case are:
30918
30919@smallexample
30920@group
30921@cartouche
30922EXPORTS
30923    api__count
30924    api__factorial
30925    api__finalize_api
30926    api__initialize_api
30927@end cartouche
30928@end group
30929@end smallexample
30930
30931@node Using gnatdll
30932@subsection Using @code{gnatdll}
30933@findex gnatdll
30934
30935@menu
30936* gnatdll Example::
30937* gnatdll behind the Scenes::
30938* Using dlltool::
30939@end menu
30940
30941@noindent
30942@code{gnatdll} is a tool to automate the DLL build process once all the Ada
30943and non-Ada sources that make up your DLL have been compiled.
30944@code{gnatdll} is actually in charge of two distinct tasks: build the
30945static import library for the DLL and the actual DLL. The form of the
30946@code{gnatdll} command is
30947
30948@smallexample
30949@cartouche
30950@c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30951@c Expanding @ovar macro inline (explanation in macro def comments)
30952$ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30953@end cartouche
30954@end smallexample
30955
30956@noindent
30957where @var{list-of-files} is a list of ALI and object files. The object
30958file list must be the exact list of objects corresponding to the non-Ada
30959sources whose services are to be included in the DLL. The ALI file list
30960must be the exact list of ALI files for the corresponding Ada sources
30961whose services are to be included in the DLL. If @var{list-of-files} is
30962missing, only the static import library is generated.
30963
30964@noindent
30965You may specify any of the following switches to @code{gnatdll}:
30966
30967@table @code
30968@c @item -a@ovar{address}
30969@c Expanding @ovar macro inline (explanation in macro def comments)
30970@item -a@r{[}@var{address}@r{]}
30971@cindex @option{-a} (@code{gnatdll})
30972Build a non-relocatable DLL at @var{address}. If @var{address} is not
30973specified the default address @var{0x11000000} will be used. By default,
30974when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30975advise the reader to build relocatable DLL.
30976
30977@item -b @var{address}
30978@cindex @option{-b} (@code{gnatdll})
30979Set the relocatable DLL base address. By default the address is
30980@code{0x11000000}.
30981
30982@item -bargs @var{opts}
30983@cindex @option{-bargs} (@code{gnatdll})
30984Binder options. Pass @var{opts} to the binder.
30985
30986@item -d @var{dllfile}
30987@cindex @option{-d} (@code{gnatdll})
30988@var{dllfile} is the name of the DLL. This switch must be present for
30989@code{gnatdll} to do anything. The name of the generated import library is
30990obtained algorithmically from @var{dllfile} as shown in the following
30991example: if @var{dllfile} is @code{xyz.dll}, the import library name is
30992@code{libxyz.dll.a}. The name of the definition file to use (if not specified
30993by option @option{-e}) is obtained algorithmically from @var{dllfile}
30994as shown in the following example:
30995if @var{dllfile} is @code{xyz.dll}, the definition
30996file used is @code{xyz.def}.
30997
30998@item -e @var{deffile}
30999@cindex @option{-e} (@code{gnatdll})
31000@var{deffile} is the name of the definition file.
31001
31002@item -g
31003@cindex @option{-g} (@code{gnatdll})
31004Generate debugging information. This information is stored in the object
31005file and copied from there to the final DLL file by the linker,
31006where it can be read by the debugger. You must use the
31007@option{-g} switch if you plan on using the debugger or the symbolic
31008stack traceback.
31009
31010@item -h
31011@cindex @option{-h} (@code{gnatdll})
31012Help mode. Displays @code{gnatdll} switch usage information.
31013
31014@item -Idir
31015@cindex @option{-I} (@code{gnatdll})
31016Direct @code{gnatdll} to search the @var{dir} directory for source and
31017object files needed to build the DLL.
31018(@pxref{Search Paths and the Run-Time Library (RTL)}).
31019
31020@item -k
31021@cindex @option{-k} (@code{gnatdll})
31022Removes the @code{@@}@var{nn} suffix from the import library's exported
31023names, but keeps them for the link names. You must specify this
31024option if you want to use a @code{Stdcall} function in a DLL for which
31025the @code{@@}@var{nn} suffix has been removed. This is the case for most
31026of the Windows NT DLL for example. This option has no effect when
31027@option{-n} option is specified.
31028
31029@item -l @var{file}
31030@cindex @option{-l} (@code{gnatdll})
31031The list of ALI and object files used to build the DLL are listed in
31032@var{file}, instead of being given in the command line. Each line in
31033@var{file} contains the name of an ALI or object file.
31034
31035@item -n
31036@cindex @option{-n} (@code{gnatdll})
31037No Import. Do not create the import library.
31038
31039@item -q
31040@cindex @option{-q} (@code{gnatdll})
31041Quiet mode. Do not display unnecessary messages.
31042
31043@item -v
31044@cindex @option{-v} (@code{gnatdll})
31045Verbose mode. Display extra information.
31046
31047@item -largs @var{opts}
31048@cindex @option{-largs} (@code{gnatdll})
31049Linker options. Pass @var{opts} to the linker.
31050@end table
31051
31052@node gnatdll Example
31053@subsubsection @code{gnatdll} Example
31054
31055@noindent
31056As an example the command to build a relocatable DLL from @file{api.adb}
31057once @file{api.adb} has been compiled and @file{api.def} created is
31058
31059@smallexample
31060$ gnatdll -d api.dll api.ali
31061@end smallexample
31062
31063@noindent
31064The above command creates two files: @file{libapi.dll.a} (the import
31065library) and @file{api.dll} (the actual DLL). If you want to create
31066only the DLL, just type:
31067
31068@smallexample
31069$ gnatdll -d api.dll -n api.ali
31070@end smallexample
31071
31072@noindent
31073Alternatively if you want to create just the import library, type:
31074
31075@smallexample
31076$ gnatdll -d api.dll
31077@end smallexample
31078
31079@node gnatdll behind the Scenes
31080@subsubsection @code{gnatdll} behind the Scenes
31081
31082@noindent
31083This section details the steps involved in creating a DLL. @code{gnatdll}
31084does these steps for you. Unless you are interested in understanding what
31085goes on behind the scenes, you should skip this section.
31086
31087We use the previous example of a DLL containing the Ada package @code{API},
31088to illustrate the steps necessary to build a DLL. The starting point is a
31089set of objects that will make up the DLL and the corresponding ALI
31090files. In the case of this example this means that @file{api.o} and
31091@file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31092the following:
31093
31094@enumerate
31095@item
31096@code{gnatdll} builds the base file (@file{api.base}). A base file gives
31097the information necessary to generate relocation information for the
31098DLL.
31099
31100@smallexample
31101@group
31102$ gnatbind -n api
31103$ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31104@end group
31105@end smallexample
31106
31107@noindent
31108In addition to the base file, the @command{gnatlink} command generates an
31109output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31110asks @command{gnatlink} to generate the routines @code{DllMain} and
31111@code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31112is loaded into memory.
31113
31114@item
31115@code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31116export table (@file{api.exp}). The export table contains the relocation
31117information in a form which can be used during the final link to ensure
31118that the Windows loader is able to place the DLL anywhere in memory.
31119
31120@smallexample
31121@group
31122$ dlltool --dllname api.dll --def api.def --base-file api.base \
31123          --output-exp api.exp
31124@end group
31125@end smallexample
31126
31127@item
31128@code{gnatdll} builds the base file using the new export table. Note that
31129@command{gnatbind} must be called once again since the binder generated file
31130has been deleted during the previous call to @command{gnatlink}.
31131
31132@smallexample
31133@group
31134$ gnatbind -n api
31135$ gnatlink api -o api.jnk api.exp -mdll
31136      -Wl,--base-file,api.base
31137@end group
31138@end smallexample
31139
31140@item
31141@code{gnatdll} builds the new export table using the new base file and
31142generates the DLL import library @file{libAPI.dll.a}.
31143
31144@smallexample
31145@group
31146$ dlltool --dllname api.dll --def api.def --base-file api.base \
31147          --output-exp api.exp --output-lib libAPI.a
31148@end group
31149@end smallexample
31150
31151@item
31152Finally @code{gnatdll} builds the relocatable DLL using the final export
31153table.
31154
31155@smallexample
31156@group
31157$ gnatbind -n api
31158$ gnatlink api api.exp -o api.dll -mdll
31159@end group
31160@end smallexample
31161@end enumerate
31162
31163@node Using dlltool
31164@subsubsection Using @code{dlltool}
31165
31166@noindent
31167@code{dlltool} is the low-level tool used by @code{gnatdll} to build
31168DLLs and static import libraries. This section summarizes the most
31169common @code{dlltool} switches. The form of the @code{dlltool} command
31170is
31171
31172@smallexample
31173@c $ dlltool @ovar{switches}
31174@c Expanding @ovar macro inline (explanation in macro def comments)
31175$ dlltool @r{[}@var{switches}@r{]}
31176@end smallexample
31177
31178@noindent
31179@code{dlltool} switches include:
31180
31181@table @option
31182@item --base-file @var{basefile}
31183@cindex @option{--base-file} (@command{dlltool})
31184Read the base file @var{basefile} generated by the linker. This switch
31185is used to create a relocatable DLL.
31186
31187@item --def @var{deffile}
31188@cindex @option{--def} (@command{dlltool})
31189Read the definition file.
31190
31191@item --dllname @var{name}
31192@cindex @option{--dllname} (@command{dlltool})
31193Gives the name of the DLL. This switch is used to embed the name of the
31194DLL in the static import library generated by @code{dlltool} with switch
31195@option{--output-lib}.
31196
31197@item -k
31198@cindex @option{-k} (@command{dlltool})
31199Kill @code{@@}@var{nn} from exported names
31200(@pxref{Windows Calling Conventions}
31201for a discussion about @code{Stdcall}-style symbols.
31202
31203@item --help
31204@cindex @option{--help} (@command{dlltool})
31205Prints the @code{dlltool} switches with a concise description.
31206
31207@item --output-exp @var{exportfile}
31208@cindex @option{--output-exp} (@command{dlltool})
31209Generate an export file @var{exportfile}. The export file contains the
31210export table (list of symbols in the DLL) and is used to create the DLL.
31211
31212@item --output-lib @var{libfile}
31213@cindex @option{--output-lib} (@command{dlltool})
31214Generate a static import library @var{libfile}.
31215
31216@item -v
31217@cindex @option{-v} (@command{dlltool})
31218Verbose mode.
31219
31220@item --as @var{assembler-name}
31221@cindex @option{--as} (@command{dlltool})
31222Use @var{assembler-name} as the assembler. The default is @code{as}.
31223@end table
31224
31225@node GNAT and Windows Resources
31226@section GNAT and Windows Resources
31227@cindex Resources, windows
31228
31229@menu
31230* Building Resources::
31231* Compiling Resources::
31232* Using Resources::
31233@end menu
31234
31235@noindent
31236Resources are an easy way to add Windows specific objects to your
31237application. The objects that can be added as resources include:
31238
31239@itemize @bullet
31240@item menus
31241
31242@item accelerators
31243
31244@item dialog boxes
31245
31246@item string tables
31247
31248@item bitmaps
31249
31250@item cursors
31251
31252@item icons
31253
31254@item fonts
31255
31256@item version information
31257@end itemize
31258
31259For example, a version information resource can be defined as follow and
31260embedded into an executable or DLL:
31261
31262A version information resource can be used to embed information into an
31263executable or a DLL. These information can be viewed using the file properties
31264from the Windows Explorer. Here is an example of a version information
31265resource:
31266
31267@smallexample
31268@group
312691 VERSIONINFO
31270FILEVERSION     1,0,0,0
31271PRODUCTVERSION  1,0,0,0
31272BEGIN
31273  BLOCK "StringFileInfo"
31274  BEGIN
31275    BLOCK "080904E4"
31276    BEGIN
31277      VALUE "CompanyName", "My Company Name"
31278      VALUE "FileDescription", "My application"
31279      VALUE "FileVersion", "1.0"
31280      VALUE "InternalName", "my_app"
31281      VALUE "LegalCopyright", "My Name"
31282      VALUE "OriginalFilename", "my_app.exe"
31283      VALUE "ProductName", "My App"
31284      VALUE "ProductVersion", "1.0"
31285    END
31286  END
31287
31288  BLOCK "VarFileInfo"
31289  BEGIN
31290    VALUE "Translation", 0x809, 1252
31291  END
31292END
31293@end group
31294@end smallexample
31295
31296The value @code{0809} (langID) is for the U.K English language and
31297@code{04E4} (charsetID), which is equal to @code{1252} decimal, for
31298multilingual.
31299
31300@noindent
31301This section explains how to build, compile and use resources. Note that this
31302section does not cover all resource objects, for a complete description see
31303the corresponding Microsoft documentation.
31304
31305@node Building Resources
31306@subsection Building Resources
31307@cindex Resources, building
31308
31309@noindent
31310A resource file is an ASCII file. By convention resource files have an
31311@file{.rc} extension.
31312The easiest way to build a resource file is to use Microsoft tools
31313such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31314@code{dlgedit.exe} to build dialogs.
31315It is always possible to build an @file{.rc} file yourself by writing a
31316resource script.
31317
31318It is not our objective to explain how to write a resource file. A
31319complete description of the resource script language can be found in the
31320Microsoft documentation.
31321
31322@node Compiling Resources
31323@subsection Compiling Resources
31324@findex rc
31325@findex windres
31326@cindex Resources, compiling
31327
31328@noindent
31329This section describes how to build a GNAT-compatible (COFF) object file
31330containing the resources. This is done using the Resource Compiler
31331@code{windres} as follows:
31332
31333@smallexample
31334$ windres -i myres.rc -o myres.o
31335@end smallexample
31336
31337@noindent
31338By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31339file. You can specify an alternate preprocessor (usually named
31340@file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31341parameter. A list of all possible options may be obtained by entering
31342the command @code{windres} @option{--help}.
31343
31344It is also possible to use the Microsoft resource compiler @code{rc.exe}
31345to produce a @file{.res} file (binary resource file). See the
31346corresponding Microsoft documentation for further details. In this case
31347you need to use @code{windres} to translate the @file{.res} file to a
31348GNAT-compatible object file as follows:
31349
31350@smallexample
31351$ windres -i myres.res -o myres.o
31352@end smallexample
31353
31354@node Using Resources
31355@subsection Using Resources
31356@cindex Resources, using
31357
31358@noindent
31359To include the resource file in your program just add the
31360GNAT-compatible object file for the resource(s) to the linker
31361arguments. With @command{gnatmake} this is done by using the @option{-largs}
31362option:
31363
31364@smallexample
31365$ gnatmake myprog -largs myres.o
31366@end smallexample
31367
31368@node Debugging a DLL
31369@section Debugging a DLL
31370@cindex DLL debugging
31371
31372@menu
31373* Program and DLL Both Built with GCC/GNAT::
31374* Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31375@end menu
31376
31377@noindent
31378Debugging a DLL is similar to debugging a standard program. But
31379we have to deal with two different executable parts: the DLL and the
31380program that uses it. We have the following four possibilities:
31381
31382@enumerate 1
31383@item
31384The program and the DLL are built with @code{GCC/GNAT}.
31385@item
31386The program is built with foreign tools and the DLL is built with
31387@code{GCC/GNAT}.
31388@item
31389The program is built with @code{GCC/GNAT} and the DLL is built with
31390foreign tools.
31391@end enumerate
31392
31393@noindent
31394In this section we address only cases one and two above.
31395There is no point in trying to debug
31396a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31397information in it. To do so you must use a debugger compatible with the
31398tools suite used to build the DLL.
31399
31400@node Program and DLL Both Built with GCC/GNAT
31401@subsection Program and DLL Both Built with GCC/GNAT
31402
31403@noindent
31404This is the simplest case. Both the DLL and the program have @code{GDB}
31405compatible debugging information. It is then possible to break anywhere in
31406the process. Let's suppose here that the main procedure is named
31407@code{ada_main} and that in the DLL there is an entry point named
31408@code{ada_dll}.
31409
31410@noindent
31411The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31412program must have been built with the debugging information (see GNAT -g
31413switch). Here are the step-by-step instructions for debugging it:
31414
31415@enumerate 1
31416@item Launch @code{GDB} on the main program.
31417
31418@smallexample
31419$ gdb -nw ada_main
31420@end smallexample
31421
31422@item Start the program and stop at the beginning of the main procedure
31423
31424@smallexample
31425(gdb) start
31426@end smallexample
31427
31428@noindent
31429This step is required to be able to set a breakpoint inside the DLL. As long
31430as the program is not run, the DLL is not loaded. This has the
31431consequence that the DLL debugging information is also not loaded, so it is not
31432possible to set a breakpoint in the DLL.
31433
31434@item Set a breakpoint inside the DLL
31435
31436@smallexample
31437(gdb) break ada_dll
31438(gdb) cont
31439@end smallexample
31440
31441@end enumerate
31442
31443@noindent
31444At this stage a breakpoint is set inside the DLL. From there on
31445you can use the standard approach to debug the whole program
31446(@pxref{Running and Debugging Ada Programs}).
31447
31448@ignore
31449@c This used to work, probably because the DLLs were non-relocatable
31450@c keep this section around until the problem is sorted out.
31451
31452To break on the @code{DllMain} routine it is not possible to follow
31453the procedure above. At the time the program stop on @code{ada_main}
31454the @code{DllMain} routine as already been called. Either you can use
31455the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31456
31457@enumerate 1
31458@item Launch @code{GDB} on the main program.
31459
31460@smallexample
31461$ gdb ada_main
31462@end smallexample
31463
31464@item Load DLL symbols
31465
31466@smallexample
31467(gdb) add-sym api.dll
31468@end smallexample
31469
31470@item Set a breakpoint inside the DLL
31471
31472@smallexample
31473(gdb) break ada_dll.adb:45
31474@end smallexample
31475
31476Note that at this point it is not possible to break using the routine symbol
31477directly as the program is not yet running. The solution is to break
31478on the proper line (break in @file{ada_dll.adb} line 45).
31479
31480@item Start the program
31481
31482@smallexample
31483(gdb) run
31484@end smallexample
31485
31486@end enumerate
31487@end ignore
31488
31489@node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31490@subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31491
31492@menu
31493* Debugging the DLL Directly::
31494* Attaching to a Running Process::
31495@end menu
31496
31497@noindent
31498In this case things are slightly more complex because it is not possible to
31499start the main program and then break at the beginning to load the DLL and the
31500associated DLL debugging information. It is not possible to break at the
31501beginning of the program because there is no @code{GDB} debugging information,
31502and therefore there is no direct way of getting initial control. This
31503section addresses this issue by describing some methods that can be used
31504to break somewhere in the DLL to debug it.
31505
31506@noindent
31507First suppose that the main procedure is named @code{main} (this is for
31508example some C code built with Microsoft Visual C) and that there is a
31509DLL named @code{test.dll} containing an Ada entry point named
31510@code{ada_dll}.
31511
31512@noindent
31513The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31514been built with debugging information (see GNAT -g option).
31515
31516@node Debugging the DLL Directly
31517@subsubsection Debugging the DLL Directly
31518
31519@enumerate 1
31520@item
31521Find out the executable starting address
31522
31523@smallexample
31524$ objdump --file-header main.exe
31525@end smallexample
31526
31527The starting address is reported on the last line. For example:
31528
31529@smallexample
31530main.exe:     file format pei-i386
31531architecture: i386, flags 0x0000010a:
31532EXEC_P, HAS_DEBUG, D_PAGED
31533start address 0x00401010
31534@end smallexample
31535
31536@item
31537Launch the debugger on the executable.
31538
31539@smallexample
31540$ gdb main.exe
31541@end smallexample
31542
31543@item
31544Set a breakpoint at the starting address, and launch the program.
31545
31546@smallexample
31547$ (gdb) break *0x00401010
31548$ (gdb) run
31549@end smallexample
31550
31551The program will stop at the given address.
31552
31553@item
31554Set a breakpoint on a DLL subroutine.
31555
31556@smallexample
31557(gdb) break ada_dll.adb:45
31558@end smallexample
31559
31560Or if you want to break using a symbol on the DLL, you need first to
31561select the Ada language (language used by the DLL).
31562
31563@smallexample
31564(gdb) set language ada
31565(gdb) break ada_dll
31566@end smallexample
31567
31568@item
31569Continue the program.
31570
31571@smallexample
31572(gdb) cont
31573@end smallexample
31574
31575@noindent
31576This will run the program until it reaches the breakpoint that has been
31577set. From that point you can use the standard way to debug a program
31578as described in (@pxref{Running and Debugging Ada Programs}).
31579
31580@end enumerate
31581
31582@noindent
31583It is also possible to debug the DLL by attaching to a running process.
31584
31585@node Attaching to a Running Process
31586@subsubsection Attaching to a Running Process
31587@cindex DLL debugging, attach to process
31588
31589@noindent
31590With @code{GDB} it is always possible to debug a running process by
31591attaching to it. It is possible to debug a DLL this way. The limitation
31592of this approach is that the DLL must run long enough to perform the
31593attach operation. It may be useful for instance to insert a time wasting
31594loop in the code of the DLL to meet this criterion.
31595
31596@enumerate 1
31597
31598@item Launch the main program @file{main.exe}.
31599
31600@smallexample
31601$ main
31602@end smallexample
31603
31604@item Use the Windows @i{Task Manager} to find the process ID. Let's say
31605that the process PID for @file{main.exe} is 208.
31606
31607@item Launch gdb.
31608
31609@smallexample
31610$ gdb
31611@end smallexample
31612
31613@item Attach to the running process to be debugged.
31614
31615@smallexample
31616(gdb) attach 208
31617@end smallexample
31618
31619@item Load the process debugging information.
31620
31621@smallexample
31622(gdb) symbol-file main.exe
31623@end smallexample
31624
31625@item Break somewhere in the DLL.
31626
31627@smallexample
31628(gdb) break ada_dll
31629@end smallexample
31630
31631@item Continue process execution.
31632
31633@smallexample
31634(gdb) cont
31635@end smallexample
31636
31637@end enumerate
31638
31639@noindent
31640This last step will resume the process execution, and stop at
31641the breakpoint we have set. From there you can use the standard
31642approach to debug a program as described in
31643(@pxref{Running and Debugging Ada Programs}).
31644
31645@node Setting Stack Size from gnatlink
31646@section Setting Stack Size from @command{gnatlink}
31647
31648@noindent
31649It is possible to specify the program stack size at link time. On modern
31650versions of Windows, starting with XP, this is mostly useful to set the size of
31651the main stack (environment task). The other task stacks are set with pragma
31652Storage_Size or with the @command{gnatbind -d} command.
31653
31654Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31655reserve size of individual tasks, the link-time stack size applies to all
31656tasks, and pragma Storage_Size has no effect.
31657In particular, Stack Overflow checks are made against this
31658link-time specified size.
31659
31660This setting can be done with
31661@command{gnatlink} using either:
31662
31663@itemize @bullet
31664
31665@item using @option{-Xlinker} linker option
31666
31667@smallexample
31668$ gnatlink hello -Xlinker --stack=0x10000,0x1000
31669@end smallexample
31670
31671This sets the stack reserve size to 0x10000 bytes and the stack commit
31672size to 0x1000 bytes.
31673
31674@item using @option{-Wl} linker option
31675
31676@smallexample
31677$ gnatlink hello -Wl,--stack=0x1000000
31678@end smallexample
31679
31680This sets the stack reserve size to 0x1000000 bytes. Note that with
31681@option{-Wl} option it is not possible to set the stack commit size
31682because the coma is a separator for this option.
31683
31684@end itemize
31685
31686@node Setting Heap Size from gnatlink
31687@section Setting Heap Size from @command{gnatlink}
31688
31689@noindent
31690Under Windows systems, it is possible to specify the program heap size from
31691@command{gnatlink} using either:
31692
31693@itemize @bullet
31694
31695@item using @option{-Xlinker} linker option
31696
31697@smallexample
31698$ gnatlink hello -Xlinker --heap=0x10000,0x1000
31699@end smallexample
31700
31701This sets the heap reserve size to 0x10000 bytes and the heap commit
31702size to 0x1000 bytes.
31703
31704@item using @option{-Wl} linker option
31705
31706@smallexample
31707$ gnatlink hello -Wl,--heap=0x1000000
31708@end smallexample
31709
31710This sets the heap reserve size to 0x1000000 bytes. Note that with
31711@option{-Wl} option it is not possible to set the heap commit size
31712because the coma is a separator for this option.
31713
31714@end itemize
31715
31716@node Mac OS Topics
31717@appendix Mac OS Topics
31718@cindex OS X
31719
31720@noindent
31721This chapter describes topics that are specific to Apple's OS X
31722platform.
31723
31724@menu
31725* Codesigning the Debugger::
31726@end menu
31727
31728@node Codesigning the Debugger
31729@section Codesigning the Debugger
31730
31731@noindent
31732The Darwin Kernel requires the debugger to have special permissions
31733before it is allowed to control other processes. These permissions
31734are granted by codesigning the GDB executable. Without these
31735permissions, the debugger will report error messages such as:
31736
31737@smallexample
31738Starting program: /x/y/foo
31739Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31740 (please check gdb is codesigned - see taskgated(8))
31741@end smallexample
31742
31743Codesigning requires a certificate.  The following procedure explains
31744how to create one:
31745
31746@itemize @bullet
31747@item Start the Keychain Access application (in
31748/Applications/Utilities/Keychain Access.app)
31749
31750@item Select the Keychain Access -> Certificate Assistant ->
31751Create a Certificate... menu
31752
31753@item Then:
31754
31755@itemize @bullet
31756@item Choose a name for the new certificate (this procedure will use
31757"gdb-cert" as an example)
31758
31759@item Set "Identity Type" to "Self Signed Root"
31760
31761@item Set "Certificate Type" to "Code Signing"
31762
31763@item Activate the "Let me override defaults" option
31764
31765@end itemize
31766
31767@item Click several times on "Continue" until the "Specify a Location
31768For The Certificate" screen appears, then set "Keychain" to "System"
31769
31770@item Click on "Continue" until the certificate is created
31771
31772@item Finally, in the view, double-click on the new certificate,
31773and set "When using this certificate" to "Always Trust"
31774
31775@item Exit the Keychain Access application and restart the computer
31776(this is unfortunately required)
31777
31778@end itemize
31779
31780Once a certificate has been created, the debugger can be codesigned
31781as follow. In a Terminal, run the following command...
31782
31783@smallexample
31784codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
31785@end smallexample
31786
31787... where "gdb-cert" should be replaced by the actual certificate
31788name chosen above, and <gnat_install_prefix> should be replaced by
31789the location where you installed GNAT.
31790
31791@c **********************************
31792@c * GNU Free Documentation License *
31793@c **********************************
31794@include fdl.texi
31795@c GNU Free Documentation License
31796
31797@node Index
31798@unnumbered Index
31799
31800@printindex cp
31801
31802@contents
31803@c Put table of contents at end, otherwise it precedes the "title page" in
31804@c the .txt version
31805@c Edit the pdf file to move the contents to the beginning, after the title
31806@c page
31807
31808@bye
31809