Fix unused warnings.
[official-gcc/graphite-test-results.git] / gcc / ada / gnat_ugn.texi
blob9e4fe98376bdd476f21de3537d4f8ae7677a97bc
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
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-2010, AdaCore                       o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
30 @c                           GNAT_UGN Style Guide
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
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
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
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.
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
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.
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.
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.
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
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}.
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
95 @ifset unw
96 @set PLATFORM
97 @end ifset
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
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.
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
124 @include gcc-common.texi
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
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
139 @sp 2
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
145 @page
146 @vskip 0pt plus 1filll
148 @insertcopying
150 @end titlepage
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
163 @noindent
164 AdaCore@*
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * The GNAT Metric Tool gnatmetric::
183 * File Name Krunching Using gnatkr::
184 * Preprocessing Using gnatprep::
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
187 @ifclear vms
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
190 @end ifclear
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties Using gnatcheck::
194 * Creating Sample Bodies Using gnatstub::
195 * Generating Ada Bindings for C and C++ headers::
196 * Other Utility Programs::
197 * Running and Debugging Ada Programs::
198 @ifclear vms
199 * Code Coverage and Profiling::
200 @end ifclear
201 @ifset vms
202 * Compatibility with HP Ada::
203 @end ifset
204 * Platform-Specific Information for the Run-Time Libraries::
205 * Example of Binder Output File::
206 * Elaboration Order Handling in GNAT::
207 * Conditional Compilation::
208 * Inline Assembler::
209 * Compatibility and Porting Guide::
210 @ifset unw
211 * Microsoft Windows Topics::
212 @end ifset
213 * GNU Free Documentation License::
214 * Index::
216  --- The Detailed Node Listing ---
218 About This Guide
220 * What This Guide Contains::
221 * What You Should Know before Reading This Guide::
222 * Related Information::
223 * Conventions::
225 Getting Started with GNAT
227 * Running GNAT::
228 * Running a Simple Ada Program::
229 * Running a Program with Multiple Units::
230 * Using the gnatmake Utility::
231 @ifset vms
232 * Editing with Emacs::
233 @end ifset
234 @ifclear vms
235 * Introduction to GPS::
236 @end ifclear
238 The GNAT Compilation Model
240 * Source Representation::
241 * Foreign Language Representation::
242 * File Naming Rules::
243 * Using Other File Names::
244 * Alternative File Naming Schemes::
245 * Generating Object Files::
246 * Source Dependencies::
247 * The Ada Library Information Files::
248 * Binding an Ada Program::
249 * Mixed Language Programming::
250 @ifclear vms
251 * Building Mixed Ada & C++ Programs::
252 * Comparison between GNAT and C/C++ Compilation Models::
253 @end ifclear
254 * Comparison between GNAT and Conventional Ada Library Models::
255 @ifset vms
256 * Placement of temporary files::
257 @end ifset
259 Foreign Language Representation
261 * Latin-1::
262 * Other 8-Bit Codes::
263 * Wide Character Encodings::
265 Compiling Ada Programs With gcc
267 * Compiling Programs::
268 * Switches for gcc::
269 * Search Paths and the Run-Time Library (RTL)::
270 * Order of Compilation Issues::
271 * Examples::
273 Switches for gcc
275 * Output and Error Message Control::
276 * Warning Message Control::
277 * Debugging and Assertion Control::
278 * Validity Checking::
279 * Style Checking::
280 * Run-Time Checks::
281 * Using gcc for Syntax Checking::
282 * Using gcc for Semantic Checking::
283 * Compiling Different Versions of Ada::
284 * Character Set Control::
285 * File Naming Control::
286 * Subprogram Inlining Control::
287 * Auxiliary Output Control::
288 * Debugging Control::
289 * Exception Handling Control::
290 * Units to Sources Mapping Files::
291 * Integrated Preprocessing::
292 @ifset vms
293 * Return Codes::
294 @end ifset
296 Binding Ada Programs With gnatbind
298 * Running gnatbind::
299 * Switches for gnatbind::
300 * Command-Line Access::
301 * Search Paths for gnatbind::
302 * Examples of gnatbind Usage::
304 Switches for gnatbind
306 * Consistency-Checking Modes::
307 * Binder Error Message Control::
308 * Elaboration Control::
309 * Output Control::
310 * Binding with Non-Ada Main Programs::
311 * Binding Programs with No Main Subprogram::
313 Linking Using gnatlink
315 * Running gnatlink::
316 * Switches for gnatlink::
318 The GNAT Make Program gnatmake
320 * Running gnatmake::
321 * Switches for gnatmake::
322 * Mode Switches for gnatmake::
323 * Notes on the Command Line::
324 * How gnatmake Works::
325 * Examples of gnatmake Usage::
327 Improving Performance
328 * Performance Considerations::
329 * Text_IO Suggestions::
330 * Reducing Size of Ada Executables with gnatelim::
331 * Reducing Size of Executables with unused subprogram/data elimination::
333 Performance Considerations
334 * Controlling Run-Time Checks::
335 * Use of Restrictions::
336 * Optimization Levels::
337 * Debugging Optimized Code::
338 * Inlining of Subprograms::
339 * Other Optimization Switches::
340 * Optimization and Strict Aliasing::
341 @ifset vms
342 * Coverage Analysis::
343 @end ifset
345 Reducing Size of Ada Executables with gnatelim
346 * About gnatelim::
347 * Running gnatelim::
348 * Processing Precompiled Libraries::
349 * Correcting the List of Eliminate Pragmas::
350 * Making Your Executables Smaller::
351 * Summary of the gnatelim Usage Cycle::
353 Reducing Size of Executables with unused subprogram/data elimination
354 * About unused subprogram/data elimination::
355 * Compilation options::
357 Renaming Files Using gnatchop
359 * Handling Files with Multiple Units::
360 * Operating gnatchop in Compilation Mode::
361 * Command Line for gnatchop::
362 * Switches for gnatchop::
363 * Examples of gnatchop Usage::
365 Configuration Pragmas
367 * Handling of Configuration Pragmas::
368 * The Configuration Pragmas Files::
370 Handling Arbitrary File Naming Conventions Using gnatname
372 * Arbitrary File Naming Conventions::
373 * Running gnatname::
374 * Switches for gnatname::
375 * Examples of gnatname Usage::
377 The Cross-Referencing Tools gnatxref and gnatfind
379 * Switches for gnatxref::
380 * Switches for gnatfind::
381 * Project Files for gnatxref and gnatfind::
382 * Regular Expressions in gnatfind and gnatxref::
383 * Examples of gnatxref Usage::
384 * Examples of gnatfind Usage::
386 The GNAT Pretty-Printer gnatpp
388 * Switches for gnatpp::
389 * Formatting Rules::
391 The GNAT Metrics Tool gnatmetric
393 * Switches for gnatmetric::
395 File Name Krunching Using gnatkr
397 * About gnatkr::
398 * Using gnatkr::
399 * Krunching Method::
400 * Examples of gnatkr Usage::
402 Preprocessing Using gnatprep
403 * Preprocessing Symbols::
404 * Using gnatprep::
405 * Switches for gnatprep::
406 * Form of Definitions File::
407 * Form of Input Text for gnatprep::
409 The GNAT Library Browser gnatls
411 * Running gnatls::
412 * Switches for gnatls::
413 * Examples of gnatls Usage::
415 Cleaning Up Using gnatclean
417 * Running gnatclean::
418 * Switches for gnatclean::
419 @c * Examples of gnatclean Usage::
421 @ifclear vms
423 GNAT and Libraries
425 * Introduction to Libraries in GNAT::
426 * General Ada Libraries::
427 * Stand-alone Ada Libraries::
428 * Rebuilding the GNAT Run-Time Library::
430 Using the GNU make Utility
432 * Using gnatmake in a Makefile::
433 * Automatically Creating a List of Directories::
434 * Generating the Command Line Switches::
435 * Overcoming Command Line Length Limits::
436 @end ifclear
438 Memory Management Issues
440 * Some Useful Memory Pools::
441 * The GNAT Debug Pool Facility::
442 @ifclear vms
443 * The gnatmem Tool::
444 @end ifclear
446 Stack Related Facilities
448 * Stack Overflow Checking::
449 * Static Stack Usage Analysis::
450 * Dynamic Stack Usage Analysis::
452 Some Useful Memory Pools
454 The GNAT Debug Pool Facility
456 @ifclear vms
457 The gnatmem Tool
459 * Running gnatmem::
460 * Switches for gnatmem::
461 * Example of gnatmem Usage::
462 @end ifclear
464 Verifying Properties Using gnatcheck
466 * Format of the Report File::
467 * General gnatcheck Switches::
468 * gnatcheck Rule Options::
469 * Adding the Results of Compiler Checks to gnatcheck Output::
470 * Project-Wide Checks::
471 * Rule exemption::
472 * Predefined Rules::
473 * Example of gnatcheck Usage::
475 Sample Bodies Using gnatstub
477 * Running gnatstub::
478 * Switches for gnatstub::
480 Other Utility Programs
482 * Using Other Utility Programs with GNAT::
483 * The External Symbol Naming Scheme of GNAT::
484 * Converting Ada Files to html with gnathtml::
486 @ifclear vms
487 Code Coverage and Profiling
489 * Code Coverage of Ada Programs using gcov::
490 * Profiling an Ada Program using gprof::
491 @end ifclear
493 Running and Debugging Ada Programs
495 * The GNAT Debugger GDB::
496 * Running GDB::
497 * Introduction to GDB Commands::
498 * Using Ada Expressions::
499 * Calling User-Defined Subprograms::
500 * Using the Next Command in a Function::
501 * Ada Exceptions::
502 * Ada Tasks::
503 * Debugging Generic Units::
504 * Remote Debugging using gdbserver::
505 * GNAT Abnormal Termination or Failure to Terminate::
506 * Naming Conventions for GNAT Source Files::
507 * Getting Internal Debugging Information::
508 * Stack Traceback::
510 @ifset vms
511 * LSE::
512 @end ifset
514 @ifset vms
515 Compatibility with HP Ada
517 * Ada Language Compatibility::
518 * Differences in the Definition of Package System::
519 * Language-Related Features::
520 * The Package STANDARD::
521 * The Package SYSTEM::
522 * Tasking and Task-Related Features::
523 * Pragmas and Pragma-Related Features::
524 * Library of Predefined Units::
525 * Bindings::
526 * Main Program Definition::
527 * Implementation-Defined Attributes::
528 * Compiler and Run-Time Interfacing::
529 * Program Compilation and Library Management::
530 * Input-Output::
531 * Implementation Limits::
532 * Tools and Utilities::
534 Language-Related Features
536 * Integer Types and Representations::
537 * Floating-Point Types and Representations::
538 * Pragmas Float_Representation and Long_Float::
539 * Fixed-Point Types and Representations::
540 * Record and Array Component Alignment::
541 * Address Clauses::
542 * Other Representation Clauses::
544 Tasking and Task-Related Features
546 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
547 * Assigning Task IDs::
548 * Task IDs and Delays::
549 * Task-Related Pragmas::
550 * Scheduling and Task Priority::
551 * The Task Stack::
552 * External Interrupts::
554 Pragmas and Pragma-Related Features
556 * Restrictions on the Pragma INLINE::
557 * Restrictions on the Pragma INTERFACE::
558 * Restrictions on the Pragma SYSTEM_NAME::
560 Library of Predefined Units
562 * Changes to DECLIB::
564 Bindings
566 * Shared Libraries and Options Files::
567 * Interfaces to C::
568 @end ifset
570 Platform-Specific Information for the Run-Time Libraries
572 * Summary of Run-Time Configurations::
573 * Specifying a Run-Time Library::
574 * Choosing the Scheduling Policy::
575 * Solaris-Specific Considerations::
576 * Linux-Specific Considerations::
577 * AIX-Specific Considerations::
578 * Irix-Specific Considerations::
579 * RTX-Specific Considerations::
580 * HP-UX-Specific Considerations::
582 Example of Binder Output File
584 Elaboration Order Handling in GNAT
586 * Elaboration Code::
587 * Checking the Elaboration Order::
588 * Controlling the Elaboration Order::
589 * Controlling Elaboration in GNAT - Internal Calls::
590 * Controlling Elaboration in GNAT - External Calls::
591 * Default Behavior in GNAT - Ensuring Safety::
592 * Treatment of Pragma Elaborate::
593 * Elaboration Issues for Library Tasks::
594 * Mixing Elaboration Models::
595 * What to Do If the Default Elaboration Behavior Fails::
596 * Elaboration for Access-to-Subprogram Values::
597 * Summary of Procedures for Elaboration Control::
598 * Other Elaboration Order Considerations::
600 Conditional Compilation
601 * Use of Boolean Constants::
602 * Debugging - A Special Case::
603 * Conditionalizing Declarations::
604 * Use of Alternative Implementations::
605 * Preprocessing::
607 Inline Assembler
609 * Basic Assembler Syntax::
610 * A Simple Example of Inline Assembler::
611 * Output Variables in Inline Assembler::
612 * Input Variables in Inline Assembler::
613 * Inlining Inline Assembler Code::
614 * Other Asm Functionality::
616 Compatibility and Porting Guide
618 * Compatibility with Ada 83::
619 * Compatibility between Ada 95 and Ada 2005::
620 * Implementation-dependent characteristics::
621 @ifclear vms
622 @c This brief section is only in the non-VMS version
623 @c The complete chapter on HP Ada issues is in the VMS version
624 * Compatibility with HP Ada 83::
625 @end ifclear
626 * Compatibility with Other Ada Systems::
627 * Representation Clauses::
628 @ifset vms
629 * Transitioning to 64-Bit GNAT for OpenVMS::
630 @end ifset
632 @ifset unw
633 Microsoft Windows Topics
635 * Using GNAT on Windows::
636 * CONSOLE and WINDOWS subsystems::
637 * Temporary Files::
638 * Mixed-Language Programming on Windows::
639 * Windows Calling Conventions::
640 * Introduction to Dynamic Link Libraries (DLLs)::
641 * Using DLLs with GNAT::
642 * Building DLLs with GNAT::
643 * GNAT and Windows Resources::
644 * Debugging a DLL::
645 * Setting Stack Size from gnatlink::
646 * Setting Heap Size from gnatlink::
647 @end ifset
649 * Index::
650 @end menu
651 @end ifnottex
653 @node About This Guide
654 @unnumbered About This Guide
656 @noindent
657 @ifset vms
658 This guide describes the use of @value{EDITION},
659 a compiler and software development toolset for the full Ada
660 programming language, implemented on OpenVMS for HP's Alpha and
661 Integrity server (I64) platforms.
662 @end ifset
663 @ifclear vms
664 This guide describes the use of @value{EDITION},
665 a compiler and software development
666 toolset for the full Ada programming language.
667 @end ifclear
668 It documents the features of the compiler and tools, and explains
669 how to use them to build Ada applications.
671 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
672 Ada 83 compatibility mode.
673 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
674 but you can override with a compiler switch
675 (@pxref{Compiling Different Versions of Ada})
676 to explicitly specify the language version.
677 Throughout this manual, references to ``Ada'' without a year suffix
678 apply to both the Ada 95 and Ada 2005 versions of the language.
681 @ifclear FSFEDITION
682 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
683 ``GNAT'' in the remainder of this document.
684 @end ifclear
689 @menu
690 * What This Guide Contains::
691 * What You Should Know before Reading This Guide::
692 * Related Information::
693 * Conventions::
694 @end menu
696 @node What This Guide Contains
697 @unnumberedsec What This Guide Contains
699 @noindent
700 This guide contains the following chapters:
701 @itemize @bullet
703 @item
704 @ref{Getting Started with GNAT}, describes how to get started compiling
705 and running Ada programs with the GNAT Ada programming environment.
706 @item
707 @ref{The GNAT Compilation Model}, describes the compilation model used
708 by GNAT.
710 @item
711 @ref{Compiling Using gcc}, describes how to compile
712 Ada programs with @command{gcc}, the Ada compiler.
714 @item
715 @ref{Binding Using gnatbind}, describes how to
716 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
717 utility.
719 @item
720 @ref{Linking Using gnatlink},
721 describes @command{gnatlink}, a
722 program that provides for linking using the GNAT run-time library to
723 construct a program. @command{gnatlink} can also incorporate foreign language
724 object units into the executable.
726 @item
727 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
728 utility that automatically determines the set of sources
729 needed by an Ada compilation unit, and executes the necessary compilations
730 binding and link.
732 @item
733 @ref{Improving Performance}, shows various techniques for making your
734 Ada program run faster or take less space.
735 It discusses the effect of the compiler's optimization switch and
736 also describes the @command{gnatelim} tool and unused subprogram/data
737 elimination.
739 @item
740 @ref{Renaming Files Using gnatchop}, describes
741 @code{gnatchop}, a utility that allows you to preprocess a file that
742 contains Ada source code, and split it into one or more new files, one
743 for each compilation unit.
745 @item
746 @ref{Configuration Pragmas}, describes the configuration pragmas
747 handled by GNAT.
749 @item
750 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
751 shows how to override the default GNAT file naming conventions,
752 either for an individual unit or globally.
754 @item
755 @ref{GNAT Project Manager}, describes how to use project files
756 to organize large projects.
758 @item
759 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
760 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
761 way to navigate through sources.
763 @item
764 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
765 version of an Ada source file with control over casing, indentation,
766 comment placement, and other elements of program presentation style.
768 @item
769 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
770 metrics for an Ada source file, such as the number of types and subprograms,
771 and assorted complexity measures.
773 @item
774 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
775 file name krunching utility, used to handle shortened
776 file names on operating systems with a limit on the length of names.
778 @item
779 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
780 preprocessor utility that allows a single source file to be used to
781 generate multiple or parameterized source files by means of macro
782 substitution.
784 @item
785 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
786 utility that displays information about compiled units, including dependences
787 on the corresponding sources files, and consistency of compilations.
789 @item
790 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
791 to delete files that are produced by the compiler, binder and linker.
793 @ifclear vms
794 @item
795 @ref{GNAT and Libraries}, describes the process of creating and using
796 Libraries with GNAT. It also describes how to recompile the GNAT run-time
797 library.
799 @item
800 @ref{Using the GNU make Utility}, describes some techniques for using
801 the GNAT toolset in Makefiles.
802 @end ifclear
804 @item
805 @ref{Memory Management Issues}, describes some useful predefined storage pools
806 and in particular the GNAT Debug Pool facility, which helps detect incorrect
807 memory references.
808 @ifclear vms
809 It also describes @command{gnatmem}, a utility that monitors dynamic
810 allocation and deallocation and helps detect ``memory leaks''.
811 @end ifclear
813 @item
814 @ref{Stack Related Facilities}, describes some useful tools associated with
815 stack checking and analysis.
817 @item
818 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
819 a utility that checks Ada code against a set of rules.
821 @item
822 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
823 a utility that generates empty but compilable bodies for library units.
825 @item
826 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
827 generate automatically Ada bindings from C and C++ headers.
829 @item
830 @ref{Other Utility Programs}, discusses several other GNAT utilities,
831 including @code{gnathtml}.
833 @ifclear vms
834 @item
835 @ref{Code Coverage and Profiling}, describes how to perform a structural
836 coverage and profile the execution of Ada programs.
837 @end ifclear
839 @item
840 @ref{Running and Debugging Ada Programs}, describes how to run and debug
841 Ada programs.
843 @ifset vms
844 @item
845 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
846 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
847 developed by Digital Equipment Corporation and currently supported by HP.}
848 for OpenVMS Alpha. This product was formerly known as DEC Ada,
849 @cindex DEC Ada
850 and for
851 historical compatibility reasons, the relevant libraries still use the
852 DEC prefix.
853 @end ifset
855 @item
856 @ref{Platform-Specific Information for the Run-Time Libraries},
857 describes the various run-time
858 libraries supported by GNAT on various platforms and explains how to
859 choose a particular library.
861 @item
862 @ref{Example of Binder Output File}, shows the source code for the binder
863 output file for a sample program.
865 @item
866 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
867 you deal with elaboration order issues.
869 @item
870 @ref{Conditional Compilation}, describes how to model conditional compilation,
871 both with Ada in general and with GNAT facilities in particular.
873 @item
874 @ref{Inline Assembler}, shows how to use the inline assembly facility
875 in an Ada program.
877 @item
878 @ref{Compatibility and Porting Guide}, contains sections on compatibility
879 of GNAT with other Ada development environments (including Ada 83 systems),
880 to assist in porting code from those environments.
882 @ifset unw
883 @item
884 @ref{Microsoft Windows Topics}, presents information relevant to the
885 Microsoft Windows platform.
886 @end ifset
887 @end itemize
889 @c *************************************************
890 @node What You Should Know before Reading This Guide
891 @c *************************************************
892 @unnumberedsec What You Should Know before Reading This Guide
894 @cindex Ada 95 Language Reference Manual
895 @cindex Ada 2005 Language Reference Manual
896 @noindent
897 This guide assumes a basic familiarity with the Ada 95 language, as
898 described in the International Standard ANSI/ISO/IEC-8652:1995, January
899 1995.
900 It does not require knowledge of the new features introduced by Ada 2005,
901 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
902 and Amendment 1).
903 Both reference manuals are included in the GNAT documentation
904 package.
906 @node Related Information
907 @unnumberedsec Related Information
909 @noindent
910 For further information about related tools, refer to the following
911 documents:
913 @itemize @bullet
914 @item
915 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
916 Reference Manual}, which contains all reference material for the GNAT
917 implementation of Ada.
919 @ifset unw
920 @item
921 @cite{Using the GNAT Programming Studio}, which describes the GPS
922 Integrated Development Environment.
924 @item
925 @cite{GNAT Programming Studio Tutorial}, which introduces the
926 main GPS features through examples.
927 @end ifset
929 @item
930 @cite{Ada 95 Reference Manual}, which contains reference
931 material for the Ada 95 programming language.
933 @item
934 @cite{Ada 2005 Reference Manual}, which contains reference
935 material for the Ada 2005 programming language.
937 @item
938 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
939 @ifset vms
940 in the GNU:[DOCS] directory,
941 @end ifset
942 for all details on the use of the GNU source-level debugger.
944 @item
945 @xref{Top,, The extensible self-documenting text editor, emacs,
946 GNU Emacs Manual},
947 @ifset vms
948 located in the GNU:[DOCS] directory if the EMACS kit is installed,
949 @end ifset
950 for full information on the extensible editor and programming
951 environment Emacs.
953 @end itemize
955 @c **************
956 @node Conventions
957 @unnumberedsec Conventions
958 @cindex Conventions
959 @cindex Typographical conventions
961 @noindent
962 Following are examples of the typographical and graphic conventions used
963 in this guide:
965 @itemize @bullet
966 @item
967 @code{Functions}, @command{utility program names}, @code{standard names},
968 and @code{classes}.
970 @item
971 @option{Option flags}
973 @item
974 @file{File names}, @samp{button names}, and @samp{field names}.
976 @item
977 @code{Variables}, @env{environment variables}, and @var{metasyntactic
978 variables}.
980 @item
981 @emph{Emphasis}.
983 @item
984 @r{[}optional information or parameters@r{]}
986 @item
987 Examples are described by text
988 @smallexample
989 and then shown this way.
990 @end smallexample
991 @end itemize
993 @noindent
994 Commands that are entered by the user are preceded in this manual by the
995 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
996 uses this sequence as a prompt, then the commands will appear exactly as
997 you see them in the manual. If your system uses some other prompt, then
998 the command will appear with the @code{$} replaced by whatever prompt
999 character you are using.
1001 @ifset unw
1002 Full file names are shown with the ``@code{/}'' character
1003 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1004 If you are using GNAT on a Windows platform, please note that
1005 the ``@code{\}'' character should be used instead.
1006 @end ifset
1008 @c ****************************
1009 @node Getting Started with GNAT
1010 @chapter Getting Started with GNAT
1012 @noindent
1013 This chapter describes some simple ways of using GNAT to build
1014 executable Ada programs.
1015 @ifset unw
1016 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1017 show how to use the command line environment.
1018 @ref{Introduction to GPS}, provides a brief
1019 introduction to the GNAT Programming Studio, a visually-oriented
1020 Integrated Development Environment for GNAT.
1021 GPS offers a graphical ``look and feel'', support for development in
1022 other programming languages, comprehensive browsing features, and
1023 many other capabilities.
1024 For information on GPS please refer to
1025 @cite{Using the GNAT Programming Studio}.
1026 @end ifset
1028 @menu
1029 * Running GNAT::
1030 * Running a Simple Ada Program::
1031 * Running a Program with Multiple Units::
1032 * Using the gnatmake Utility::
1033 @ifset vms
1034 * Editing with Emacs::
1035 @end ifset
1036 @ifclear vms
1037 * Introduction to GPS::
1038 @end ifclear
1039 @end menu
1041 @node Running GNAT
1042 @section Running GNAT
1044 @noindent
1045 Three steps are needed to create an executable file from an Ada source
1046 file:
1048 @enumerate
1049 @item
1050 The source file(s) must be compiled.
1051 @item
1052 The file(s) must be bound using the GNAT binder.
1053 @item
1054 All appropriate object files must be linked to produce an executable.
1055 @end enumerate
1057 @noindent
1058 All three steps are most commonly handled by using the @command{gnatmake}
1059 utility program that, given the name of the main program, automatically
1060 performs the necessary compilation, binding and linking steps.
1062 @node Running a Simple Ada Program
1063 @section Running a Simple Ada Program
1065 @noindent
1066 Any text editor may be used to prepare an Ada program.
1067 (If @code{Emacs} is
1068 used, the optional Ada mode may be helpful in laying out the program.)
1070 program text is a normal text file. We will assume in our initial
1071 example that you have used your editor to prepare the following
1072 standard format text file:
1074 @smallexample @c ada
1075 @cartouche
1076 with Ada.Text_IO; use Ada.Text_IO;
1077 procedure Hello is
1078 begin
1079    Put_Line ("Hello WORLD!");
1080 end Hello;
1081 @end cartouche
1082 @end smallexample
1084 @noindent
1085 This file should be named @file{hello.adb}.
1086 With the normal default file naming conventions, GNAT requires
1087 that each file
1088 contain a single compilation unit whose file name is the
1089 unit name,
1090 with periods replaced by hyphens; the
1091 extension is @file{ads} for a
1092 spec and @file{adb} for a body.
1093 You can override this default file naming convention by use of the
1094 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1095 Alternatively, if you want to rename your files according to this default
1096 convention, which is probably more convenient if you will be using GNAT
1097 for all your compilations, then the @code{gnatchop} utility
1098 can be used to generate correctly-named source files
1099 (@pxref{Renaming Files Using gnatchop}).
1101 You can compile the program using the following command (@code{$} is used
1102 as the command prompt in the examples in this document):
1104 @smallexample
1105 $ gcc -c hello.adb
1106 @end smallexample
1108 @noindent
1109 @command{gcc} is the command used to run the compiler. This compiler is
1110 capable of compiling programs in several languages, including Ada and
1111 C. It assumes that you have given it an Ada program if the file extension is
1112 either @file{.ads} or @file{.adb}, and it will then call
1113 the GNAT compiler to compile the specified file.
1115 @ifclear vms
1116 The @option{-c} switch is required. It tells @command{gcc} to only do a
1117 compilation. (For C programs, @command{gcc} can also do linking, but this
1118 capability is not used directly for Ada programs, so the @option{-c}
1119 switch must always be present.)
1120 @end ifclear
1122 This compile command generates a file
1123 @file{hello.o}, which is the object
1124 file corresponding to your Ada program. It also generates
1125 an ``Ada Library Information'' file @file{hello.ali},
1126 which contains additional information used to check
1127 that an Ada program is consistent.
1128 To build an executable file,
1129 use @code{gnatbind} to bind the program
1130 and @command{gnatlink} to link it. The
1131 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1132 @file{ALI} file, but the default extension of @file{.ali} can
1133 be omitted. This means that in the most common case, the argument
1134 is simply the name of the main program:
1136 @smallexample
1137 $ gnatbind hello
1138 $ gnatlink hello
1139 @end smallexample
1141 @noindent
1142 A simpler method of carrying out these steps is to use
1143 @command{gnatmake},
1144 a master program that invokes all the required
1145 compilation, binding and linking tools in the correct order. In particular,
1146 @command{gnatmake} automatically recompiles any sources that have been
1147 modified since they were last compiled, or sources that depend
1148 on such modified sources, so that ``version skew'' is avoided.
1149 @cindex Version skew (avoided by @command{gnatmake})
1151 @smallexample
1152 $ gnatmake hello.adb
1153 @end smallexample
1155 @noindent
1156 The result is an executable program called @file{hello}, which can be
1157 run by entering:
1159 @smallexample
1160 $ ^hello^RUN HELLO^
1161 @end smallexample
1163 @noindent
1164 assuming that the current directory is on the search path
1165 for executable programs.
1167 @noindent
1168 and, if all has gone well, you will see
1170 @smallexample
1171 Hello WORLD!
1172 @end smallexample
1174 @noindent
1175 appear in response to this command.
1177 @c ****************************************
1178 @node Running a Program with Multiple Units
1179 @section Running a Program with Multiple Units
1181 @noindent
1182 Consider a slightly more complicated example that has three files: a
1183 main program, and the spec and body of a package:
1185 @smallexample @c ada
1186 @cartouche
1187 @group
1188 package Greetings is
1189    procedure Hello;
1190    procedure Goodbye;
1191 end Greetings;
1193 with Ada.Text_IO; use Ada.Text_IO;
1194 package body Greetings is
1195    procedure Hello is
1196    begin
1197       Put_Line ("Hello WORLD!");
1198    end Hello;
1200    procedure Goodbye is
1201    begin
1202       Put_Line ("Goodbye WORLD!");
1203    end Goodbye;
1204 end Greetings;
1205 @end group
1207 @group
1208 with Greetings;
1209 procedure Gmain is
1210 begin
1211    Greetings.Hello;
1212    Greetings.Goodbye;
1213 end Gmain;
1214 @end group
1215 @end cartouche
1216 @end smallexample
1218 @noindent
1219 Following the one-unit-per-file rule, place this program in the
1220 following three separate files:
1222 @table @file
1223 @item greetings.ads
1224 spec of package @code{Greetings}
1226 @item greetings.adb
1227 body of package @code{Greetings}
1229 @item gmain.adb
1230 body of main program
1231 @end table
1233 @noindent
1234 To build an executable version of
1235 this program, we could use four separate steps to compile, bind, and link
1236 the program, as follows:
1238 @smallexample
1239 $ gcc -c gmain.adb
1240 $ gcc -c greetings.adb
1241 $ gnatbind gmain
1242 $ gnatlink gmain
1243 @end smallexample
1245 @noindent
1246 Note that there is no required order of compilation when using GNAT.
1247 In particular it is perfectly fine to compile the main program first.
1248 Also, it is not necessary to compile package specs in the case where
1249 there is an accompanying body; you only need to compile the body. If you want
1250 to submit these files to the compiler for semantic checking and not code
1251 generation, then use the
1252 @option{-gnatc} switch:
1254 @smallexample
1255 $ gcc -c greetings.ads -gnatc
1256 @end smallexample
1258 @noindent
1259 Although the compilation can be done in separate steps as in the
1260 above example, in practice it is almost always more convenient
1261 to use the @command{gnatmake} tool. All you need to know in this case
1262 is the name of the main program's source file. The effect of the above four
1263 commands can be achieved with a single one:
1265 @smallexample
1266 $ gnatmake gmain.adb
1267 @end smallexample
1269 @noindent
1270 In the next section we discuss the advantages of using @command{gnatmake} in
1271 more detail.
1273 @c *****************************
1274 @node Using the gnatmake Utility
1275 @section Using the @command{gnatmake} Utility
1277 @noindent
1278 If you work on a program by compiling single components at a time using
1279 @command{gcc}, you typically keep track of the units you modify. In order to
1280 build a consistent system, you compile not only these units, but also any
1281 units that depend on the units you have modified.
1282 For example, in the preceding case,
1283 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1284 you edit @file{greetings.ads}, you must recompile both
1285 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1286 units that depend on @file{greetings.ads}.
1288 @code{gnatbind} will warn you if you forget one of these compilation
1289 steps, so that it is impossible to generate an inconsistent program as a
1290 result of forgetting to do a compilation. Nevertheless it is tedious and
1291 error-prone to keep track of dependencies among units.
1292 One approach to handle the dependency-bookkeeping is to use a
1293 makefile. However, makefiles present maintenance problems of their own:
1294 if the dependencies change as you change the program, you must make
1295 sure that the makefile is kept up-to-date manually, which is also an
1296 error-prone process.
1298 The @command{gnatmake} utility takes care of these details automatically.
1299 Invoke it using either one of the following forms:
1301 @smallexample
1302 $ gnatmake gmain.adb
1303 $ gnatmake ^gmain^GMAIN^
1304 @end smallexample
1306 @noindent
1307 The argument is the name of the file containing the main program;
1308 you may omit the extension. @command{gnatmake}
1309 examines the environment, automatically recompiles any files that need
1310 recompiling, and binds and links the resulting set of object files,
1311 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1312 In a large program, it
1313 can be extremely helpful to use @command{gnatmake}, because working out by hand
1314 what needs to be recompiled can be difficult.
1316 Note that @command{gnatmake}
1317 takes into account all the Ada rules that
1318 establish dependencies among units. These include dependencies that result
1319 from inlining subprogram bodies, and from
1320 generic instantiation. Unlike some other
1321 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1322 found by the compiler on a previous compilation, which may possibly
1323 be wrong when sources change. @command{gnatmake} determines the exact set of
1324 dependencies from scratch each time it is run.
1326 @ifset vms
1327 @node Editing with Emacs
1328 @section Editing with Emacs
1329 @cindex Emacs
1331 @noindent
1332 Emacs is an extensible self-documenting text editor that is available in a
1333 separate VMSINSTAL kit.
1335 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1336 click on the Emacs Help menu and run the Emacs Tutorial.
1337 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1338 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1340 Documentation on Emacs and other tools is available in Emacs under the
1341 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1342 use the middle mouse button to select a topic (e.g.@: Emacs).
1344 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1345 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1346 get to the Emacs manual.
1347 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1348 prompt.
1350 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1351 which is sufficiently extensible to provide for a complete programming
1352 environment and shell for the sophisticated user.
1353 @end ifset
1355 @ifclear vms
1356 @node Introduction to GPS
1357 @section Introduction to GPS
1358 @cindex GPS (GNAT Programming Studio)
1359 @cindex GNAT Programming Studio (GPS)
1360 @noindent
1361 Although the command line interface (@command{gnatmake}, etc.) alone
1362 is sufficient, a graphical Interactive Development
1363 Environment can make it easier for you to compose, navigate, and debug
1364 programs.  This section describes the main features of GPS
1365 (``GNAT Programming Studio''), the GNAT graphical IDE.
1366 You will see how to use GPS to build and debug an executable, and
1367 you will also learn some of the basics of the GNAT ``project'' facility.
1369 GPS enables you to do much more than is presented here;
1370 e.g., you can produce a call graph, interface to a third-party
1371 Version Control System, and inspect the generated assembly language
1372 for a program.
1373 Indeed, GPS also supports languages other than Ada.
1374 Such additional information, and an explanation of all of the GPS menu
1375 items. may be found in the on-line help, which includes
1376 a user's guide and a tutorial (these are also accessible from the GNAT
1377 startup menu).
1379 @menu
1380 * Building a New Program with GPS::
1381 * Simple Debugging with GPS::
1382 @end menu
1384 @node Building a New Program with GPS
1385 @subsection Building a New Program with GPS
1386 @noindent
1387 GPS invokes the GNAT compilation tools using information
1388 contained in a @emph{project} (also known as a @emph{project file}):
1389 a collection of properties such
1390 as source directories, identities of main subprograms, tool switches, etc.,
1391 and their associated values.
1392 See @ref{GNAT Project Manager} for details.
1393 In order to run GPS, you will need to either create a new project
1394 or else open an existing one.
1396 This section will explain how you can use GPS to create a project,
1397 to associate Ada source files with a project, and to build and run
1398 programs.
1400 @enumerate
1401 @item @emph{Creating a project}
1403 Invoke GPS, either from the command line or the platform's IDE.
1404 After it starts, GPS will display a ``Welcome'' screen with three
1405 radio buttons:
1407 @itemize @bullet
1408 @item
1409 @code{Start with default project in directory}
1411 @item
1412 @code{Create new project with wizard}
1414 @item
1415 @code{Open existing project}
1416 @end itemize
1418 @noindent
1419 Select @code{Create new project with wizard} and press @code{OK}.
1420 A new window will appear.  In the text box labeled with
1421 @code{Enter the name of the project to create}, type @file{sample}
1422 as the project name.
1423 In the next box, browse to choose the directory in which you
1424 would like to create the project file.
1425 After selecting an appropriate directory, press @code{Forward}.
1427 A window will appear with the title
1428 @code{Version Control System Configuration}.
1429 Simply press @code{Forward}.
1431 A window will appear with the title
1432 @code{Please select the source directories for this project}.
1433 The directory that you specified for the project file will be selected
1434 by default as the one to use for sources; simply press @code{Forward}.
1436 A window will appear with the title
1437 @code{Please select the build directory for this project}.
1438 The directory that you specified for the project file will be selected
1439 by default for object files and executables;
1440 simply press @code{Forward}.
1442 A window will appear with the title
1443 @code{Please select the main units for this project}.
1444 You will supply this information later, after creating the source file.
1445 Simply press @code{Forward} for now.
1447 A window will appear with the title
1448 @code{Please select the switches to build the project}.
1449 Press @code{Apply}.  This will create a project file named
1450 @file{sample.prj} in the directory that you had specified.
1452 @item @emph{Creating and saving the source file}
1454 After you create the new project, a GPS window will appear, which is
1455 partitioned into two main sections:
1457 @itemize @bullet
1458 @item
1459 A @emph{Workspace area}, initially greyed out, which you will use for
1460 creating and editing source files
1462 @item
1463 Directly below, a @emph{Messages area}, which initially displays a
1464 ``Welcome'' message.
1465 (If the Messages area is not visible, drag its border upward to expand it.)
1466 @end itemize
1468 @noindent
1469 Select @code{File} on the menu bar, and then the @code{New} command.
1470 The Workspace area will become white, and you can now
1471 enter the source program explicitly.
1472 Type the following text
1474 @smallexample @c ada
1475 @group
1476 with Ada.Text_IO; use Ada.Text_IO;
1477 procedure Hello is
1478 begin
1479   Put_Line("Hello from GPS!");
1480 end Hello;
1481 @end group
1482 @end smallexample
1484 @noindent
1485 Select @code{File}, then @code{Save As}, and enter the source file name
1486 @file{hello.adb}.
1487 The file will be saved in the same directory you specified as the
1488 location of the default project file.
1490 @item @emph{Updating the project file}
1492 You need to add the new source file to the project.
1493 To do this, select
1494 the @code{Project} menu and then @code{Edit project properties}.
1495 Click the @code{Main files} tab on the left, and then the
1496 @code{Add} button.
1497 Choose @file{hello.adb} from the list, and press @code{Open}.
1498 The project settings window will reflect this action.
1499 Click @code{OK}.
1501 @item @emph{Building and running the program}
1503 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1504 and select @file{hello.adb}.
1505 The Messages window will display the resulting invocations of @command{gcc},
1506 @command{gnatbind}, and @command{gnatlink}
1507 (reflecting the default switch settings from the
1508 project file that you created) and then a ``successful compilation/build''
1509 message.
1511 To run the program, choose the @code{Build} menu, then @code{Run}, and
1512 select @command{hello}.
1513 An @emph{Arguments Selection} window will appear.
1514 There are no command line arguments, so just click @code{OK}.
1516 The Messages window will now display the program's output (the string
1517 @code{Hello from GPS}), and at the bottom of the GPS window a status
1518 update is displayed (@code{Run: hello}).
1519 Close the GPS window (or select @code{File}, then @code{Exit}) to
1520 terminate this GPS session.
1521 @end enumerate
1523 @node Simple Debugging with GPS
1524 @subsection Simple Debugging with GPS
1525 @noindent
1526 This section illustrates basic debugging techniques (setting breakpoints,
1527 examining/modifying variables, single stepping).
1529 @enumerate
1530 @item @emph{Opening a project}
1532 Start GPS and select @code{Open existing project}; browse to
1533 specify the project file @file{sample.prj} that you had created in the
1534 earlier example.
1536 @item @emph{Creating a source file}
1538 Select @code{File}, then @code{New}, and type in the following program:
1540 @smallexample @c ada
1541 @group
1542 with Ada.Text_IO; use Ada.Text_IO;
1543 procedure Example is
1544    Line : String (1..80);
1545    N    : Natural;
1546 begin
1547    Put_Line("Type a line of text at each prompt; an empty line to exit");
1548    loop
1549       Put(": ");
1550       Get_Line (Line, N);
1551       Put_Line (Line (1..N) );
1552       exit when N=0;
1553    end loop;
1554 end Example;
1555 @end group
1556 @end smallexample
1558 @noindent
1559 Select @code{File}, then @code{Save as}, and enter the file name
1560 @file{example.adb}.
1562 @item @emph{Updating the project file}
1564 Add @code{Example} as a new main unit for the project:
1565 @enumerate a
1566 @item
1567 Select @code{Project}, then @code{Edit Project Properties}.
1569 @item
1570 Select the @code{Main files} tab, click @code{Add}, then
1571 select the file @file{example.adb} from the list, and
1572 click @code{Open}.
1573 You will see the file name appear in the list of main units
1575 @item
1576 Click @code{OK}
1577 @end enumerate
1579 @item @emph{Building/running the executable}
1581 To build the executable
1582 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1584 Run the program to see its effect (in the Messages area).
1585 Each line that you enter is displayed; an empty line will
1586 cause the loop to exit and the program to terminate.
1588 @item @emph{Debugging the program}
1590 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1591 which are required for debugging, are on by default when you create
1592 a new project.
1593 Thus unless you intentionally remove these settings, you will be able
1594 to debug any program that you develop using GPS.
1596 @enumerate a
1597 @item @emph{Initializing}
1599 Select @code{Debug}, then @code{Initialize}, then @file{example}
1601 @item @emph{Setting a breakpoint}
1603 After performing the initialization step, you will observe a small
1604 icon to the right of each line number.
1605 This serves as a toggle for breakpoints; clicking the icon will
1606 set a breakpoint at the corresponding line (the icon will change to
1607 a red circle with an ``x''), and clicking it again
1608 will remove the breakpoint / reset the icon.
1610 For purposes of this example, set a breakpoint at line 10 (the
1611 statement @code{Put_Line@ (Line@ (1..N));}
1613 @item @emph{Starting program execution}
1615 Select @code{Debug}, then @code{Run}.  When the
1616 @code{Program Arguments} window appears, click @code{OK}.
1617 A console window will appear; enter some line of text,
1618 e.g.@: @code{abcde}, at the prompt.
1619 The program will pause execution when it gets to the
1620 breakpoint, and the corresponding line is highlighted.
1622 @item @emph{Examining a variable}
1624 Move the mouse over one of the occurrences of the variable @code{N}.
1625 You will see the value (5) displayed, in ``tool tip'' fashion.
1626 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1627 You will see information about @code{N} appear in the @code{Debugger Data}
1628 pane, showing the value as 5.
1630 @item @emph{Assigning a new value to a variable}
1632 Right click on the @code{N} in the @code{Debugger Data} pane, and
1633 select @code{Set value of N}.
1634 When the input window appears, enter the value @code{4} and click
1635 @code{OK}.
1636 This value does not automatically appear in the @code{Debugger Data}
1637 pane; to see it, right click again on the @code{N} in the
1638 @code{Debugger Data} pane and select @code{Update value}.
1639 The new value, 4, will appear in red.
1641 @item @emph{Single stepping}
1643 Select @code{Debug}, then @code{Next}.
1644 This will cause the next statement to be executed, in this case the
1645 call of @code{Put_Line} with the string slice.
1646 Notice in the console window that the displayed string is simply
1647 @code{abcd} and not @code{abcde} which you had entered.
1648 This is because the upper bound of the slice is now 4 rather than 5.
1650 @item @emph{Removing a breakpoint}
1652 Toggle the breakpoint icon at line 10.
1654 @item @emph{Resuming execution from a breakpoint}
1656 Select @code{Debug}, then @code{Continue}.
1657 The program will reach the next iteration of the loop, and
1658 wait for input after displaying the prompt.
1659 This time, just hit the @kbd{Enter} key.
1660 The value of @code{N} will be 0, and the program will terminate.
1661 The console window will disappear.
1662 @end enumerate
1663 @end enumerate
1664 @end ifclear
1666 @node The GNAT Compilation Model
1667 @chapter The GNAT Compilation Model
1668 @cindex GNAT compilation model
1669 @cindex Compilation model
1671 @menu
1672 * Source Representation::
1673 * Foreign Language Representation::
1674 * File Naming Rules::
1675 * Using Other File Names::
1676 * Alternative File Naming Schemes::
1677 * Generating Object Files::
1678 * Source Dependencies::
1679 * The Ada Library Information Files::
1680 * Binding an Ada Program::
1681 * Mixed Language Programming::
1682 @ifclear vms
1683 * Building Mixed Ada & C++ Programs::
1684 * Comparison between GNAT and C/C++ Compilation Models::
1685 @end ifclear
1686 * Comparison between GNAT and Conventional Ada Library Models::
1687 @ifset vms
1688 * Placement of temporary files::
1689 @end ifset
1690 @end menu
1692 @noindent
1693 This chapter describes the compilation model used by GNAT. Although
1694 similar to that used by other languages, such as C and C++, this model
1695 is substantially different from the traditional Ada compilation models,
1696 which are based on a library. The model is initially described without
1697 reference to the library-based model. If you have not previously used an
1698 Ada compiler, you need only read the first part of this chapter. The
1699 last section describes and discusses the differences between the GNAT
1700 model and the traditional Ada compiler models. If you have used other
1701 Ada compilers, this section will help you to understand those
1702 differences, and the advantages of the GNAT model.
1704 @node Source Representation
1705 @section Source Representation
1706 @cindex Latin-1
1708 @noindent
1709 Ada source programs are represented in standard text files, using
1710 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1711 7-bit ASCII set, plus additional characters used for
1712 representing foreign languages (@pxref{Foreign Language Representation}
1713 for support of non-USA character sets). The format effector characters
1714 are represented using their standard ASCII encodings, as follows:
1716 @table @code
1717 @item VT
1718 @findex VT
1719 Vertical tab, @code{16#0B#}
1721 @item HT
1722 @findex HT
1723 Horizontal tab, @code{16#09#}
1725 @item CR
1726 @findex CR
1727 Carriage return, @code{16#0D#}
1729 @item LF
1730 @findex LF
1731 Line feed, @code{16#0A#}
1733 @item FF
1734 @findex FF
1735 Form feed, @code{16#0C#}
1736 @end table
1738 @noindent
1739 Source files are in standard text file format. In addition, GNAT will
1740 recognize a wide variety of stream formats, in which the end of
1741 physical lines is marked by any of the following sequences:
1742 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1743 in accommodating files that are imported from other operating systems.
1745 @cindex End of source file
1746 @cindex Source file, end
1747 @findex SUB
1748 The end of a source file is normally represented by the physical end of
1749 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1750 recognized as signalling the end of the source file. Again, this is
1751 provided for compatibility with other operating systems where this
1752 code is used to represent the end of file.
1754 Each file contains a single Ada compilation unit, including any pragmas
1755 associated with the unit. For example, this means you must place a
1756 package declaration (a package @dfn{spec}) and the corresponding body in
1757 separate files. An Ada @dfn{compilation} (which is a sequence of
1758 compilation units) is represented using a sequence of files. Similarly,
1759 you will place each subunit or child unit in a separate file.
1761 @node Foreign Language Representation
1762 @section Foreign Language Representation
1764 @noindent
1765 GNAT supports the standard character sets defined in Ada as well as
1766 several other non-standard character sets for use in localized versions
1767 of the compiler (@pxref{Character Set Control}).
1768 @menu
1769 * Latin-1::
1770 * Other 8-Bit Codes::
1771 * Wide Character Encodings::
1772 @end menu
1774 @node Latin-1
1775 @subsection Latin-1
1776 @cindex Latin-1
1778 @noindent
1779 The basic character set is Latin-1. This character set is defined by ISO
1780 standard 8859, part 1. The lower half (character codes @code{16#00#}
1781 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1782 half is used to represent additional characters. These include extended letters
1783 used by European languages, such as French accents, the vowels with umlauts
1784 used in German, and the extra letter A-ring used in Swedish.
1786 @findex Ada.Characters.Latin_1
1787 For a complete list of Latin-1 codes and their encodings, see the source
1788 file of library unit @code{Ada.Characters.Latin_1} in file
1789 @file{a-chlat1.ads}.
1790 You may use any of these extended characters freely in character or
1791 string literals. In addition, the extended characters that represent
1792 letters can be used in identifiers.
1794 @node Other 8-Bit Codes
1795 @subsection Other 8-Bit Codes
1797 @noindent
1798 GNAT also supports several other 8-bit coding schemes:
1800 @table @asis
1801 @item ISO 8859-2 (Latin-2)
1802 @cindex Latin-2
1803 @cindex ISO 8859-2
1804 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1805 equivalence.
1807 @item ISO 8859-3 (Latin-3)
1808 @cindex Latin-3
1809 @cindex ISO 8859-3
1810 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1811 equivalence.
1813 @item ISO 8859-4 (Latin-4)
1814 @cindex Latin-4
1815 @cindex ISO 8859-4
1816 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1817 equivalence.
1819 @item ISO 8859-5 (Cyrillic)
1820 @cindex ISO 8859-5
1821 @cindex Cyrillic
1822 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1823 lowercase equivalence.
1825 @item ISO 8859-15 (Latin-9)
1826 @cindex ISO 8859-15
1827 @cindex Latin-9
1828 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1829 lowercase equivalence
1831 @item IBM PC (code page 437)
1832 @cindex code page 437
1833 This code page is the normal default for PCs in the U.S. It corresponds
1834 to the original IBM PC character set. This set has some, but not all, of
1835 the extended Latin-1 letters, but these letters do not have the same
1836 encoding as Latin-1. In this mode, these letters are allowed in
1837 identifiers with uppercase and lowercase equivalence.
1839 @item IBM PC (code page 850)
1840 @cindex code page 850
1841 This code page is a modification of 437 extended to include all the
1842 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1843 mode, all these letters are allowed in identifiers with uppercase and
1844 lowercase equivalence.
1846 @item Full Upper 8-bit
1847 Any character in the range 80-FF allowed in identifiers, and all are
1848 considered distinct. In other words, there are no uppercase and lowercase
1849 equivalences in this range. This is useful in conjunction with
1850 certain encoding schemes used for some foreign character sets (e.g.,
1851 the typical method of representing Chinese characters on the PC).
1853 @item No Upper-Half
1854 No upper-half characters in the range 80-FF are allowed in identifiers.
1855 This gives Ada 83 compatibility for identifier names.
1856 @end table
1858 @noindent
1859 For precise data on the encodings permitted, and the uppercase and lowercase
1860 equivalences that are recognized, see the file @file{csets.adb} in
1861 the GNAT compiler sources. You will need to obtain a full source release
1862 of GNAT to obtain this file.
1864 @node Wide Character Encodings
1865 @subsection Wide Character Encodings
1867 @noindent
1868 GNAT allows wide character codes to appear in character and string
1869 literals, and also optionally in identifiers, by means of the following
1870 possible encoding schemes:
1872 @table @asis
1874 @item Hex Coding
1875 In this encoding, a wide character is represented by the following five
1876 character sequence:
1878 @smallexample
1879 ESC a b c d
1880 @end smallexample
1882 @noindent
1883 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1884 characters (using uppercase letters) of the wide character code. For
1885 example, ESC A345 is used to represent the wide character with code
1886 @code{16#A345#}.
1887 This scheme is compatible with use of the full Wide_Character set.
1889 @item Upper-Half Coding
1890 @cindex Upper-Half Coding
1891 The wide character with encoding @code{16#abcd#} where the upper bit is on
1892 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1893 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1894 character, but is not required to be in the upper half. This method can
1895 be also used for shift-JIS or EUC, where the internal coding matches the
1896 external coding.
1898 @item Shift JIS Coding
1899 @cindex Shift JIS Coding
1900 A wide character is represented by a two-character sequence,
1901 @code{16#ab#} and
1902 @code{16#cd#}, with the restrictions described for upper-half encoding as
1903 described above. The internal character code is the corresponding JIS
1904 character according to the standard algorithm for Shift-JIS
1905 conversion. Only characters defined in the JIS code set table can be
1906 used with this encoding method.
1908 @item EUC Coding
1909 @cindex EUC Coding
1910 A wide character is represented by a two-character sequence
1911 @code{16#ab#} and
1912 @code{16#cd#}, with both characters being in the upper half. The internal
1913 character code is the corresponding JIS character according to the EUC
1914 encoding algorithm. Only characters defined in the JIS code set table
1915 can be used with this encoding method.
1917 @item UTF-8 Coding
1918 A wide character is represented using
1919 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1920 10646-1/Am.2. Depending on the character value, the representation
1921 is a one, two, or three byte sequence:
1922 @smallexample
1923 @iftex
1924 @leftskip=.7cm
1925 @end iftex
1926 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1927 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1928 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1930 @end smallexample
1932 @noindent
1933 where the @var{xxx} bits correspond to the left-padded bits of the
1934 16-bit character value. Note that all lower half ASCII characters
1935 are represented as ASCII bytes and all upper half characters and
1936 other wide characters are represented as sequences of upper-half
1937 (The full UTF-8 scheme allows for encoding 31-bit characters as
1938 6-byte sequences, but in this implementation, all UTF-8 sequences
1939 of four or more bytes length will be treated as illegal).
1940 @item Brackets Coding
1941 In this encoding, a wide character is represented by the following eight
1942 character sequence:
1944 @smallexample
1945 [ " a b c d " ]
1946 @end smallexample
1948 @noindent
1949 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1950 characters (using uppercase letters) of the wide character code. For
1951 example, [``A345''] is used to represent the wide character with code
1952 @code{16#A345#}. It is also possible (though not required) to use the
1953 Brackets coding for upper half characters. For example, the code
1954 @code{16#A3#} can be represented as @code{[``A3'']}.
1956 This scheme is compatible with use of the full Wide_Character set,
1957 and is also the method used for wide character encoding in the standard
1958 ACVC (Ada Compiler Validation Capability) test suite distributions.
1960 @end table
1962 @noindent
1963 Note: Some of these coding schemes do not permit the full use of the
1964 Ada character set. For example, neither Shift JIS, nor EUC allow the
1965 use of the upper half of the Latin-1 set.
1967 @node File Naming Rules
1968 @section File Naming Rules
1970 @noindent
1971 The default file name is determined by the name of the unit that the
1972 file contains. The name is formed by taking the full expanded name of
1973 the unit and replacing the separating dots with hyphens and using
1974 ^lowercase^uppercase^ for all letters.
1976 An exception arises if the file name generated by the above rules starts
1977 with one of the characters
1978 @ifset vms
1979 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1980 @end ifset
1981 @ifclear vms
1982 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1983 @end ifclear
1984 and the second character is a
1985 minus. In this case, the character ^tilde^dollar sign^ is used in place
1986 of the minus. The reason for this special rule is to avoid clashes with
1987 the standard names for child units of the packages System, Ada,
1988 Interfaces, and GNAT, which use the prefixes
1989 @ifset vms
1990 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1991 @end ifset
1992 @ifclear vms
1993 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1994 @end ifclear
1995 respectively.
1997 The file extension is @file{.ads} for a spec and
1998 @file{.adb} for a body. The following list shows some
1999 examples of these rules.
2001 @table @file
2002 @item main.ads
2003 Main (spec)
2004 @item main.adb
2005 Main (body)
2006 @item arith_functions.ads
2007 Arith_Functions (package spec)
2008 @item arith_functions.adb
2009 Arith_Functions (package body)
2010 @item func-spec.ads
2011 Func.Spec (child package spec)
2012 @item func-spec.adb
2013 Func.Spec (child package body)
2014 @item main-sub.adb
2015 Sub (subunit of Main)
2016 @item ^a~bad.adb^A$BAD.ADB^
2017 A.Bad (child package body)
2018 @end table
2020 @noindent
2021 Following these rules can result in excessively long
2022 file names if corresponding
2023 unit names are long (for example, if child units or subunits are
2024 heavily nested). An option is available to shorten such long file names
2025 (called file name ``krunching''). This may be particularly useful when
2026 programs being developed with GNAT are to be used on operating systems
2027 with limited file name lengths. @xref{Using gnatkr}.
2029 Of course, no file shortening algorithm can guarantee uniqueness over
2030 all possible unit names; if file name krunching is used, it is your
2031 responsibility to ensure no name clashes occur. Alternatively you
2032 can specify the exact file names that you want used, as described
2033 in the next section. Finally, if your Ada programs are migrating from a
2034 compiler with a different naming convention, you can use the gnatchop
2035 utility to produce source files that follow the GNAT naming conventions.
2036 (For details @pxref{Renaming Files Using gnatchop}.)
2038 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2039 systems, case is not significant. So for example on @code{Windows XP}
2040 if the canonical name is @code{main-sub.adb}, you can use the file name
2041 @code{Main-Sub.adb} instead. However, case is significant for other
2042 operating systems, so for example, if you want to use other than
2043 canonically cased file names on a Unix system, you need to follow
2044 the procedures described in the next section.
2046 @node Using Other File Names
2047 @section Using Other File Names
2048 @cindex File names
2050 @noindent
2051 In the previous section, we have described the default rules used by
2052 GNAT to determine the file name in which a given unit resides. It is
2053 often convenient to follow these default rules, and if you follow them,
2054 the compiler knows without being explicitly told where to find all
2055 the files it needs.
2057 However, in some cases, particularly when a program is imported from
2058 another Ada compiler environment, it may be more convenient for the
2059 programmer to specify which file names contain which units. GNAT allows
2060 arbitrary file names to be used by means of the Source_File_Name pragma.
2061 The form of this pragma is as shown in the following examples:
2062 @cindex Source_File_Name pragma
2064 @smallexample @c ada
2065 @cartouche
2066 pragma Source_File_Name (My_Utilities.Stacks,
2067   Spec_File_Name => "myutilst_a.ada");
2068 pragma Source_File_name (My_Utilities.Stacks,
2069   Body_File_Name => "myutilst.ada");
2070 @end cartouche
2071 @end smallexample
2073 @noindent
2074 As shown in this example, the first argument for the pragma is the unit
2075 name (in this example a child unit). The second argument has the form
2076 of a named association. The identifier
2077 indicates whether the file name is for a spec or a body;
2078 the file name itself is given by a string literal.
2080 The source file name pragma is a configuration pragma, which means that
2081 normally it will be placed in the @file{gnat.adc}
2082 file used to hold configuration
2083 pragmas that apply to a complete compilation environment.
2084 For more details on how the @file{gnat.adc} file is created and used
2085 see @ref{Handling of Configuration Pragmas}.
2086 @cindex @file{gnat.adc}
2088 @ifclear vms
2089 GNAT allows completely arbitrary file names to be specified using the
2090 source file name pragma. However, if the file name specified has an
2091 extension other than @file{.ads} or @file{.adb} it is necessary to use
2092 a special syntax when compiling the file. The name in this case must be
2093 preceded by the special sequence @option{-x} followed by a space and the name
2094 of the language, here @code{ada}, as in:
2096 @smallexample
2097 $ gcc -c -x ada peculiar_file_name.sim
2098 @end smallexample
2099 @end ifclear
2101 @noindent
2102 @command{gnatmake} handles non-standard file names in the usual manner (the
2103 non-standard file name for the main program is simply used as the
2104 argument to gnatmake). Note that if the extension is also non-standard,
2105 then it must be included in the @command{gnatmake} command, it may not
2106 be omitted.
2108 @node Alternative File Naming Schemes
2109 @section Alternative File Naming Schemes
2110 @cindex File naming schemes, alternative
2111 @cindex File names
2113 In the previous section, we described the use of the @code{Source_File_Name}
2114 pragma to allow arbitrary names to be assigned to individual source files.
2115 However, this approach requires one pragma for each file, and especially in
2116 large systems can result in very long @file{gnat.adc} files, and also create
2117 a maintenance problem.
2119 GNAT also provides a facility for specifying systematic file naming schemes
2120 other than the standard default naming scheme previously described. An
2121 alternative scheme for naming is specified by the use of
2122 @code{Source_File_Name} pragmas having the following format:
2123 @cindex Source_File_Name pragma
2125 @smallexample @c ada
2126 pragma Source_File_Name (
2127    Spec_File_Name  => FILE_NAME_PATTERN
2128  @r{[},Casing          => CASING_SPEC@r{]}
2129  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2131 pragma Source_File_Name (
2132    Body_File_Name  => FILE_NAME_PATTERN
2133  @r{[},Casing          => CASING_SPEC@r{]}
2134  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2136 pragma Source_File_Name (
2137    Subunit_File_Name  => FILE_NAME_PATTERN
2138  @r{[},Casing             => CASING_SPEC@r{]}
2139  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2141 FILE_NAME_PATTERN ::= STRING_LITERAL
2142 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2143 @end smallexample
2145 @noindent
2146 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2147 It contains a single asterisk character, and the unit name is substituted
2148 systematically for this asterisk. The optional parameter
2149 @code{Casing} indicates
2150 whether the unit name is to be all upper-case letters, all lower-case letters,
2151 or mixed-case. If no
2152 @code{Casing} parameter is used, then the default is all
2153 ^lower-case^upper-case^.
2155 The optional @code{Dot_Replacement} string is used to replace any periods
2156 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2157 argument is used then separating dots appear unchanged in the resulting
2158 file name.
2159 Although the above syntax indicates that the
2160 @code{Casing} argument must appear
2161 before the @code{Dot_Replacement} argument, but it
2162 is also permissible to write these arguments in the opposite order.
2164 As indicated, it is possible to specify different naming schemes for
2165 bodies, specs, and subunits. Quite often the rule for subunits is the
2166 same as the rule for bodies, in which case, there is no need to give
2167 a separate @code{Subunit_File_Name} rule, and in this case the
2168 @code{Body_File_name} rule is used for subunits as well.
2170 The separate rule for subunits can also be used to implement the rather
2171 unusual case of a compilation environment (e.g.@: a single directory) which
2172 contains a subunit and a child unit with the same unit name. Although
2173 both units cannot appear in the same partition, the Ada Reference Manual
2174 allows (but does not require) the possibility of the two units coexisting
2175 in the same environment.
2177 The file name translation works in the following steps:
2179 @itemize @bullet
2181 @item
2182 If there is a specific @code{Source_File_Name} pragma for the given unit,
2183 then this is always used, and any general pattern rules are ignored.
2185 @item
2186 If there is a pattern type @code{Source_File_Name} pragma that applies to
2187 the unit, then the resulting file name will be used if the file exists. If
2188 more than one pattern matches, the latest one will be tried first, and the
2189 first attempt resulting in a reference to a file that exists will be used.
2191 @item
2192 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2193 for which the corresponding file exists, then the standard GNAT default
2194 naming rules are used.
2196 @end itemize
2198 @noindent
2199 As an example of the use of this mechanism, consider a commonly used scheme
2200 in which file names are all lower case, with separating periods copied
2201 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2202 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2203 two pragmas appear:
2205 @smallexample @c ada
2206 pragma Source_File_Name
2207   (Spec_File_Name => "*.1.ada");
2208 pragma Source_File_Name
2209   (Body_File_Name => "*.2.ada");
2210 @end smallexample
2212 @noindent
2213 The default GNAT scheme is actually implemented by providing the following
2214 default pragmas internally:
2216 @smallexample @c ada
2217 pragma Source_File_Name
2218   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2219 pragma Source_File_Name
2220   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2221 @end smallexample
2223 @noindent
2224 Our final example implements a scheme typically used with one of the
2225 Ada 83 compilers, where the separator character for subunits was ``__''
2226 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2227 by adding @file{.ADA}, and subunits by
2228 adding @file{.SEP}. All file names were
2229 upper case. Child units were not present of course since this was an
2230 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2231 the same double underscore separator for child units.
2233 @smallexample @c ada
2234 pragma Source_File_Name
2235   (Spec_File_Name => "*_.ADA",
2236    Dot_Replacement => "__",
2237    Casing = Uppercase);
2238 pragma Source_File_Name
2239   (Body_File_Name => "*.ADA",
2240    Dot_Replacement => "__",
2241    Casing = Uppercase);
2242 pragma Source_File_Name
2243   (Subunit_File_Name => "*.SEP",
2244    Dot_Replacement => "__",
2245    Casing = Uppercase);
2246 @end smallexample
2248 @node Generating Object Files
2249 @section Generating Object Files
2251 @noindent
2252 An Ada program consists of a set of source files, and the first step in
2253 compiling the program is to generate the corresponding object files.
2254 These are generated by compiling a subset of these source files.
2255 The files you need to compile are the following:
2257 @itemize @bullet
2258 @item
2259 If a package spec has no body, compile the package spec to produce the
2260 object file for the package.
2262 @item
2263 If a package has both a spec and a body, compile the body to produce the
2264 object file for the package. The source file for the package spec need
2265 not be compiled in this case because there is only one object file, which
2266 contains the code for both the spec and body of the package.
2268 @item
2269 For a subprogram, compile the subprogram body to produce the object file
2270 for the subprogram. The spec, if one is present, is as usual in a
2271 separate file, and need not be compiled.
2273 @item
2274 @cindex Subunits
2275 In the case of subunits, only compile the parent unit. A single object
2276 file is generated for the entire subunit tree, which includes all the
2277 subunits.
2279 @item
2280 Compile child units independently of their parent units
2281 (though, of course, the spec of all the ancestor unit must be present in order
2282 to compile a child unit).
2284 @item
2285 @cindex Generics
2286 Compile generic units in the same manner as any other units. The object
2287 files in this case are small dummy files that contain at most the
2288 flag used for elaboration checking. This is because GNAT always handles generic
2289 instantiation by means of macro expansion. However, it is still necessary to
2290 compile generic units, for dependency checking and elaboration purposes.
2291 @end itemize
2293 @noindent
2294 The preceding rules describe the set of files that must be compiled to
2295 generate the object files for a program. Each object file has the same
2296 name as the corresponding source file, except that the extension is
2297 @file{.o} as usual.
2299 You may wish to compile other files for the purpose of checking their
2300 syntactic and semantic correctness. For example, in the case where a
2301 package has a separate spec and body, you would not normally compile the
2302 spec. However, it is convenient in practice to compile the spec to make
2303 sure it is error-free before compiling clients of this spec, because such
2304 compilations will fail if there is an error in the spec.
2306 GNAT provides an option for compiling such files purely for the
2307 purposes of checking correctness; such compilations are not required as
2308 part of the process of building a program. To compile a file in this
2309 checking mode, use the @option{-gnatc} switch.
2311 @node Source Dependencies
2312 @section Source Dependencies
2314 @noindent
2315 A given object file clearly depends on the source file which is compiled
2316 to produce it. Here we are using @dfn{depends} in the sense of a typical
2317 @code{make} utility; in other words, an object file depends on a source
2318 file if changes to the source file require the object file to be
2319 recompiled.
2320 In addition to this basic dependency, a given object may depend on
2321 additional source files as follows:
2323 @itemize @bullet
2324 @item
2325 If a file being compiled @code{with}'s a unit @var{X}, the object file
2326 depends on the file containing the spec of unit @var{X}. This includes
2327 files that are @code{with}'ed implicitly either because they are parents
2328 of @code{with}'ed child units or they are run-time units required by the
2329 language constructs used in a particular unit.
2331 @item
2332 If a file being compiled instantiates a library level generic unit, the
2333 object file depends on both the spec and body files for this generic
2334 unit.
2336 @item
2337 If a file being compiled instantiates a generic unit defined within a
2338 package, the object file depends on the body file for the package as
2339 well as the spec file.
2341 @item
2342 @findex Inline
2343 @cindex @option{-gnatn} switch
2344 If a file being compiled contains a call to a subprogram for which
2345 pragma @code{Inline} applies and inlining is activated with the
2346 @option{-gnatn} switch, the object file depends on the file containing the
2347 body of this subprogram as well as on the file containing the spec. Note
2348 that for inlining to actually occur as a result of the use of this switch,
2349 it is necessary to compile in optimizing mode.
2351 @cindex @option{-gnatN} switch
2352 The use of @option{-gnatN} activates  inlining optimization
2353 that is performed by the front end of the compiler. This inlining does
2354 not require that the code generation be optimized. Like @option{-gnatn},
2355 the use of this switch generates additional dependencies.
2357 When using a gcc-based back end (in practice this means using any version
2358 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2359 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2360 Historically front end inlining was more extensive than the gcc back end
2361 inlining, but that is no longer the case.
2363 @item
2364 If an object file @file{O} depends on the proper body of a subunit through
2365 inlining or instantiation, it depends on the parent unit of the subunit.
2366 This means that any modification of the parent unit or one of its subunits
2367 affects the compilation of @file{O}.
2369 @item
2370 The object file for a parent unit depends on all its subunit body files.
2372 @item
2373 The previous two rules meant that for purposes of computing dependencies and
2374 recompilation, a body and all its subunits are treated as an indivisible whole.
2376 @noindent
2377 These rules are applied transitively: if unit @code{A} @code{with}'s
2378 unit @code{B}, whose elaboration calls an inlined procedure in package
2379 @code{C}, the object file for unit @code{A} will depend on the body of
2380 @code{C}, in file @file{c.adb}.
2382 The set of dependent files described by these rules includes all the
2383 files on which the unit is semantically dependent, as dictated by the
2384 Ada language standard. However, it is a superset of what the
2385 standard describes, because it includes generic, inline, and subunit
2386 dependencies.
2388 An object file must be recreated by recompiling the corresponding source
2389 file if any of the source files on which it depends are modified. For
2390 example, if the @code{make} utility is used to control compilation,
2391 the rule for an Ada object file must mention all the source files on
2392 which the object file depends, according to the above definition.
2393 The determination of the necessary
2394 recompilations is done automatically when one uses @command{gnatmake}.
2395 @end itemize
2397 @node The Ada Library Information Files
2398 @section The Ada Library Information Files
2399 @cindex Ada Library Information files
2400 @cindex @file{ALI} files
2402 @noindent
2403 Each compilation actually generates two output files. The first of these
2404 is the normal object file that has a @file{.o} extension. The second is a
2405 text file containing full dependency information. It has the same
2406 name as the source file, but an @file{.ali} extension.
2407 This file is known as the Ada Library Information (@file{ALI}) file.
2408 The following information is contained in the @file{ALI} file.
2410 @itemize @bullet
2411 @item
2412 Version information (indicates which version of GNAT was used to compile
2413 the unit(s) in question)
2415 @item
2416 Main program information (including priority and time slice settings,
2417 as well as the wide character encoding used during compilation).
2419 @item
2420 List of arguments used in the @command{gcc} command for the compilation
2422 @item
2423 Attributes of the unit, including configuration pragmas used, an indication
2424 of whether the compilation was successful, exception model used etc.
2426 @item
2427 A list of relevant restrictions applying to the unit (used for consistency)
2428 checking.
2430 @item
2431 Categorization information (e.g.@: use of pragma @code{Pure}).
2433 @item
2434 Information on all @code{with}'ed units, including presence of
2435 @code{Elaborate} or @code{Elaborate_All} pragmas.
2437 @item
2438 Information from any @code{Linker_Options} pragmas used in the unit
2440 @item
2441 Information on the use of @code{Body_Version} or @code{Version}
2442 attributes in the unit.
2444 @item
2445 Dependency information. This is a list of files, together with
2446 time stamp and checksum information. These are files on which
2447 the unit depends in the sense that recompilation is required
2448 if any of these units are modified.
2450 @item
2451 Cross-reference data. Contains information on all entities referenced
2452 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2453 provide cross-reference information.
2455 @end itemize
2457 @noindent
2458 For a full detailed description of the format of the @file{ALI} file,
2459 see the source of the body of unit @code{Lib.Writ}, contained in file
2460 @file{lib-writ.adb} in the GNAT compiler sources.
2462 @node Binding an Ada Program
2463 @section Binding an Ada Program
2465 @noindent
2466 When using languages such as C and C++, once the source files have been
2467 compiled the only remaining step in building an executable program
2468 is linking the object modules together. This means that it is possible to
2469 link an inconsistent version of a program, in which two units have
2470 included different versions of the same header.
2472 The rules of Ada do not permit such an inconsistent program to be built.
2473 For example, if two clients have different versions of the same package,
2474 it is illegal to build a program containing these two clients.
2475 These rules are enforced by the GNAT binder, which also determines an
2476 elaboration order consistent with the Ada rules.
2478 The GNAT binder is run after all the object files for a program have
2479 been created. It is given the name of the main program unit, and from
2480 this it determines the set of units required by the program, by reading the
2481 corresponding ALI files. It generates error messages if the program is
2482 inconsistent or if no valid order of elaboration exists.
2484 If no errors are detected, the binder produces a main program, in Ada by
2485 default, that contains calls to the elaboration procedures of those
2486 compilation unit that require them, followed by
2487 a call to the main program. This Ada program is compiled to generate the
2488 object file for the main program. The name of
2489 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2490 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2491 main program unit.
2493 Finally, the linker is used to build the resulting executable program,
2494 using the object from the main program from the bind step as well as the
2495 object files for the Ada units of the program.
2497 @node Mixed Language Programming
2498 @section Mixed Language Programming
2499 @cindex Mixed Language Programming
2501 @noindent
2502 This section describes how to develop a mixed-language program,
2503 specifically one that comprises units in both Ada and C.
2505 @menu
2506 * Interfacing to C::
2507 * Calling Conventions::
2508 @end menu
2510 @node Interfacing to C
2511 @subsection Interfacing to C
2512 @noindent
2513 Interfacing Ada with a foreign language such as C involves using
2514 compiler directives to import and/or export entity definitions in each
2515 language---using @code{extern} statements in C, for instance, and the
2516 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2517 A full treatment of these topics is provided in Appendix B, section 1
2518 of the Ada Reference Manual.
2520 There are two ways to build a program using GNAT that contains some Ada
2521 sources and some foreign language sources, depending on whether or not
2522 the main subprogram is written in Ada.  Here is a source example with
2523 the main subprogram in Ada:
2525 @smallexample
2526 /* file1.c */
2527 #include <stdio.h>
2529 void print_num (int num)
2531   printf ("num is %d.\n", num);
2532   return;
2535 /* file2.c */
2537 /* num_from_Ada is declared in my_main.adb */
2538 extern int num_from_Ada;
2540 int get_num (void)
2542   return num_from_Ada;
2544 @end smallexample
2546 @smallexample @c ada
2547 --  my_main.adb
2548 procedure My_Main is
2550    --  Declare then export an Integer entity called num_from_Ada
2551    My_Num : Integer := 10;
2552    pragma Export (C, My_Num, "num_from_Ada");
2554    --  Declare an Ada function spec for Get_Num, then use
2555    --  C function get_num for the implementation.
2556    function Get_Num return Integer;
2557    pragma Import (C, Get_Num, "get_num");
2559    --  Declare an Ada procedure spec for Print_Num, then use
2560    --  C function print_num for the implementation.
2561    procedure Print_Num (Num : Integer);
2562    pragma Import (C, Print_Num, "print_num");
2564 begin
2565    Print_Num (Get_Num);
2566 end My_Main;
2567 @end smallexample
2569 @enumerate
2570 @item
2571 To build this example, first compile the foreign language files to
2572 generate object files:
2573 @smallexample
2574 ^gcc -c file1.c^gcc -c FILE1.C^
2575 ^gcc -c file2.c^gcc -c FILE2.C^
2576 @end smallexample
2578 @item
2579 Then, compile the Ada units to produce a set of object files and ALI
2580 files:
2581 @smallexample
2582 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2583 @end smallexample
2585 @item
2586 Run the Ada binder on the Ada main program:
2587 @smallexample
2588 gnatbind my_main.ali
2589 @end smallexample
2591 @item
2592 Link the Ada main program, the Ada objects and the other language
2593 objects:
2594 @smallexample
2595 gnatlink my_main.ali file1.o file2.o
2596 @end smallexample
2597 @end enumerate
2599 The last three steps can be grouped in a single command:
2600 @smallexample
2601 gnatmake my_main.adb -largs file1.o file2.o
2602 @end smallexample
2604 @cindex Binder output file
2605 @noindent
2606 If the main program is in a language other than Ada, then you may have
2607 more than one entry point into the Ada subsystem. You must use a special
2608 binder option to generate callable routines that initialize and
2609 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2610 Calls to the initialization and finalization routines must be inserted
2611 in the main program, or some other appropriate point in the code. The
2612 call to initialize the Ada units must occur before the first Ada
2613 subprogram is called, and the call to finalize the Ada units must occur
2614 after the last Ada subprogram returns. The binder will place the
2615 initialization and finalization subprograms into the
2616 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2617 sources.  To illustrate, we have the following example:
2619 @smallexample
2620 /* main.c */
2621 extern void adainit (void);
2622 extern void adafinal (void);
2623 extern int add (int, int);
2624 extern int sub (int, int);
2626 int main (int argc, char *argv[])
2628   int a = 21, b = 7;
2630   adainit();
2632   /* Should print "21 + 7 = 28" */
2633   printf ("%d + %d = %d\n", a, b, add (a, b));
2634   /* Should print "21 - 7 = 14" */
2635   printf ("%d - %d = %d\n", a, b, sub (a, b));
2637   adafinal();
2639 @end smallexample
2641 @smallexample @c ada
2642 --  unit1.ads
2643 package Unit1 is
2644    function Add (A, B : Integer) return Integer;
2645    pragma Export (C, Add, "add");
2646 end Unit1;
2648 --  unit1.adb
2649 package body Unit1 is
2650    function Add (A, B : Integer) return Integer is
2651    begin
2652       return A + B;
2653    end Add;
2654 end Unit1;
2656 --  unit2.ads
2657 package Unit2 is
2658    function Sub (A, B : Integer) return Integer;
2659    pragma Export (C, Sub, "sub");
2660 end Unit2;
2662 --  unit2.adb
2663 package body Unit2 is
2664    function Sub (A, B : Integer) return Integer is
2665    begin
2666       return A - B;
2667    end Sub;
2668 end Unit2;
2669 @end smallexample
2671 @enumerate
2672 @item
2673 The build procedure for this application is similar to the last
2674 example's.  First, compile the foreign language files to generate object
2675 files:
2676 @smallexample
2677 ^gcc -c main.c^gcc -c main.c^
2678 @end smallexample
2680 @item
2681 Next, compile the Ada units to produce a set of object files and ALI
2682 files:
2683 @smallexample
2684 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2685 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2686 @end smallexample
2688 @item
2689 Run the Ada binder on every generated ALI file.  Make sure to use the
2690 @option{-n} option to specify a foreign main program:
2691 @smallexample
2692 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2693 @end smallexample
2695 @item
2696 Link the Ada main program, the Ada objects and the foreign language
2697 objects. You need only list the last ALI file here:
2698 @smallexample
2699 gnatlink unit2.ali main.o -o exec_file
2700 @end smallexample
2702 This procedure yields a binary executable called @file{exec_file}.
2703 @end enumerate
2705 @noindent
2706 Depending on the circumstances (for example when your non-Ada main object
2707 does not provide symbol @code{main}), you may also need to instruct the
2708 GNAT linker not to include the standard startup objects by passing the
2709 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2711 @node Calling Conventions
2712 @subsection Calling Conventions
2713 @cindex Foreign Languages
2714 @cindex Calling Conventions
2715 GNAT follows standard calling sequence conventions and will thus interface
2716 to any other language that also follows these conventions. The following
2717 Convention identifiers are recognized by GNAT:
2719 @table @code
2720 @cindex Interfacing to Ada
2721 @cindex Other Ada compilers
2722 @cindex Convention Ada
2723 @item Ada
2724 This indicates that the standard Ada calling sequence will be
2725 used and all Ada data items may be passed without any limitations in the
2726 case where GNAT is used to generate both the caller and callee. It is also
2727 possible to mix GNAT generated code and code generated by another Ada
2728 compiler. In this case, the data types should be restricted to simple
2729 cases, including primitive types. Whether complex data types can be passed
2730 depends on the situation. Probably it is safe to pass simple arrays, such
2731 as arrays of integers or floats. Records may or may not work, depending
2732 on whether both compilers lay them out identically. Complex structures
2733 involving variant records, access parameters, tasks, or protected types,
2734 are unlikely to be able to be passed.
2736 Note that in the case of GNAT running
2737 on a platform that supports HP Ada 83, a higher degree of compatibility
2738 can be guaranteed, and in particular records are layed out in an identical
2739 manner in the two compilers. Note also that if output from two different
2740 compilers is mixed, the program is responsible for dealing with elaboration
2741 issues. Probably the safest approach is to write the main program in the
2742 version of Ada other than GNAT, so that it takes care of its own elaboration
2743 requirements, and then call the GNAT-generated adainit procedure to ensure
2744 elaboration of the GNAT components. Consult the documentation of the other
2745 Ada compiler for further details on elaboration.
2747 However, it is not possible to mix the tasking run time of GNAT and
2748 HP Ada 83, All the tasking operations must either be entirely within
2749 GNAT compiled sections of the program, or entirely within HP Ada 83
2750 compiled sections of the program.
2752 @cindex Interfacing to Assembly
2753 @cindex Convention Assembler
2754 @item Assembler
2755 Specifies assembler as the convention. In practice this has the
2756 same effect as convention Ada (but is not equivalent in the sense of being
2757 considered the same convention).
2759 @cindex Convention Asm
2760 @findex Asm
2761 @item Asm
2762 Equivalent to Assembler.
2764 @cindex Interfacing to COBOL
2765 @cindex Convention COBOL
2766 @findex COBOL
2767 @item COBOL
2768 Data will be passed according to the conventions described
2769 in section B.4 of the Ada Reference Manual.
2771 @findex C
2772 @cindex Interfacing to C
2773 @cindex Convention C
2774 @item C
2775 Data will be passed according to the conventions described
2776 in section B.3 of the Ada Reference Manual.
2778 A note on interfacing to a C ``varargs'' function:
2779 @findex C varargs function
2780 @cindex Interfacing to C varargs function
2781 @cindex varargs function interfaces
2783 @itemize @bullet
2784 @item
2785 In C, @code{varargs} allows a function to take a variable number of
2786 arguments. There is no direct equivalent in this to Ada. One
2787 approach that can be used is to create a C wrapper for each
2788 different profile and then interface to this C wrapper. For
2789 example, to print an @code{int} value using @code{printf},
2790 create a C function @code{printfi} that takes two arguments, a
2791 pointer to a string and an int, and calls @code{printf}.
2792 Then in the Ada program, use pragma @code{Import} to
2793 interface to @code{printfi}.
2795 @item
2796 It may work on some platforms to directly interface to
2797 a @code{varargs} function by providing a specific Ada profile
2798 for a particular call. However, this does not work on
2799 all platforms, since there is no guarantee that the
2800 calling sequence for a two argument normal C function
2801 is the same as for calling a @code{varargs} C function with
2802 the same two arguments.
2803 @end itemize
2805 @cindex Convention Default
2806 @findex Default
2807 @item Default
2808 Equivalent to C.
2810 @cindex Convention External
2811 @findex External
2812 @item External
2813 Equivalent to C.
2815 @ifclear vms
2816 @findex C++
2817 @cindex Interfacing to C++
2818 @cindex Convention C++
2819 @item C_Plus_Plus (or CPP)
2820 This stands for C++. For most purposes this is identical to C.
2821 See the separate description of the specialized GNAT pragmas relating to
2822 C++ interfacing for further details.
2823 @end ifclear
2825 @findex Fortran
2826 @cindex Interfacing to Fortran
2827 @cindex Convention Fortran
2828 @item Fortran
2829 Data will be passed according to the conventions described
2830 in section B.5 of the Ada Reference Manual.
2832 @item Intrinsic
2833 This applies to an intrinsic operation, as defined in the Ada
2834 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2835 this means that the body of the subprogram is provided by the compiler itself,
2836 usually by means of an efficient code sequence, and that the user does not
2837 supply an explicit body for it. In an application program, the pragma may
2838 be applied to the following sets of names:
2840 @itemize @bullet
2841 @item
2842 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2843 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2844 two formal parameters. The
2845 first one must be a signed integer type or a modular type with a binary
2846 modulus, and the second parameter must be of type Natural.
2847 The return type must be the same as the type of the first argument. The size
2848 of this type can only be 8, 16, 32, or 64.
2850 @item
2851 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2852 The corresponding operator declaration must have parameters and result type
2853 that have the same root numeric type (for example, all three are long_float
2854 types). This simplifies the definition of operations that use type checking
2855 to perform dimensional checks:
2857 @smallexample @c ada
2858 type Distance is new Long_Float;
2859 type Time     is new Long_Float;
2860 type Velocity is new Long_Float;
2861 function "/" (D : Distance; T : Time)
2862   return Velocity;
2863 pragma Import (Intrinsic, "/");
2864 @end smallexample
2866 @noindent
2867 This common idiom is often programmed with a generic definition and an
2868 explicit body. The pragma makes it simpler to introduce such declarations.
2869 It incurs no overhead in compilation time or code size, because it is
2870 implemented as a single machine instruction.
2872 @item
2873 General subprogram entities, to bind an Ada subprogram declaration to
2874 a compiler builtin by name with back-ends where such interfaces are
2875 available. A typical example is the set of ``__builtin'' functions
2876 exposed by the GCC back-end, as in the following example:
2878 @smallexample @c ada
2879    function builtin_sqrt (F : Float) return Float;
2880    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2881 @end smallexample
2883 Most of the GCC builtins are accessible this way, and as for other
2884 import conventions (e.g. C), it is the user's responsibility to ensure
2885 that the Ada subprogram profile matches the underlying builtin
2886 expectations.
2887 @end itemize
2889 @noindent
2891 @ifset unw
2892 @findex Stdcall
2893 @cindex Convention Stdcall
2894 @item Stdcall
2895 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2896 and specifies that the @code{Stdcall} calling sequence will be used,
2897 as defined by the NT API. Nevertheless, to ease building
2898 cross-platform bindings this convention will be handled as a @code{C} calling
2899 convention on non-Windows platforms.
2901 @findex DLL
2902 @cindex Convention DLL
2903 @item DLL
2904 This is equivalent to @code{Stdcall}.
2906 @findex Win32
2907 @cindex Convention Win32
2908 @item Win32
2909 This is equivalent to @code{Stdcall}.
2910 @end ifset
2912 @findex Stubbed
2913 @cindex Convention Stubbed
2914 @item Stubbed
2915 This is a special convention that indicates that the compiler
2916 should provide a stub body that raises @code{Program_Error}.
2917 @end table
2919 @noindent
2920 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2921 that can be used to parameterize conventions and allow additional synonyms
2922 to be specified. For example if you have legacy code in which the convention
2923 identifier Fortran77 was used for Fortran, you can use the configuration
2924 pragma:
2926 @smallexample @c ada
2927 pragma Convention_Identifier (Fortran77, Fortran);
2928 @end smallexample
2930 @noindent
2931 And from now on the identifier Fortran77 may be used as a convention
2932 identifier (for example in an @code{Import} pragma) with the same
2933 meaning as Fortran.
2935 @ifclear vms
2936 @node Building Mixed Ada & C++ Programs
2937 @section Building Mixed Ada and C++ Programs
2939 @noindent
2940 A programmer inexperienced with mixed-language development may find that
2941 building an application containing both Ada and C++ code can be a
2942 challenge.  This section gives a few
2943 hints that should make this task easier. The first section addresses
2944 the differences between interfacing with C and interfacing with C++.
2945 The second section
2946 looks into the delicate problem of linking the complete application from
2947 its Ada and C++ parts. The last section gives some hints on how the GNAT
2948 run-time library can be adapted in order to allow inter-language dispatching
2949 with a new C++ compiler.
2951 @menu
2952 * Interfacing to C++::
2953 * Linking a Mixed C++ & Ada Program::
2954 * A Simple Example::
2955 * Interfacing with C++ constructors::
2956 * Interfacing with C++ at the Class Level::
2957 @end menu
2959 @node Interfacing to C++
2960 @subsection Interfacing to C++
2962 @noindent
2963 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2964 generating code that is compatible with the G++ Application Binary
2965 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2967 @noindent
2968 Interfacing can be done at 3 levels: simple data, subprograms, and
2969 classes. In the first two cases, GNAT offers a specific @code{Convention
2970 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2971 Usually, C++ mangles the names of subprograms. To generate proper mangled
2972 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2973 This problem can also be addressed manually in two ways:
2975 @itemize @bullet
2976 @item
2977 by modifying the C++ code in order to force a C convention using
2978 the @code{extern "C"} syntax.
2980 @item
2981 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2982 Link_Name argument of the pragma import.
2983 @end itemize
2985 @noindent
2986 Interfacing at the class level can be achieved by using the GNAT specific
2987 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2988 gnat_rm, GNAT Reference Manual}, for additional information.
2990 @node Linking a Mixed C++ & Ada Program
2991 @subsection Linking a Mixed C++ & Ada Program
2993 @noindent
2994 Usually the linker of the C++ development system must be used to link
2995 mixed applications because most C++ systems will resolve elaboration
2996 issues (such as calling constructors on global class instances)
2997 transparently during the link phase. GNAT has been adapted to ease the
2998 use of a foreign linker for the last phase. Three cases can be
2999 considered:
3000 @enumerate
3002 @item
3003 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3004 The C++ linker can simply be called by using the C++ specific driver
3005 called @code{g++}.
3007 Note that if the C++ code uses inline functions, you will need to
3008 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3009 order to provide an existing function implementation that the Ada code can
3010 link with.
3012 @smallexample
3013 $ g++ -c -fkeep-inline-functions file1.C
3014 $ g++ -c -fkeep-inline-functions file2.C
3015 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3016 @end smallexample
3018 @item
3019 Using GNAT and G++ from two different GCC installations: If both
3020 compilers are on the @env{PATH}, the previous method may be used. It is
3021 important to note that environment variables such as
3022 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3023 @env{GCC_ROOT} will affect both compilers
3024 at the same time and may make one of the two compilers operate
3025 improperly if set during invocation of the wrong compiler.  It is also
3026 very important that the linker uses the proper @file{libgcc.a} GCC
3027 library -- that is, the one from the C++ compiler installation. The
3028 implicit link command as suggested in the @command{gnatmake} command
3029 from the former example can be replaced by an explicit link command with
3030 the full-verbosity option in order to verify which library is used:
3031 @smallexample
3032 $ gnatbind ada_unit
3033 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3034 @end smallexample
3035 If there is a problem due to interfering environment variables, it can
3036 be worked around by using an intermediate script. The following example
3037 shows the proper script to use when GNAT has not been installed at its
3038 default location and g++ has been installed at its default location:
3040 @smallexample
3041 $ cat ./my_script
3042 #!/bin/sh
3043 unset BINUTILS_ROOT
3044 unset GCC_ROOT
3045 c++ $*
3046 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3047 @end smallexample
3049 @item
3050 Using a non-GNU C++ compiler: The commands previously described can be
3051 used to insure that the C++ linker is used. Nonetheless, you need to add
3052 a few more parameters to the link command line, depending on the exception
3053 mechanism used.
3055 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3056 to the libgcc libraries are required:
3058 @smallexample
3059 $ cat ./my_script
3060 #!/bin/sh
3061 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3062 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3063 @end smallexample
3065 Where CC is the name of the non-GNU C++ compiler.
3067 If the @code{zero cost} exception mechanism is used, and the platform
3068 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3069 paths to more objects are required:
3071 @smallexample
3072 $ cat ./my_script
3073 #!/bin/sh
3074 CC `gcc -print-file-name=crtbegin.o` $* \
3075 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3076 `gcc -print-file-name=crtend.o`
3077 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3078 @end smallexample
3080 If the @code{zero cost} exception mechanism is used, and the platform
3081 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3082 Tru64 or AIX), the simple approach described above will not work and
3083 a pre-linking phase using GNAT will be necessary.
3085 @end enumerate
3087 Another alternative is to use the @command{gprbuild} multi-language builder
3088 which has a large knowledge base and knows how to link Ada and C++ code
3089 together automatically in most cases.
3091 @node A Simple Example
3092 @subsection  A Simple Example
3093 @noindent
3094 The following example, provided as part of the GNAT examples, shows how
3095 to achieve procedural interfacing between Ada and C++ in both
3096 directions. The C++ class A has two methods. The first method is exported
3097 to Ada by the means of an extern C wrapper function. The second method
3098 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3099 a limited record with a layout comparable to the C++ class. The Ada
3100 subprogram, in turn, calls the C++ method. So, starting from the C++
3101 main program, the process passes back and forth between the two
3102 languages.
3104 @noindent
3105 Here are the compilation commands:
3106 @smallexample
3107 $ gnatmake -c simple_cpp_interface
3108 $ g++ -c cpp_main.C
3109 $ g++ -c ex7.C
3110 $ gnatbind -n simple_cpp_interface
3111 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3112       -lstdc++ ex7.o cpp_main.o
3113 @end smallexample
3115 @noindent
3116 Here are the corresponding sources:
3117 @smallexample
3119 //cpp_main.C
3121 #include "ex7.h"
3123 extern "C" @{
3124   void adainit (void);
3125   void adafinal (void);
3126   void method1 (A *t);
3129 void method1 (A *t)
3131   t->method1 ();
3134 int main ()
3136   A obj;
3137   adainit ();
3138   obj.method2 (3030);
3139   adafinal ();
3142 //ex7.h
3144 class Origin @{
3145  public:
3146   int o_value;
3148 class A : public Origin @{
3149  public:
3150   void method1 (void);
3151   void method2 (int v);
3152   A();
3153   int   a_value;
3156 //ex7.C
3158 #include "ex7.h"
3159 #include <stdio.h>
3161 extern "C" @{ void ada_method2 (A *t, int v);@}
3163 void A::method1 (void)
3165   a_value = 2020;
3166   printf ("in A::method1, a_value = %d \n",a_value);
3170 void A::method2 (int v)
3172    ada_method2 (this, v);
3173    printf ("in A::method2, a_value = %d \n",a_value);
3177 A::A(void)
3179    a_value = 1010;
3180   printf ("in A::A, a_value = %d \n",a_value);
3182 @end smallexample
3184 @smallexample @c ada
3185 -- Ada sources
3186 package body Simple_Cpp_Interface is
3188    procedure Ada_Method2 (This : in out A; V : Integer) is
3189    begin
3190       Method1 (This);
3191       This.A_Value := V;
3192    end Ada_Method2;
3194 end Simple_Cpp_Interface;
3196 with System;
3197 package Simple_Cpp_Interface is
3198    type A is limited
3199       record
3200          Vptr    : System.Address;
3201          O_Value : Integer;
3202          A_Value : Integer;
3203       end record;
3204    pragma Convention (C, A);
3206    procedure Method1 (This : in out A);
3207    pragma Import (C, Method1);
3209    procedure Ada_Method2 (This : in out A; V : Integer);
3210    pragma Export (C, Ada_Method2);
3212 end Simple_Cpp_Interface;
3213 @end smallexample
3215 @node Interfacing with C++ constructors
3216 @subsection Interfacing with C++ constructors
3217 @noindent
3219 In order to interface with C++ constructors GNAT provides the
3220 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3221 gnat_rm, GNAT Reference Manual}, for additional information).
3222 In this section we present some common uses of C++ constructors
3223 in mixed-languages programs in GNAT.
3225 Let us assume that we need to interface with the following
3226 C++ class:
3228 @smallexample
3229 @b{class} Root @{
3230 @b{public}:
3231   int  a_value;
3232   int  b_value;
3233   @b{virtual} int Get_Value ();
3234   Root();              // Default constructor
3235   Root(int v);         // 1st non-default constructor
3236   Root(int v, int w);  // 2nd non-default constructor
3238 @end smallexample
3240 For this purpose we can write the following package spec (further
3241 information on how to build this spec is available in
3242 @ref{Interfacing with C++ at the Class Level} and
3243 @ref{Generating Ada Bindings for C and C++ headers}).
3245 @smallexample @c ada
3246 with Interfaces.C; use Interfaces.C;
3247 package Pkg_Root is
3248   type Root is tagged limited record
3249      A_Value : int;
3250      B_Value : int;
3251   end record;
3252   pragma Import (CPP, Root);
3254   function Get_Value (Obj : Root) return int;
3255   pragma Import (CPP, Get_Value);
3257   function Constructor return Root;
3258   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3260   function Constructor (v : Integer) return Root;
3261   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3263   function Constructor (v, w : Integer) return Root;
3264   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3265 end Pkg_Root;
3266 @end smallexample
3268 On the Ada side the constructor is represented by a function (whose
3269 name is arbitrary) that returns the classwide type corresponding to
3270 the imported C++ class. Although the constructor is described as a
3271 function, it is typically a procedure with an extra implicit argument
3272 (the object being initialized) at the implementation level. GNAT
3273 issues the appropriate call, whatever it is, to get the object
3274 properly initialized.
3276 Constructors can only appear in the following contexts:
3278 @itemize @bullet
3279 @item
3280 On the right side of an initialization of an object of type @var{T}.
3281 @item
3282 On the right side of an initialization of a record component of type @var{T}.
3283 @item
3284 In an Ada 2005 limited aggregate.
3285 @item
3286 In an Ada 2005 nested limited aggregate.
3287 @item
3288 In an Ada 2005 limited aggregate that initializes an object built in
3289 place by an extended return statement.
3290 @end itemize
3292 @noindent
3293 In a declaration of an object whose type is a class imported from C++,
3294 either the default C++ constructor is implicitly called by GNAT, or
3295 else the required C++ constructor must be explicitly called in the
3296 expression that initializes the object. For example:
3298 @smallexample @c ada
3299   Obj1 : Root;
3300   Obj2 : Root := Constructor;
3301   Obj3 : Root := Constructor (v => 10);
3302   Obj4 : Root := Constructor (30, 40);
3303 @end smallexample
3305 The first two declarations are equivalent: in both cases the default C++
3306 constructor is invoked (in the former case the call to the constructor is
3307 implicit, and in the latter case the call is explicit in the object
3308 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3309 that takes an integer argument, and @code{Obj4} is initialized by the
3310 non-default C++ constructor that takes two integers.
3312 Let us derive the imported C++ class in the Ada side. For example:
3314 @smallexample @c ada
3315   type DT is new Root with record
3316      C_Value : Natural := 2009;
3317   end record;
3318 @end smallexample
3320 In this case the components DT inherited from the C++ side must be
3321 initialized by a C++ constructor, and the additional Ada components
3322 of type DT are initialized by GNAT. The initialization of such an
3323 object is done either by default, or by means of a function returning
3324 an aggregate of type DT, or by means of an extension aggregate.
3326 @smallexample @c ada
3327   Obj5 : DT;
3328   Obj6 : DT := Function_Returning_DT (50);
3329   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3330 @end smallexample
3332 The declaration of @code{Obj5} invokes the default constructors: the
3333 C++ default constructor of the parent type takes care of the initialization
3334 of the components inherited from Root, and GNAT takes care of the default
3335 initialization of the additional Ada components of type DT (that is,
3336 @code{C_Value} is initialized to value 2009). The order of invocation of
3337 the constructors is consistent with the order of elaboration required by
3338 Ada and C++. That is, the constructor of the parent type is always called
3339 before the constructor of the derived type.
3341 Let us now consider a record that has components whose type is imported
3342 from C++. For example:
3344 @smallexample @c ada
3345   type Rec1 is limited record
3346      Data1 : Root := Constructor (10);
3347      Value : Natural := 1000;
3348   end record;
3350   type Rec2 (D : Integer := 20) is limited record
3351      Rec   : Rec1;
3352      Data2 : Root := Constructor (D, 30);
3353   end record;
3354 @end smallexample
3356 The initialization of an object of type @code{Rec2} will call the
3357 non-default C++ constructors specified for the imported components.
3358 For example:
3360 @smallexample @c ada
3361   Obj8 : Rec2 (40);
3362 @end smallexample
3364 Using Ada 2005 we can use limited aggregates to initialize an object
3365 invoking C++ constructors that differ from those specified in the type
3366 declarations. For example:
3368 @smallexample @c ada
3369   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3370                           others => <>),
3371                   others => <>);
3372 @end smallexample
3374 The above declaration uses an Ada 2005 limited aggregate to
3375 initialize @code{Obj9}, and the C++ constructor that has two integer
3376 arguments is invoked to initialize the @code{Data1} component instead
3377 of the constructor specified in the declaration of type @code{Rec1}. In
3378 Ada 2005 the box in the aggregate indicates that unspecified components
3379 are initialized using the expression (if any) available in the component
3380 declaration. That is, in this case discriminant @code{D} is initialized
3381 to value @code{20}, @code{Value} is initialized to value 1000, and the
3382 non-default C++ constructor that handles two integers takes care of
3383 initializing component @code{Data2} with values @code{20,30}.
3385 In Ada 2005 we can use the extended return statement to build the Ada
3386 equivalent to C++ non-default constructors. For example:
3388 @smallexample @c ada
3389   function Constructor (V : Integer) return Rec2 is
3390   begin
3391      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3392                                    others => <>),
3393                            others => <>) do
3394         --  Further actions required for construction of
3395         --  objects of type Rec2
3396         ...
3397      end record;
3398   end Constructor;
3399 @end smallexample
3401 In this example the extended return statement construct is used to
3402 build in place the returned object whose components are initialized
3403 by means of a limited aggregate. Any further action associated with
3404 the constructor can be placed inside the construct.
3406 @node Interfacing with C++ at the Class Level
3407 @subsection Interfacing with C++ at the Class Level
3408 @noindent
3409 In this section we demonstrate the GNAT features for interfacing with
3410 C++ by means of an example making use of Ada 2005 abstract interface
3411 types. This example consists of a classification of animals; classes
3412 have been used to model our main classification of animals, and
3413 interfaces provide support for the management of secondary
3414 classifications. We first demonstrate a case in which the types and
3415 constructors are defined on the C++ side and imported from the Ada
3416 side, and latter the reverse case.
3418 The root of our derivation will be the @code{Animal} class, with a
3419 single private attribute (the @code{Age} of the animal) and two public
3420 primitives to set and get the value of this attribute.
3422 @smallexample
3423 @b{class} Animal @{
3424  @b{public}:
3425    @b{virtual} void Set_Age (int New_Age);
3426    @b{virtual} int Age ();
3427  @b{private}:
3428    int Age_Count;
3430 @end smallexample
3432 Abstract interface types are defined in C++ by means of classes with pure
3433 virtual functions and no data members. In our example we will use two
3434 interfaces that provide support for the common management of @code{Carnivore}
3435 and @code{Domestic} animals:
3437 @smallexample
3438 @b{class} Carnivore @{
3439 @b{public}:
3440    @b{virtual} int Number_Of_Teeth () = 0;
3443 @b{class} Domestic @{
3444 @b{public}:
3445    @b{virtual void} Set_Owner (char* Name) = 0;
3447 @end smallexample
3449 Using these declarations, we can now say that a @code{Dog} is an animal that is
3450 both Carnivore and Domestic, that is:
3452 @smallexample
3453 @b{class} Dog : Animal, Carnivore, Domestic @{
3454  @b{public}:
3455    @b{virtual} int  Number_Of_Teeth ();
3456    @b{virtual} void Set_Owner (char* Name);
3458    Dog(); // Constructor
3459  @b{private}:
3460    int  Tooth_Count;
3461    char *Owner;
3463 @end smallexample
3465 In the following examples we will assume that the previous declarations are
3466 located in a file named @code{animals.h}. The following package demonstrates
3467 how to import these C++ declarations from the Ada side:
3469 @smallexample @c ada
3470 with Interfaces.C.Strings; use Interfaces.C.Strings;
3471 package Animals is
3472   type Carnivore is interface;
3473   pragma Convention (C_Plus_Plus, Carnivore);
3474   function Number_Of_Teeth (X : Carnivore)
3475      return Natural is abstract;
3477   type Domestic is interface;
3478   pragma Convention (C_Plus_Plus, Set_Owner);
3479   procedure Set_Owner
3480     (X    : in out Domestic;
3481      Name : Chars_Ptr) is abstract;
3483   type Animal is tagged record
3484     Age : Natural := 0;
3485   end record;
3486   pragma Import (C_Plus_Plus, Animal);
3488   procedure Set_Age (X : in out Animal; Age : Integer);
3489   pragma Import (C_Plus_Plus, Set_Age);
3491   function Age (X : Animal) return Integer;
3492   pragma Import (C_Plus_Plus, Age);
3494   type Dog is new Animal and Carnivore and Domestic with record
3495     Tooth_Count : Natural;
3496     Owner       : String (1 .. 30);
3497   end record;
3498   pragma Import (C_Plus_Plus, Dog);
3500   function Number_Of_Teeth (A : Dog) return Integer;
3501   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3503   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3504   pragma Import (C_Plus_Plus, Set_Owner);
3506   function New_Dog return Dog;
3507   pragma CPP_Constructor (New_Dog);
3508   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3509 end Animals;
3510 @end smallexample
3512 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3513 interfacing with these C++ classes is easy. The only requirement is that all
3514 the primitives and components must be declared exactly in the same order in
3515 the two languages.
3517 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3518 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3519 the arguments to the called primitives will be the same as for C++. For the
3520 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3521 to indicate that they have been defined on the C++ side; this is required
3522 because the dispatch table associated with these tagged types will be built
3523 in the C++ side and therefore will not contain the predefined Ada primitives
3524 which Ada would otherwise expect.
3526 As the reader can see there is no need to indicate the C++ mangled names
3527 associated with each subprogram because it is assumed that all the calls to
3528 these primitives will be dispatching calls. The only exception is the
3529 constructor, which must be registered with the compiler by means of
3530 @code{pragma CPP_Constructor} and needs to provide its associated C++
3531 mangled name because the Ada compiler generates direct calls to it.
3533 With the above packages we can now declare objects of type Dog on the Ada side
3534 and dispatch calls to the corresponding subprograms on the C++ side. We can
3535 also extend the tagged type Dog with further fields and primitives, and
3536 override some of its C++ primitives on the Ada side. For example, here we have
3537 a type derivation defined on the Ada side that inherits all the dispatching
3538 primitives of the ancestor from the C++ side.
3540 @smallexample
3541 @b{with} Animals; @b{use} Animals;
3542 @b{package} Vaccinated_Animals @b{is}
3543   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3544   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3545 @b{end} Vaccinated_Animals;
3546 @end smallexample
3548 It is important to note that, because of the ABI compatibility, the programmer
3549 does not need to add any further information to indicate either the object
3550 layout or the dispatch table entry associated with each dispatching operation.
3552 Now let us define all the types and constructors on the Ada side and export
3553 them to C++, using the same hierarchy of our previous example:
3555 @smallexample @c ada
3556 with Interfaces.C.Strings;
3557 use Interfaces.C.Strings;
3558 package Animals is
3559   type Carnivore is interface;
3560   pragma Convention (C_Plus_Plus, Carnivore);
3561   function Number_Of_Teeth (X : Carnivore)
3562      return Natural is abstract;
3564   type Domestic is interface;
3565   pragma Convention (C_Plus_Plus, Set_Owner);
3566   procedure Set_Owner
3567     (X    : in out Domestic;
3568      Name : Chars_Ptr) is abstract;
3570   type Animal is tagged record
3571     Age : Natural := 0;
3572   end record;
3573   pragma Convention (C_Plus_Plus, Animal);
3575   procedure Set_Age (X : in out Animal; Age : Integer);
3576   pragma Export (C_Plus_Plus, Set_Age);
3578   function Age (X : Animal) return Integer;
3579   pragma Export (C_Plus_Plus, Age);
3581   type Dog is new Animal and Carnivore and Domestic with record
3582     Tooth_Count : Natural;
3583     Owner       : String (1 .. 30);
3584   end record;
3585   pragma Convention (C_Plus_Plus, Dog);
3587   function Number_Of_Teeth (A : Dog) return Integer;
3588   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3590   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3591   pragma Export (C_Plus_Plus, Set_Owner);
3593   function New_Dog return Dog'Class;
3594   pragma Export (C_Plus_Plus, New_Dog);
3595 end Animals;
3596 @end smallexample
3598 Compared with our previous example the only difference is the use of
3599 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3600 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3601 nothing else to be done; as explained above, the only requirement is that all
3602 the primitives and components are declared in exactly the same order.
3604 For completeness, let us see a brief C++ main program that uses the
3605 declarations available in @code{animals.h} (presented in our first example) to
3606 import and use the declarations from the Ada side, properly initializing and
3607 finalizing the Ada run-time system along the way:
3609 @smallexample
3610 @b{#include} "animals.h"
3611 @b{#include} <iostream>
3612 @b{using namespace} std;
3614 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3615 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3616 void Check_Animal (Animal *obj)       @{@dots{}@}
3617 void Check_Dog (Dog *obj)             @{@dots{}@}
3619 @b{extern} "C" @{
3620   void adainit (void);
3621   void adafinal (void);
3622   Dog* new_dog ();
3625 void test ()
3627   Dog *obj = new_dog();  // Ada constructor
3628   Check_Carnivore (obj); // Check secondary DT
3629   Check_Domestic (obj);  // Check secondary DT
3630   Check_Animal (obj);    // Check primary DT
3631   Check_Dog (obj);       // Check primary DT
3634 int main ()
3636   adainit ();  test();  adafinal ();
3637   return 0;
3639 @end smallexample
3641 @node Comparison between GNAT and C/C++ Compilation Models
3642 @section Comparison between GNAT and C/C++ Compilation Models
3644 @noindent
3645 The GNAT model of compilation is close to the C and C++ models. You can
3646 think of Ada specs as corresponding to header files in C. As in C, you
3647 don't need to compile specs; they are compiled when they are used. The
3648 Ada @code{with} is similar in effect to the @code{#include} of a C
3649 header.
3651 One notable difference is that, in Ada, you may compile specs separately
3652 to check them for semantic and syntactic accuracy. This is not always
3653 possible with C headers because they are fragments of programs that have
3654 less specific syntactic or semantic rules.
3656 The other major difference is the requirement for running the binder,
3657 which performs two important functions. First, it checks for
3658 consistency. In C or C++, the only defense against assembling
3659 inconsistent programs lies outside the compiler, in a makefile, for
3660 example. The binder satisfies the Ada requirement that it be impossible
3661 to construct an inconsistent program when the compiler is used in normal
3662 mode.
3664 @cindex Elaboration order control
3665 The other important function of the binder is to deal with elaboration
3666 issues. There are also elaboration issues in C++ that are handled
3667 automatically. This automatic handling has the advantage of being
3668 simpler to use, but the C++ programmer has no control over elaboration.
3669 Where @code{gnatbind} might complain there was no valid order of
3670 elaboration, a C++ compiler would simply construct a program that
3671 malfunctioned at run time.
3672 @end ifclear
3674 @node Comparison between GNAT and Conventional Ada Library Models
3675 @section Comparison between GNAT and Conventional Ada Library Models
3677 @noindent
3678 This section is intended for Ada programmers who have
3679 used an Ada compiler implementing the traditional Ada library
3680 model, as described in the Ada Reference Manual.
3682 @cindex GNAT library
3683 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3684 source files themselves acts as the library. Compiling Ada programs does
3685 not generate any centralized information, but rather an object file and
3686 a ALI file, which are of interest only to the binder and linker.
3687 In a traditional system, the compiler reads information not only from
3688 the source file being compiled, but also from the centralized library.
3689 This means that the effect of a compilation depends on what has been
3690 previously compiled. In particular:
3692 @itemize @bullet
3693 @item
3694 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3695 to the version of the unit most recently compiled into the library.
3697 @item
3698 Inlining is effective only if the necessary body has already been
3699 compiled into the library.
3701 @item
3702 Compiling a unit may obsolete other units in the library.
3703 @end itemize
3705 @noindent
3706 In GNAT, compiling one unit never affects the compilation of any other
3707 units because the compiler reads only source files. Only changes to source
3708 files can affect the results of a compilation. In particular:
3710 @itemize @bullet
3711 @item
3712 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3713 to the source version of the unit that is currently accessible to the
3714 compiler.
3716 @item
3717 @cindex Inlining
3718 Inlining requires the appropriate source files for the package or
3719 subprogram bodies to be available to the compiler. Inlining is always
3720 effective, independent of the order in which units are complied.
3722 @item
3723 Compiling a unit never affects any other compilations. The editing of
3724 sources may cause previous compilations to be out of date if they
3725 depended on the source file being modified.
3726 @end itemize
3728 @noindent
3729 The most important result of these differences is that order of compilation
3730 is never significant in GNAT. There is no situation in which one is
3731 required to do one compilation before another. What shows up as order of
3732 compilation requirements in the traditional Ada library becomes, in
3733 GNAT, simple source dependencies; in other words, there is only a set
3734 of rules saying what source files must be present when a file is
3735 compiled.
3737 @ifset vms
3738 @node Placement of temporary files
3739 @section Placement of temporary files
3740 @cindex Temporary files (user control over placement)
3742 @noindent
3743 GNAT creates temporary files in the directory designated by the environment
3744 variable @env{TMPDIR}.
3745 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3746 for detailed information on how environment variables are resolved.
3747 For most users the easiest way to make use of this feature is to simply
3748 define @env{TMPDIR} as a job level logical name).
3749 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3750 for compiler temporary files, then you can include something like the
3751 following command in your @file{LOGIN.COM} file:
3753 @smallexample
3754 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3755 @end smallexample
3757 @noindent
3758 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3759 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3760 designated by @env{TEMP}.
3761 If none of these environment variables are defined then GNAT uses the
3762 directory designated by the logical name @code{SYS$SCRATCH:}
3763 (by default the user's home directory). If all else fails
3764 GNAT uses the current directory for temporary files.
3765 @end ifset
3767 @c *************************
3768 @node Compiling Using gcc
3769 @chapter Compiling Using @command{gcc}
3771 @noindent
3772 This chapter discusses how to compile Ada programs using the @command{gcc}
3773 command. It also describes the set of switches
3774 that can be used to control the behavior of the compiler.
3775 @menu
3776 * Compiling Programs::
3777 * Switches for gcc::
3778 * Search Paths and the Run-Time Library (RTL)::
3779 * Order of Compilation Issues::
3780 * Examples::
3781 @end menu
3783 @node Compiling Programs
3784 @section Compiling Programs
3786 @noindent
3787 The first step in creating an executable program is to compile the units
3788 of the program using the @command{gcc} command. You must compile the
3789 following files:
3791 @itemize @bullet
3792 @item
3793 the body file (@file{.adb}) for a library level subprogram or generic
3794 subprogram
3796 @item
3797 the spec file (@file{.ads}) for a library level package or generic
3798 package that has no body
3800 @item
3801 the body file (@file{.adb}) for a library level package
3802 or generic package that has a body
3804 @end itemize
3806 @noindent
3807 You need @emph{not} compile the following files
3809 @itemize @bullet
3811 @item
3812 the spec of a library unit which has a body
3814 @item
3815 subunits
3816 @end itemize
3818 @noindent
3819 because they are compiled as part of compiling related units. GNAT
3820 package specs
3821 when the corresponding body is compiled, and subunits when the parent is
3822 compiled.
3824 @cindex cannot generate code
3825 If you attempt to compile any of these files, you will get one of the
3826 following error messages (where @var{fff} is the name of the file you
3827 compiled):
3829 @smallexample
3830 cannot generate code for file @var{fff} (package spec)
3831 to check package spec, use -gnatc
3833 cannot generate code for file @var{fff} (missing subunits)
3834 to check parent unit, use -gnatc
3836 cannot generate code for file @var{fff} (subprogram spec)
3837 to check subprogram spec, use -gnatc
3839 cannot generate code for file @var{fff} (subunit)
3840 to check subunit, use -gnatc
3841 @end smallexample
3843 @noindent
3844 As indicated by the above error messages, if you want to submit
3845 one of these files to the compiler to check for correct semantics
3846 without generating code, then use the @option{-gnatc} switch.
3848 The basic command for compiling a file containing an Ada unit is
3850 @smallexample
3851 @c $ gcc -c @ovar{switches} @file{file name}
3852 @c Expanding @ovar macro inline (explanation in macro def comments)
3853 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3854 @end smallexample
3856 @noindent
3857 where @var{file name} is the name of the Ada file (usually
3858 having an extension
3859 @file{.ads} for a spec or @file{.adb} for a body).
3860 @ifclear vms
3861 You specify the
3862 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3863 @end ifclear
3864 The result of a successful compilation is an object file, which has the
3865 same name as the source file but an extension of @file{.o} and an Ada
3866 Library Information (ALI) file, which also has the same name as the
3867 source file, but with @file{.ali} as the extension. GNAT creates these
3868 two output files in the current directory, but you may specify a source
3869 file in any directory using an absolute or relative path specification
3870 containing the directory information.
3872 @findex gnat1
3873 @command{gcc} is actually a driver program that looks at the extensions of
3874 the file arguments and loads the appropriate compiler. For example, the
3875 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3876 These programs are in directories known to the driver program (in some
3877 configurations via environment variables you set), but need not be in
3878 your path. The @command{gcc} driver also calls the assembler and any other
3879 utilities needed to complete the generation of the required object
3880 files.
3882 It is possible to supply several file names on the same @command{gcc}
3883 command. This causes @command{gcc} to call the appropriate compiler for
3884 each file. For example, the following command lists three separate
3885 files to be compiled:
3887 @smallexample
3888 $ gcc -c x.adb y.adb z.c
3889 @end smallexample
3891 @noindent
3892 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3893 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3894 The compiler generates three object files @file{x.o}, @file{y.o} and
3895 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3896 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3897 @ifclear vms
3898 except for
3899 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3900 @end ifclear
3902 @node Switches for gcc
3903 @section Switches for @command{gcc}
3905 @noindent
3906 The @command{gcc} command accepts switches that control the
3907 compilation process. These switches are fully described in this section.
3908 First we briefly list all the switches, in alphabetical order, then we
3909 describe the switches in more detail in functionally grouped sections.
3911 More switches exist for GCC than those documented here, especially
3912 for specific targets. However, their use is not recommended as
3913 they may change code generation in ways that are incompatible with
3914 the Ada run-time library, or can cause inconsistencies between
3915 compilation units.
3917 @menu
3918 * Output and Error Message Control::
3919 * Warning Message Control::
3920 * Debugging and Assertion Control::
3921 * Validity Checking::
3922 * Style Checking::
3923 * Run-Time Checks::
3924 * Using gcc for Syntax Checking::
3925 * Using gcc for Semantic Checking::
3926 * Compiling Different Versions of Ada::
3927 * Character Set Control::
3928 * File Naming Control::
3929 * Subprogram Inlining Control::
3930 * Auxiliary Output Control::
3931 * Debugging Control::
3932 * Exception Handling Control::
3933 * Units to Sources Mapping Files::
3934 * Integrated Preprocessing::
3935 * Code Generation Control::
3936 @ifset vms
3937 * Return Codes::
3938 @end ifset
3939 @end menu
3941 @table @option
3942 @c !sort!
3943 @ifclear vms
3944 @cindex @option{-b} (@command{gcc})
3945 @item -b @var{target}
3946 Compile your program to run on @var{target}, which is the name of a
3947 system configuration. You must have a GNAT cross-compiler built if
3948 @var{target} is not the same as your host system.
3950 @item -B@var{dir}
3951 @cindex @option{-B} (@command{gcc})
3952 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3953 from @var{dir} instead of the default location. Only use this switch
3954 when multiple versions of the GNAT compiler are available.
3955 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3956 GNU Compiler Collection (GCC)}, for further details. You would normally
3957 use the @option{-b} or @option{-V} switch instead.
3959 @item -c
3960 @cindex @option{-c} (@command{gcc})
3961 Compile. Always use this switch when compiling Ada programs.
3963 Note: for some other languages when using @command{gcc}, notably in
3964 the case of C and C++, it is possible to use
3965 use @command{gcc} without a @option{-c} switch to
3966 compile and link in one step. In the case of GNAT, you
3967 cannot use this approach, because the binder must be run
3968 and @command{gcc} cannot be used to run the GNAT binder.
3969 @end ifclear
3971 @item -fno-inline
3972 @cindex @option{-fno-inline} (@command{gcc})
3973 Suppresses all back-end inlining, even if other optimization or inlining
3974 switches are set.
3975 This includes suppression of inlining that results
3976 from the use of the pragma @code{Inline_Always}.
3977 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3978 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3979 effect if this switch is present.
3981 @item -fno-inline-functions
3982 @cindex @option{-fno-inline-functions} (@command{gcc})
3983 Suppresses automatic inlining of subprograms, which is enabled
3984 if @option{-O3} is used.
3986 @item -fno-inline-small-functions
3987 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3988 Suppresses automatic inlining of small subprograms, which is enabled
3989 if @option{-O2} is used.
3991 @item -fno-inline-functions-called-once
3992 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3993 Suppresses inlining of subprograms local to the unit and called once
3994 from within it, which is enabled if @option{-O1} is used.
3996 @item -fno-ivopts
3997 @cindex @option{-fno-ivopts} (@command{gcc})
3998 Suppresses high-level loop induction variable optimizations, which are
3999 enabled if @option{-O1} is used. These optimizations are generally
4000 profitable but, for some specific cases of loops with numerous uses
4001 of the iteration variable that follow a common pattern, they may end
4002 up destroying the regularity that could be exploited at a lower level
4003 and thus producing inferior code.
4005 @item -fno-strict-aliasing
4006 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4007 Causes the compiler to avoid assumptions regarding non-aliasing
4008 of objects of different types. See
4009 @ref{Optimization and Strict Aliasing} for details.
4011 @item -fstack-check
4012 @cindex @option{-fstack-check} (@command{gcc})
4013 Activates stack checking.
4014 See @ref{Stack Overflow Checking} for details.
4016 @item -fstack-usage
4017 @cindex @option{-fstack-usage} (@command{gcc})
4018 Makes the compiler output stack usage information for the program, on a
4019 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4021 @item -fcallgraph-info@r{[}=su@r{]}
4022 @cindex @option{-fcallgraph-info} (@command{gcc})
4023 Makes the compiler output callgraph information for the program, on a
4024 per-file basis.  The information is generated in the VCG format.  It can
4025 be decorated with stack-usage per-node information.
4027 @item ^-g^/DEBUG^
4028 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4029 Generate debugging information. This information is stored in the object
4030 file and copied from there to the final executable file by the linker,
4031 where it can be read by the debugger. You must use the
4032 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4034 @item -gnat83
4035 @cindex @option{-gnat83} (@command{gcc})
4036 Enforce Ada 83 restrictions.
4038 @item -gnat95
4039 @cindex @option{-gnat95} (@command{gcc})
4040 Enforce Ada 95 restrictions.
4042 @item -gnat05
4043 @cindex @option{-gnat05} (@command{gcc})
4044 Allow full Ada 2005 features.
4046 @item -gnat2005
4047 @cindex @option{-gnat2005} (@command{gcc})
4048 Allow full Ada 2005 features (same as @option{-gnat05})
4050 @item -gnat12
4051 @cindex @option{-gnat12} (@command{gcc})
4053 @item -gnat2012
4054 @cindex @option{-gnat2012} (@command{gcc})
4055 Allow full Ada 2012 features (same as @option{-gnat12})
4057 @item -gnata
4058 @cindex @option{-gnata} (@command{gcc})
4059 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4060 activated. Note that these pragmas can also be controlled using the
4061 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4062 It also activates pragmas @code{Check}, @code{Precondition}, and
4063 @code{Postcondition}. Note that these pragmas can also be controlled
4064 using the configuration pragma @code{Check_Policy}.
4066 @item -gnatA
4067 @cindex @option{-gnatA} (@command{gcc})
4068 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4069 it will be ignored.
4071 @item -gnatb
4072 @cindex @option{-gnatb} (@command{gcc})
4073 Generate brief messages to @file{stderr} even if verbose mode set.
4075 @item -gnatB
4076 @cindex @option{-gnatB} (@command{gcc})
4077 Assume no invalid (bad) values except for 'Valid attribute use
4078 (@pxref{Validity Checking}).
4080 @item -gnatc
4081 @cindex @option{-gnatc} (@command{gcc})
4082 Check syntax and semantics only (no code generation attempted).
4084 @item -gnatC
4085 @cindex @option{-gnatC} (@command{gcc})
4086 Generate CodePeer information (no code generation attempted).
4087 This switch will generate an intermediate representation suitable for
4088 use by CodePeer (@file{.scil} files). This switch is not compatible with
4089 code generation (it will, among other things, disable some switches such
4090 as -gnatn, and enable others such as -gnata).
4092 @item -gnatd
4093 @cindex @option{-gnatd} (@command{gcc})
4094 Specify debug options for the compiler. The string of characters after
4095 the @option{-gnatd} specify the specific debug options. The possible
4096 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4097 compiler source file @file{debug.adb} for details of the implemented
4098 debug options. Certain debug options are relevant to applications
4099 programmers, and these are documented at appropriate points in this
4100 users guide.
4102 @ifclear vms
4103 @item -gnatD
4104 @cindex @option{-gnatD[nn]} (@command{gcc})
4105 @end ifclear
4106 @ifset vms
4107 @item /XDEBUG /LXDEBUG=nnn
4108 @end ifset
4109 Create expanded source files for source level debugging. This switch
4110 also suppress generation of cross-reference information
4111 (see @option{-gnatx}).
4113 @item -gnatec=@var{path}
4114 @cindex @option{-gnatec} (@command{gcc})
4115 Specify a configuration pragma file
4116 @ifclear vms
4117 (the equal sign is optional)
4118 @end ifclear
4119 (@pxref{The Configuration Pragmas Files}).
4121 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4122 @cindex @option{-gnateD} (@command{gcc})
4123 Defines a symbol, associated with @var{value}, for preprocessing.
4124 (@pxref{Integrated Preprocessing}).
4126 @item -gnateE
4127 @cindex @option{-gnateE} (@command{gcc})
4128 Generate extra information in exception messages, in particular display
4129 extra column information and the value and range associated with index and
4130 range check failures, and extra column information for access checks.
4132 @item -gnatef
4133 @cindex @option{-gnatef} (@command{gcc})
4134 Display full source path name in brief error messages.
4136 @item -gnateG
4137 @cindex @option{-gnateG} (@command{gcc})
4138 Save result of preprocessing in a text file.
4140 @item -gnatem=@var{path}
4141 @cindex @option{-gnatem} (@command{gcc})
4142 Specify a mapping file
4143 @ifclear vms
4144 (the equal sign is optional)
4145 @end ifclear
4146 (@pxref{Units to Sources Mapping Files}).
4148 @item -gnatep=@var{file}
4149 @cindex @option{-gnatep} (@command{gcc})
4150 Specify a preprocessing data file
4151 @ifclear vms
4152 (the equal sign is optional)
4153 @end ifclear
4154 (@pxref{Integrated Preprocessing}).
4156 @item -gnateS
4157 @cindex @option{-gnateS} (@command{gcc})
4158 Generate SCO (Source Coverage Obligation) information in the ALI
4159 file. This information is used by advanced coverage tools. See
4160 unit @file{SCOs} in the compiler sources for details in files
4161 @file{scos.ads} and @file{scos.adb}.
4163 @item -gnatE
4164 @cindex @option{-gnatE} (@command{gcc})
4165 Full dynamic elaboration checks.
4167 @item -gnatf
4168 @cindex @option{-gnatf} (@command{gcc})
4169 Full errors. Multiple errors per line, all undefined references, do not
4170 attempt to suppress cascaded errors.
4172 @item -gnatF
4173 @cindex @option{-gnatF} (@command{gcc})
4174 Externals names are folded to all uppercase.
4176 @item ^-gnatg^/GNAT_INTERNAL^
4177 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4178 Internal GNAT implementation mode. This should not be used for
4179 applications programs, it is intended only for use by the compiler
4180 and its run-time library. For documentation, see the GNAT sources.
4181 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4182 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4183 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4184 so that all standard warnings and all standard style options are turned on.
4185 All warnings and style messages are treated as errors.
4187 @ifclear vms
4188 @item -gnatG=nn
4189 @cindex @option{-gnatG[nn]} (@command{gcc})
4190 @end ifclear
4191 @ifset vms
4192 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4193 @end ifset
4194 List generated expanded code in source form.
4196 @item ^-gnath^/HELP^
4197 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4198 Output usage information. The output is written to @file{stdout}.
4200 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4201 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4202 Identifier character set
4203 @ifclear vms
4204 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4205 @end ifclear
4206 For details of the possible selections for @var{c},
4207 see @ref{Character Set Control}.
4209 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4210 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4211 Ignore representation clauses. When this switch is used,
4212 representation clauses are treated as comments. This is useful
4213 when initially porting code where you want to ignore rep clause
4214 problems, and also for compiling foreign code (particularly
4215 for use with ASIS). The representation clauses that are ignored
4216 are: enumeration_representation_clause, record_representation_clause,
4217 and attribute_definition_clause for the following attributes:
4218 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4219 Object_Size, Size, Small, Stream_Size, and Value_Size.
4220 Note that this option should be used only for compiling -- the
4221 code is likely to malfunction at run time.
4223 @item -gnatjnn
4224 @cindex @option{-gnatjnn} (@command{gcc})
4225 Reformat error messages to fit on nn character lines
4227 @item -gnatk=@var{n}
4228 @cindex @option{-gnatk} (@command{gcc})
4229 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4231 @item -gnatl
4232 @cindex @option{-gnatl} (@command{gcc})
4233 Output full source listing with embedded error messages.
4235 @item -gnatL
4236 @cindex @option{-gnatL} (@command{gcc})
4237 Used in conjunction with -gnatG or -gnatD to intersperse original
4238 source lines (as comment lines with line numbers) in the expanded
4239 source output.
4241 @item -gnatm=@var{n}
4242 @cindex @option{-gnatm} (@command{gcc})
4243 Limit number of detected error or warning messages to @var{n}
4244 where @var{n} is in the range 1..999999. The default setting if
4245 no switch is given is 9999. If the number of warnings reaches this
4246 limit, then a message is output and further warnings are suppressed,
4247 but the compilation is continued. If the number of error messages
4248 reaches this limit, then a message is output and the compilation
4249 is abandoned. The equal sign here is optional. A value of zero
4250 means that no limit applies.
4252 @item -gnatn
4253 @cindex @option{-gnatn} (@command{gcc})
4254 Activate inlining for subprograms for which
4255 pragma @code{Inline} is specified. This inlining is performed
4256 by the GCC back-end.
4258 @item -gnatN
4259 @cindex @option{-gnatN} (@command{gcc})
4260 Activate front end inlining for subprograms for which
4261 pragma @code{Inline} is specified. This inlining is performed
4262 by the front end and will be visible in the
4263 @option{-gnatG} output.
4265 When using a gcc-based back end (in practice this means using any version
4266 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4267 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4268 Historically front end inlining was more extensive than the gcc back end
4269 inlining, but that is no longer the case.
4271 @item -gnato
4272 @cindex @option{-gnato} (@command{gcc})
4273 Enable numeric overflow checking (which is not normally enabled by
4274 default). Note that division by zero is a separate check that is not
4275 controlled by this switch (division by zero checking is on by default).
4277 @item -gnatp
4278 @cindex @option{-gnatp} (@command{gcc})
4279 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4280 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4282 @item -gnat-p
4283 @cindex @option{-gnat-p} (@command{gcc})
4284 Cancel effect of previous @option{-gnatp} switch.
4286 @item -gnatP
4287 @cindex @option{-gnatP} (@command{gcc})
4288 Enable polling. This is required on some systems (notably Windows NT) to
4289 obtain asynchronous abort and asynchronous transfer of control capability.
4290 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4291 details.
4293 @item -gnatq
4294 @cindex @option{-gnatq} (@command{gcc})
4295 Don't quit. Try semantics, even if parse errors.
4297 @item -gnatQ
4298 @cindex @option{-gnatQ} (@command{gcc})
4299 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4301 @item -gnatr
4302 @cindex @option{-gnatr} (@command{gcc})
4303 Treat pragma Restrictions as Restriction_Warnings.
4305 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4306 @cindex @option{-gnatR} (@command{gcc})
4307 Output representation information for declared types and objects.
4309 @item -gnats
4310 @cindex @option{-gnats} (@command{gcc})
4311 Syntax check only.
4313 @item -gnatS
4314 @cindex @option{-gnatS} (@command{gcc})
4315 Print package Standard.
4317 @item -gnatt
4318 @cindex @option{-gnatt} (@command{gcc})
4319 Generate tree output file.
4321 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4322 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4323 All compiler tables start at @var{nnn} times usual starting size.
4325 @item -gnatu
4326 @cindex @option{-gnatu} (@command{gcc})
4327 List units for this compilation.
4329 @item -gnatU
4330 @cindex @option{-gnatU} (@command{gcc})
4331 Tag all error messages with the unique string ``error:''
4333 @item -gnatv
4334 @cindex @option{-gnatv} (@command{gcc})
4335 Verbose mode. Full error output with source lines to @file{stdout}.
4337 @item -gnatV
4338 @cindex @option{-gnatV} (@command{gcc})
4339 Control level of validity checking (@pxref{Validity Checking}).
4341 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4342 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4343 Warning mode where
4344 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4345 the exact warnings that
4346 are enabled or disabled (@pxref{Warning Message Control}).
4348 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4349 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4350 Wide character encoding method
4351 @ifclear vms
4352 (@var{e}=n/h/u/s/e/8).
4353 @end ifclear
4354 @ifset vms
4355 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4356 @end ifset
4358 @item -gnatx
4359 @cindex @option{-gnatx} (@command{gcc})
4360 Suppress generation of cross-reference information.
4362 @item -gnatX
4363 @cindex @option{-gnatX} (@command{gcc})
4364 Enable GNAT implementation extensions and latest Ada version.
4366 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4367 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4368 Enable built-in style checks (@pxref{Style Checking}).
4370 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4371 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4372 Distribution stub generation and compilation
4373 @ifclear vms
4374 (@var{m}=r/c for receiver/caller stubs).
4375 @end ifclear
4376 @ifset vms
4377 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4378 to be generated and compiled).
4379 @end ifset
4381 @item ^-I^/SEARCH=^@var{dir}
4382 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4383 @cindex RTL
4384 Direct GNAT to search the @var{dir} directory for source files needed by
4385 the current compilation
4386 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4388 @item ^-I-^/NOCURRENT_DIRECTORY^
4389 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4390 @cindex RTL
4391 Except for the source file named in the command line, do not look for source
4392 files in the directory containing the source file named in the command line
4393 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4395 @ifclear vms
4396 @item -mbig-switch
4397 @cindex @option{-mbig-switch} (@command{gcc})
4398 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4399 This standard gcc switch causes the compiler to use larger offsets in its
4400 jump table representation for @code{case} statements.
4401 This may result in less efficient code, but is sometimes necessary
4402 (for example on HP-UX targets)
4403 @cindex HP-UX and @option{-mbig-switch} option
4404 in order to compile large and/or nested @code{case} statements.
4406 @item -o @var{file}
4407 @cindex @option{-o} (@command{gcc})
4408 This switch is used in @command{gcc} to redirect the generated object file
4409 and its associated ALI file. Beware of this switch with GNAT, because it may
4410 cause the object file and ALI file to have different names which in turn
4411 may confuse the binder and the linker.
4412 @end ifclear
4414 @item -nostdinc
4415 @cindex @option{-nostdinc} (@command{gcc})
4416 Inhibit the search of the default location for the GNAT Run Time
4417 Library (RTL) source files.
4419 @item -nostdlib
4420 @cindex @option{-nostdlib} (@command{gcc})
4421 Inhibit the search of the default location for the GNAT Run Time
4422 Library (RTL) ALI files.
4424 @ifclear vms
4425 @c @item -O@ovar{n}
4426 @c Expanding @ovar macro inline (explanation in macro def comments)
4427 @item -O@r{[}@var{n}@r{]}
4428 @cindex @option{-O} (@command{gcc})
4429 @var{n} controls the optimization level.
4431 @table @asis
4432 @item n = 0
4433 No optimization, the default setting if no @option{-O} appears
4435 @item n = 1
4436 Normal optimization, the default if you specify @option{-O} without
4437 an operand. A good compromise between code quality and compilation
4438 time.
4440 @item n = 2
4441 Extensive optimization, may improve execution time, possibly at the cost of
4442 substantially increased compilation time.
4444 @item n = 3
4445 Same as @option{-O2}, and also includes inline expansion for small subprograms
4446 in the same unit.
4448 @item n = s
4449 Optimize space usage
4450 @end table
4452 @noindent
4453 See also @ref{Optimization Levels}.
4454 @end ifclear
4456 @ifset vms
4457 @item  /NOOPTIMIZE
4458 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4459 Equivalent to @option{/OPTIMIZE=NONE}.
4460 This is the default behavior in the absence of an @option{/OPTIMIZE}
4461 qualifier.
4463 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4464 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4465 Selects the level of optimization for your program. The supported
4466 keywords are as follows:
4467 @table @code
4468 @item   ALL
4469 Perform most optimizations, including those that
4470 are expensive.
4471 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4472 without keyword options.
4474 @item   NONE
4475 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4477 @item SOME
4478 Perform some optimizations, but omit ones that are costly.
4480 @item   DEVELOPMENT
4481 Same as @code{SOME}.
4483 @item INLINING
4484 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4485 automatic inlining of small subprograms within a unit
4487 @item   UNROLL_LOOPS
4488 Try to unroll loops. This keyword may be specified together with
4489 any keyword above other than @code{NONE}. Loop unrolling
4490 usually, but not always, improves the performance of programs.
4492 @item SPACE
4493 Optimize space usage
4494 @end table
4496 @noindent
4497 See also @ref{Optimization Levels}.
4498 @end ifset
4500 @ifclear vms
4501 @item -pass-exit-codes
4502 @cindex @option{-pass-exit-codes} (@command{gcc})
4503 Catch exit codes from the compiler and use the most meaningful as
4504 exit status.
4505 @end ifclear
4507 @item --RTS=@var{rts-path}
4508 @cindex @option{--RTS} (@command{gcc})
4509 Specifies the default location of the runtime library. Same meaning as the
4510 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4512 @item ^-S^/ASM^
4513 @cindex @option{^-S^/ASM^} (@command{gcc})
4514 ^Used in place of @option{-c} to^Used to^
4515 cause the assembler source file to be
4516 generated, using @file{^.s^.S^} as the extension,
4517 instead of the object file.
4518 This may be useful if you need to examine the generated assembly code.
4520 @item ^-fverbose-asm^/VERBOSE_ASM^
4521 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4522 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4523 to cause the generated assembly code file to be annotated with variable
4524 names, making it significantly easier to follow.
4526 @item ^-v^/VERBOSE^
4527 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4528 Show commands generated by the @command{gcc} driver. Normally used only for
4529 debugging purposes or if you need to be sure what version of the
4530 compiler you are executing.
4532 @ifclear vms
4533 @item -V @var{ver}
4534 @cindex @option{-V} (@command{gcc})
4535 Execute @var{ver} version of the compiler. This is the @command{gcc}
4536 version, not the GNAT version.
4537 @end ifclear
4539 @item ^-w^/NO_BACK_END_WARNINGS^
4540 @cindex @option{-w} (@command{gcc})
4541 Turn off warnings generated by the back end of the compiler. Use of
4542 this switch also causes the default for front end warnings to be set
4543 to suppress (as though @option{-gnatws} had appeared at the start of
4544 the options).
4546 @end table
4548 @ifclear vms
4549 @c Combining qualifiers does not work on VMS
4550 You may combine a sequence of GNAT switches into a single switch. For
4551 example, the combined switch
4553 @cindex Combining GNAT switches
4554 @smallexample
4555 -gnatofi3
4556 @end smallexample
4558 @noindent
4559 is equivalent to specifying the following sequence of switches:
4561 @smallexample
4562 -gnato -gnatf -gnati3
4563 @end smallexample
4564 @end ifclear
4566 @noindent
4567 The following restrictions apply to the combination of switches
4568 in this manner:
4570 @itemize @bullet
4571 @item
4572 The switch @option{-gnatc} if combined with other switches must come
4573 first in the string.
4575 @item
4576 The switch @option{-gnats} if combined with other switches must come
4577 first in the string.
4579 @item
4580 The switches
4581 ^^@option{/DISTRIBUTION_STUBS=},^
4582 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4583 switches, and only one of them may appear in the command line.
4585 @item
4586 The switch @option{-gnat-p} may not be combined with any other switch.
4588 @ifclear vms
4589 @item
4590 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4591 switch), then all further characters in the switch are interpreted
4592 as style modifiers (see description of @option{-gnaty}).
4594 @item
4595 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4596 switch), then all further characters in the switch are interpreted
4597 as debug flags (see description of @option{-gnatd}).
4599 @item
4600 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4601 switch), then all further characters in the switch are interpreted
4602 as warning mode modifiers (see description of @option{-gnatw}).
4604 @item
4605 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4606 switch), then all further characters in the switch are interpreted
4607 as validity checking options (@pxref{Validity Checking}).
4609 @item
4610 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4611 a combined list of options.
4612 @end ifclear
4613 @end itemize
4615 @node Output and Error Message Control
4616 @subsection Output and Error Message Control
4617 @findex stderr
4619 @noindent
4620 The standard default format for error messages is called ``brief format''.
4621 Brief format messages are written to @file{stderr} (the standard error
4622 file) and have the following form:
4624 @smallexample
4625 e.adb:3:04: Incorrect spelling of keyword "function"
4626 e.adb:4:20: ";" should be "is"
4627 @end smallexample
4629 @noindent
4630 The first integer after the file name is the line number in the file,
4631 and the second integer is the column number within the line.
4632 @ifclear vms
4633 @code{GPS} can parse the error messages
4634 and point to the referenced character.
4635 @end ifclear
4636 The following switches provide control over the error message
4637 format:
4639 @table @option
4640 @c !sort!
4641 @item -gnatv
4642 @cindex @option{-gnatv} (@command{gcc})
4643 @findex stdout
4644 @ifclear vms
4645 The v stands for verbose.
4646 @end ifclear
4647 The effect of this setting is to write long-format error
4648 messages to @file{stdout} (the standard output file.
4649 The same program compiled with the
4650 @option{-gnatv} switch would generate:
4652 @smallexample
4653 @cartouche
4654 3. funcion X (Q : Integer)
4655    |
4656 >>> Incorrect spelling of keyword "function"
4657 4. return Integer;
4658                  |
4659 >>> ";" should be "is"
4660 @end cartouche
4661 @end smallexample
4663 @noindent
4664 The vertical bar indicates the location of the error, and the @samp{>>>}
4665 prefix can be used to search for error messages. When this switch is
4666 used the only source lines output are those with errors.
4668 @item -gnatl
4669 @cindex @option{-gnatl} (@command{gcc})
4670 @ifclear vms
4671 The @code{l} stands for list.
4672 @end ifclear
4673 This switch causes a full listing of
4674 the file to be generated. In the case where a body is
4675 compiled, the corresponding spec is also listed, along
4676 with any subunits. Typical output from compiling a package
4677 body @file{p.adb} might look like:
4679 @smallexample @c ada
4680 @cartouche
4681  Compiling: p.adb
4683      1. package body p is
4684      2.    procedure a;
4685      3.    procedure a is separate;
4686      4. begin
4687      5.    null
4688                |
4689         >>> missing ";"
4691      6. end;
4693 Compiling: p.ads
4695      1. package p is
4696      2.    pragma Elaborate_Body
4697                                 |
4698         >>> missing ";"
4700      3. end p;
4702 Compiling: p-a.adb
4704      1. separate p
4705                 |
4706         >>> missing "("
4708      2. procedure a is
4709      3. begin
4710      4.    null
4711                |
4712         >>> missing ";"
4714      5. end;
4715 @end cartouche
4716 @end smallexample
4718 @noindent
4719 @findex stderr
4720 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4721 standard output is redirected, a brief summary is written to
4722 @file{stderr} (standard error) giving the number of error messages and
4723 warning messages generated.
4725 @item ^-gnatl^/OUTPUT_FILE^=file
4726 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4727 This has the same effect as @option{-gnatl} except that the output is
4728 written to a file instead of to standard output. If the given name
4729 @file{fname} does not start with a period, then it is the full name
4730 of the file to be written. If @file{fname} is an extension, it is
4731 appended to the name of the file being compiled. For example, if
4732 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4733 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4735 @item -gnatU
4736 @cindex @option{-gnatU} (@command{gcc})
4737 This switch forces all error messages to be preceded by the unique
4738 string ``error:''. This means that error messages take a few more
4739 characters in space, but allows easy searching for and identification
4740 of error messages.
4742 @item -gnatb
4743 @cindex @option{-gnatb} (@command{gcc})
4744 @ifclear vms
4745 The @code{b} stands for brief.
4746 @end ifclear
4747 This switch causes GNAT to generate the
4748 brief format error messages to @file{stderr} (the standard error
4749 file) as well as the verbose
4750 format message or full listing (which as usual is written to
4751 @file{stdout} (the standard output file).
4753 @item -gnatm=@var{n}
4754 @cindex @option{-gnatm} (@command{gcc})
4755 @ifclear vms
4756 The @code{m} stands for maximum.
4757 @end ifclear
4758 @var{n} is a decimal integer in the
4759 range of 1 to 999999 and limits the number of error or warning
4760 messages to be generated. For example, using
4761 @option{-gnatm2} might yield
4763 @smallexample
4764 e.adb:3:04: Incorrect spelling of keyword "function"
4765 e.adb:5:35: missing ".."
4766 fatal error: maximum number of errors detected
4767 compilation abandoned
4768 @end smallexample
4770 @noindent
4771 The default setting if
4772 no switch is given is 9999. If the number of warnings reaches this
4773 limit, then a message is output and further warnings are suppressed,
4774 but the compilation is continued. If the number of error messages
4775 reaches this limit, then a message is output and the compilation
4776 is abandoned. A value of zero means that no limit applies.
4778 @noindent
4779 Note that the equal sign is optional, so the switches
4780 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4782 @item -gnatf
4783 @cindex @option{-gnatf} (@command{gcc})
4784 @cindex Error messages, suppressing
4785 @ifclear vms
4786 The @code{f} stands for full.
4787 @end ifclear
4788 Normally, the compiler suppresses error messages that are likely to be
4789 redundant. This switch causes all error
4790 messages to be generated. In particular, in the case of
4791 references to undefined variables. If a given variable is referenced
4792 several times, the normal format of messages is
4793 @smallexample
4794 e.adb:7:07: "V" is undefined (more references follow)
4795 @end smallexample
4797 @noindent
4798 where the parenthetical comment warns that there are additional
4799 references to the variable @code{V}. Compiling the same program with the
4800 @option{-gnatf} switch yields
4802 @smallexample
4803 e.adb:7:07: "V" is undefined
4804 e.adb:8:07: "V" is undefined
4805 e.adb:8:12: "V" is undefined
4806 e.adb:8:16: "V" is undefined
4807 e.adb:9:07: "V" is undefined
4808 e.adb:9:12: "V" is undefined
4809 @end smallexample
4811 @noindent
4812 The @option{-gnatf} switch also generates additional information for
4813 some error messages.  Some examples are:
4815 @itemize @bullet
4816 @item
4817 Details on possibly non-portable unchecked conversion
4818 @item
4819 List possible interpretations for ambiguous calls
4820 @item
4821 Additional details on incorrect parameters
4822 @end itemize
4824 @item -gnatjnn
4825 @cindex @option{-gnatjnn} (@command{gcc})
4826 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4827 with continuation lines are treated as though the continuation lines were
4828 separate messages (and so a warning with two continuation lines counts as
4829 three warnings, and is listed as three separate messages).
4831 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4832 messages are output in a different manner. A message and all its continuation
4833 lines are treated as a unit, and count as only one warning or message in the
4834 statistics totals. Furthermore, the message is reformatted so that no line
4835 is longer than nn characters.
4837 @item -gnatq
4838 @cindex @option{-gnatq} (@command{gcc})
4839 @ifclear vms
4840 The @code{q} stands for quit (really ``don't quit'').
4841 @end ifclear
4842 In normal operation mode, the compiler first parses the program and
4843 determines if there are any syntax errors. If there are, appropriate
4844 error messages are generated and compilation is immediately terminated.
4845 This switch tells
4846 GNAT to continue with semantic analysis even if syntax errors have been
4847 found. This may enable the detection of more errors in a single run. On
4848 the other hand, the semantic analyzer is more likely to encounter some
4849 internal fatal error when given a syntactically invalid tree.
4851 @item -gnatQ
4852 @cindex @option{-gnatQ} (@command{gcc})
4853 In normal operation mode, the @file{ALI} file is not generated if any
4854 illegalities are detected in the program. The use of @option{-gnatQ} forces
4855 generation of the @file{ALI} file. This file is marked as being in
4856 error, so it cannot be used for binding purposes, but it does contain
4857 reasonably complete cross-reference information, and thus may be useful
4858 for use by tools (e.g., semantic browsing tools or integrated development
4859 environments) that are driven from the @file{ALI} file. This switch
4860 implies @option{-gnatq}, since the semantic phase must be run to get a
4861 meaningful ALI file.
4863 In addition, if @option{-gnatt} is also specified, then the tree file is
4864 generated even if there are illegalities. It may be useful in this case
4865 to also specify @option{-gnatq} to ensure that full semantic processing
4866 occurs. The resulting tree file can be processed by ASIS, for the purpose
4867 of providing partial information about illegal units, but if the error
4868 causes the tree to be badly malformed, then ASIS may crash during the
4869 analysis.
4871 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4872 being in error, @command{gnatmake} will attempt to recompile the source when it
4873 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4875 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4876 since ALI files are never generated if @option{-gnats} is set.
4878 @end table
4880 @node Warning Message Control
4881 @subsection Warning Message Control
4882 @cindex Warning messages
4883 @noindent
4884 In addition to error messages, which correspond to illegalities as defined
4885 in the Ada Reference Manual, the compiler detects two kinds of warning
4886 situations.
4888 First, the compiler considers some constructs suspicious and generates a
4889 warning message to alert you to a possible error. Second, if the
4890 compiler detects a situation that is sure to raise an exception at
4891 run time, it generates a warning message. The following shows an example
4892 of warning messages:
4893 @smallexample
4894 e.adb:4:24: warning: creation of object may raise Storage_Error
4895 e.adb:10:17: warning: static value out of range
4896 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4897 @end smallexample
4899 @noindent
4900 GNAT considers a large number of situations as appropriate
4901 for the generation of warning messages. As always, warnings are not
4902 definite indications of errors. For example, if you do an out-of-range
4903 assignment with the deliberate intention of raising a
4904 @code{Constraint_Error} exception, then the warning that may be
4905 issued does not indicate an error. Some of the situations for which GNAT
4906 issues warnings (at least some of the time) are given in the following
4907 list. This list is not complete, and new warnings are often added to
4908 subsequent versions of GNAT. The list is intended to give a general idea
4909 of the kinds of warnings that are generated.
4911 @itemize @bullet
4912 @item
4913 Possible infinitely recursive calls
4915 @item
4916 Out-of-range values being assigned
4918 @item
4919 Possible order of elaboration problems
4921 @item
4922 Assertions (pragma Assert) that are sure to fail
4924 @item
4925 Unreachable code
4927 @item
4928 Address clauses with possibly unaligned values, or where an attempt is
4929 made to overlay a smaller variable with a larger one.
4931 @item
4932 Fixed-point type declarations with a null range
4934 @item
4935 Direct_IO or Sequential_IO instantiated with a type that has access values
4937 @item
4938 Variables that are never assigned a value
4940 @item
4941 Variables that are referenced before being initialized
4943 @item
4944 Task entries with no corresponding @code{accept} statement
4946 @item
4947 Duplicate accepts for the same task entry in a @code{select}
4949 @item
4950 Objects that take too much storage
4952 @item
4953 Unchecked conversion between types of differing sizes
4955 @item
4956 Missing @code{return} statement along some execution path in a function
4958 @item
4959 Incorrect (unrecognized) pragmas
4961 @item
4962 Incorrect external names
4964 @item
4965 Allocation from empty storage pool
4967 @item
4968 Potentially blocking operation in protected type
4970 @item
4971 Suspicious parenthesization of expressions
4973 @item
4974 Mismatching bounds in an aggregate
4976 @item
4977 Attempt to return local value by reference
4979 @item
4980 Premature instantiation of a generic body
4982 @item
4983 Attempt to pack aliased components
4985 @item
4986 Out of bounds array subscripts
4988 @item
4989 Wrong length on string assignment
4991 @item
4992 Violations of style rules if style checking is enabled
4994 @item
4995 Unused @code{with} clauses
4997 @item
4998 @code{Bit_Order} usage that does not have any effect
5000 @item
5001 @code{Standard.Duration} used to resolve universal fixed expression
5003 @item
5004 Dereference of possibly null value
5006 @item
5007 Declaration that is likely to cause storage error
5009 @item
5010 Internal GNAT unit @code{with}'ed by application unit
5012 @item
5013 Values known to be out of range at compile time
5015 @item
5016 Unreferenced labels and variables
5018 @item
5019 Address overlays that could clobber memory
5021 @item
5022 Unexpected initialization when address clause present
5024 @item
5025 Bad alignment for address clause
5027 @item
5028 Useless type conversions
5030 @item
5031 Redundant assignment statements and other redundant constructs
5033 @item
5034 Useless exception handlers
5036 @item
5037 Accidental hiding of name by child unit
5039 @item
5040 Access before elaboration detected at compile time
5042 @item
5043 A range in a @code{for} loop that is known to be null or might be null
5045 @end itemize
5047 @noindent
5048 The following section lists compiler switches that are available
5049 to control the handling of warning messages. It is also possible
5050 to exercise much finer control over what warnings are issued and
5051 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5052 gnat_rm, GNAT Reference manual}.
5054 @table @option
5055 @c !sort!
5056 @item -gnatwa
5057 @emph{Activate most optional warnings.}
5058 @cindex @option{-gnatwa} (@command{gcc})
5059 This switch activates most optional warning messages.  See the remaining list
5060 in this section for details on optional warning messages that can be
5061 individually controlled.  The warnings that are not turned on by this
5062 switch are
5063 @option{-gnatwd} (implicit dereferencing),
5064 @option{-gnatwh} (hiding),
5065 @option{-gnatw.h} (holes (gaps) in record layouts)
5066 @option{-gnatwl} (elaboration warnings),
5067 @option{-gnatw.o} (warn on values set by out parameters ignored)
5068 and @option{-gnatwt} (tracking of deleted conditional code).
5069 All other optional warnings are turned on.
5071 @item -gnatwA
5072 @emph{Suppress all optional errors.}
5073 @cindex @option{-gnatwA} (@command{gcc})
5074 This switch suppresses all optional warning messages, see remaining list
5075 in this section for details on optional warning messages that can be
5076 individually controlled.
5078 @item -gnatw.a
5079 @emph{Activate warnings on failing assertions.}
5080 @cindex @option{-gnatw.a} (@command{gcc})
5081 @cindex Assert failures
5082 This switch activates warnings for assertions where the compiler can tell at
5083 compile time that the assertion will fail. Note that this warning is given
5084 even if assertions are disabled. The default is that such warnings are
5085 generated.
5087 @item -gnatw.A
5088 @emph{Suppress warnings on failing assertions.}
5089 @cindex @option{-gnatw.A} (@command{gcc})
5090 @cindex Assert failures
5091 This switch suppresses warnings for assertions where the compiler can tell at
5092 compile time that the assertion will fail.
5094 @item -gnatwb
5095 @emph{Activate warnings on bad fixed values.}
5096 @cindex @option{-gnatwb} (@command{gcc})
5097 @cindex Bad fixed values
5098 @cindex Fixed-point Small value
5099 @cindex Small value
5100 This switch activates warnings for static fixed-point expressions whose
5101 value is not an exact multiple of Small. Such values are implementation
5102 dependent, since an implementation is free to choose either of the multiples
5103 that surround the value. GNAT always chooses the closer one, but this is not
5104 required behavior, and it is better to specify a value that is an exact
5105 multiple, ensuring predictable execution. The default is that such warnings
5106 are not generated.
5108 @item -gnatwB
5109 @emph{Suppress warnings on bad fixed values.}
5110 @cindex @option{-gnatwB} (@command{gcc})
5111 This switch suppresses warnings for static fixed-point expressions whose
5112 value is not an exact multiple of Small.
5114 @item -gnatw.b
5115 @emph{Activate warnings on biased representation.}
5116 @cindex @option{-gnatw.b} (@command{gcc})
5117 @cindex Biased representation
5118 This switch activates warnings when a size clause, value size clause, component
5119 clause, or component size clause forces the use of biased representation for an
5120 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5121 to represent 10/11). The default is that such warnings are generated.
5123 @item -gnatw.B
5124 @emph{Suppress warnings on biased representation.}
5125 @cindex @option{-gnatwB} (@command{gcc})
5126 This switch suppresses warnings for representation clauses that force the use
5127 of biased representation.
5129 @item -gnatwc
5130 @emph{Activate warnings on conditionals.}
5131 @cindex @option{-gnatwc} (@command{gcc})
5132 @cindex Conditionals, constant
5133 This switch activates warnings for conditional expressions used in
5134 tests that are known to be True or False at compile time. The default
5135 is that such warnings are not generated.
5136 Note that this warning does
5137 not get issued for the use of boolean variables or constants whose
5138 values are known at compile time, since this is a standard technique
5139 for conditional compilation in Ada, and this would generate too many
5140 false positive warnings.
5142 This warning option also activates a special test for comparisons using
5143 the operators ``>='' and`` <=''.
5144 If the compiler can tell that only the equality condition is possible,
5145 then it will warn that the ``>'' or ``<'' part of the test
5146 is useless and that the operator could be replaced by ``=''.
5147 An example would be comparing a @code{Natural} variable <= 0.
5149 This warning option also generates warnings if
5150 one or both tests is optimized away in a membership test for integer
5151 values if the result can be determined at compile time. Range tests on
5152 enumeration types are not included, since it is common for such tests
5153 to include an end point.
5155 This warning can also be turned on using @option{-gnatwa}.
5157 @item -gnatwC
5158 @emph{Suppress warnings on conditionals.}
5159 @cindex @option{-gnatwC} (@command{gcc})
5160 This switch suppresses warnings for conditional expressions used in
5161 tests that are known to be True or False at compile time.
5163 @item -gnatw.c
5164 @emph{Activate warnings on missing component clauses.}
5165 @cindex @option{-gnatw.c} (@command{gcc})
5166 @cindex Component clause, missing
5167 This switch activates warnings for record components where a record
5168 representation clause is present and has component clauses for the
5169 majority, but not all, of the components. A warning is given for each
5170 component for which no component clause is present.
5172 This warning can also be turned on using @option{-gnatwa}.
5174 @item -gnatw.C
5175 @emph{Suppress warnings on missing component clauses.}
5176 @cindex @option{-gnatwC} (@command{gcc})
5177 This switch suppresses warnings for record components that are
5178 missing a component clause in the situation described above.
5180 @item -gnatwd
5181 @emph{Activate warnings on implicit dereferencing.}
5182 @cindex @option{-gnatwd} (@command{gcc})
5183 If this switch is set, then the use of a prefix of an access type
5184 in an indexed component, slice, or selected component without an
5185 explicit @code{.all} will generate a warning. With this warning
5186 enabled, access checks occur only at points where an explicit
5187 @code{.all} appears in the source code (assuming no warnings are
5188 generated as a result of this switch). The default is that such
5189 warnings are not generated.
5190 Note that @option{-gnatwa} does not affect the setting of
5191 this warning option.
5193 @item -gnatwD
5194 @emph{Suppress warnings on implicit dereferencing.}
5195 @cindex @option{-gnatwD} (@command{gcc})
5196 @cindex Implicit dereferencing
5197 @cindex Dereferencing, implicit
5198 This switch suppresses warnings for implicit dereferences in
5199 indexed components, slices, and selected components.
5201 @item -gnatwe
5202 @emph{Treat warnings and style checks as errors.}
5203 @cindex @option{-gnatwe} (@command{gcc})
5204 @cindex Warnings, treat as error
5205 This switch causes warning messages and style check messages to be
5206 treated as errors.
5207 The warning string still appears, but the warning messages are counted
5208 as errors, and prevent the generation of an object file. Note that this
5209 is the only -gnatw switch that affects the handling of style check messages.
5211 @item -gnatw.e
5212 @emph{Activate every optional warning}
5213 @cindex @option{-gnatw.e} (@command{gcc})
5214 @cindex Warnings, activate every optional warning
5215 This switch activates all optional warnings, including those which
5216 are not activated by @code{-gnatwa}.
5218 @item -gnatwf
5219 @emph{Activate warnings on unreferenced formals.}
5220 @cindex @option{-gnatwf} (@command{gcc})
5221 @cindex Formals, unreferenced
5222 This switch causes a warning to be generated if a formal parameter
5223 is not referenced in the body of the subprogram. This warning can
5224 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5225 default is that these warnings are not generated.
5227 @item -gnatwF
5228 @emph{Suppress warnings on unreferenced formals.}
5229 @cindex @option{-gnatwF} (@command{gcc})
5230 This switch suppresses warnings for unreferenced formal
5231 parameters. Note that the
5232 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5233 effect of warning on unreferenced entities other than subprogram
5234 formals.
5236 @item -gnatwg
5237 @emph{Activate warnings on unrecognized pragmas.}
5238 @cindex @option{-gnatwg} (@command{gcc})
5239 @cindex Pragmas, unrecognized
5240 This switch causes a warning to be generated if an unrecognized
5241 pragma is encountered. Apart from issuing this warning, the
5242 pragma is ignored and has no effect. This warning can
5243 also be turned on using @option{-gnatwa}. The default
5244 is that such warnings are issued (satisfying the Ada Reference
5245 Manual requirement that such warnings appear).
5247 @item -gnatwG
5248 @emph{Suppress warnings on unrecognized pragmas.}
5249 @cindex @option{-gnatwG} (@command{gcc})
5250 This switch suppresses warnings for unrecognized pragmas.
5252 @item -gnatwh
5253 @emph{Activate warnings on hiding.}
5254 @cindex @option{-gnatwh} (@command{gcc})
5255 @cindex Hiding of Declarations
5256 This switch activates warnings on hiding declarations.
5257 A declaration is considered hiding
5258 if it is for a non-overloadable entity, and it declares an entity with the
5259 same name as some other entity that is directly or use-visible. The default
5260 is that such warnings are not generated.
5261 Note that @option{-gnatwa} does not affect the setting of this warning option.
5263 @item -gnatwH
5264 @emph{Suppress warnings on hiding.}
5265 @cindex @option{-gnatwH} (@command{gcc})
5266 This switch suppresses warnings on hiding declarations.
5268 @item -gnatw.h
5269 @emph{Activate warnings on holes/gaps in records.}
5270 @cindex @option{-gnatw.h} (@command{gcc})
5271 @cindex Record Representation (gaps)
5272 This switch activates warnings on component clauses in record
5273 representation clauses that leave holes (gaps) in the record layout.
5274 If this warning option is active, then record representation clauses
5275 should specify a contiguous layout, adding unused fill fields if needed.
5276 Note that @option{-gnatwa} does not affect the setting of this warning option.
5278 @item -gnatw.H
5279 @emph{Suppress warnings on holes/gaps in records.}
5280 @cindex @option{-gnatw.H} (@command{gcc})
5281 This switch suppresses warnings on component clauses in record
5282 representation clauses that leave holes (haps) in the record layout.
5284 @item -gnatwi
5285 @emph{Activate warnings on implementation units.}
5286 @cindex @option{-gnatwi} (@command{gcc})
5287 This switch activates warnings for a @code{with} of an internal GNAT
5288 implementation unit, defined as any unit from the @code{Ada},
5289 @code{Interfaces}, @code{GNAT},
5290 ^^@code{DEC},^ or @code{System}
5291 hierarchies that is not
5292 documented in either the Ada Reference Manual or the GNAT
5293 Programmer's Reference Manual. Such units are intended only
5294 for internal implementation purposes and should not be @code{with}'ed
5295 by user programs. The default is that such warnings are generated
5296 This warning can also be turned on using @option{-gnatwa}.
5298 @item -gnatwI
5299 @emph{Disable warnings on implementation units.}
5300 @cindex @option{-gnatwI} (@command{gcc})
5301 This switch disables warnings for a @code{with} of an internal GNAT
5302 implementation unit.
5304 @item -gnatw.i
5305 @emph{Activate warnings on overlapping actuals.}
5306 @cindex @option{-gnatw.i} (@command{gcc})
5307 This switch enables a warning on statically detectable overlapping actuals in
5308 a subprogram call, when one of the actuals is an in-out parameter, and the
5309 types of the actuals are not by-copy types. The warning is off by default,
5310 and is not included under -gnatwa.
5312 @item -gnatw.I
5313 @emph{Disable warnings on overlapping actuals.}
5314 @cindex @option{-gnatw.I} (@command{gcc})
5315 This switch disables warnings on overlapping actuals in a call..
5317 @item -gnatwj
5318 @emph{Activate warnings on obsolescent features (Annex J).}
5319 @cindex @option{-gnatwj} (@command{gcc})
5320 @cindex Features, obsolescent
5321 @cindex Obsolescent features
5322 If this warning option is activated, then warnings are generated for
5323 calls to subprograms marked with @code{pragma Obsolescent} and
5324 for use of features in Annex J of the Ada Reference Manual. In the
5325 case of Annex J, not all features are flagged. In particular use
5326 of the renamed packages (like @code{Text_IO}) and use of package
5327 @code{ASCII} are not flagged, since these are very common and
5328 would generate many annoying positive warnings. The default is that
5329 such warnings are not generated. This warning is also turned on by
5330 the use of @option{-gnatwa}.
5332 In addition to the above cases, warnings are also generated for
5333 GNAT features that have been provided in past versions but which
5334 have been superseded (typically by features in the new Ada standard).
5335 For example, @code{pragma Ravenscar} will be flagged since its
5336 function is replaced by @code{pragma Profile(Ravenscar)}.
5338 Note that this warning option functions differently from the
5339 restriction @code{No_Obsolescent_Features} in two respects.
5340 First, the restriction applies only to annex J features.
5341 Second, the restriction does flag uses of package @code{ASCII}.
5343 @item -gnatwJ
5344 @emph{Suppress warnings on obsolescent features (Annex J).}
5345 @cindex @option{-gnatwJ} (@command{gcc})
5346 This switch disables warnings on use of obsolescent features.
5348 @item -gnatwk
5349 @emph{Activate warnings on variables that could be constants.}
5350 @cindex @option{-gnatwk} (@command{gcc})
5351 This switch activates warnings for variables that are initialized but
5352 never modified, and then could be declared constants. The default is that
5353 such warnings are not given.
5354 This warning can also be turned on using @option{-gnatwa}.
5356 @item -gnatwK
5357 @emph{Suppress warnings on variables that could be constants.}
5358 @cindex @option{-gnatwK} (@command{gcc})
5359 This switch disables warnings on variables that could be declared constants.
5361 @item -gnatwl
5362 @emph{Activate warnings for elaboration pragmas.}
5363 @cindex @option{-gnatwl} (@command{gcc})
5364 @cindex Elaboration, warnings
5365 This switch activates warnings on missing
5366 @code{Elaborate_All} and @code{Elaborate} pragmas.
5367 See the section in this guide on elaboration checking for details on
5368 when such pragmas should be used. In dynamic elaboration mode, this switch
5369 generations warnings about the need to add elaboration pragmas. Note however,
5370 that if you blindly follow these warnings, and add @code{Elaborate_All}
5371 warnings wherever they are recommended, you basically end up with the
5372 equivalent of the static elaboration model, which may not be what you want for
5373 legacy code for which the static model does not work.
5375 For the static model, the messages generated are labeled "info:" (for
5376 information messages). They are not warnings to add elaboration pragmas,
5377 merely informational messages showing what implicit elaboration pragmas
5378 have been added, for use in analyzing elaboration circularity problems.
5380 Warnings are also generated if you
5381 are using the static mode of elaboration, and a @code{pragma Elaborate}
5382 is encountered. The default is that such warnings
5383 are not generated.
5384 This warning is not automatically turned on by the use of @option{-gnatwa}.
5386 @item -gnatwL
5387 @emph{Suppress warnings for elaboration pragmas.}
5388 @cindex @option{-gnatwL} (@command{gcc})
5389 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5390 See the section in this guide on elaboration checking for details on
5391 when such pragmas should be used.
5393 @item -gnatwm
5394 @emph{Activate warnings on modified but unreferenced variables.}
5395 @cindex @option{-gnatwm} (@command{gcc})
5396 This switch activates warnings for variables that are assigned (using
5397 an initialization value or with one or more assignment statements) but
5398 whose value is never read. The warning is suppressed for volatile
5399 variables and also for variables that are renamings of other variables
5400 or for which an address clause is given.
5401 This warning can also be turned on using @option{-gnatwa}.
5402 The default is that these warnings are not given.
5404 @item -gnatwM
5405 @emph{Disable warnings on modified but unreferenced variables.}
5406 @cindex @option{-gnatwM} (@command{gcc})
5407 This switch disables warnings for variables that are assigned or
5408 initialized, but never read.
5410 @item -gnatw.m
5411 @emph{Activate warnings on suspicious modulus values.}
5412 @cindex @option{-gnatw.m} (@command{gcc})
5413 This switch activates warnings for modulus values that seem suspicious.
5414 The cases caught are where the size is the same as the modulus (e.g.
5415 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5416 with no size clause. The guess in both cases is that 2**x was intended
5417 rather than x. The default is that these warnings are given.
5419 @item -gnatw.M
5420 @emph{Disable warnings on suspicious modulus values.}
5421 @cindex @option{-gnatw.M} (@command{gcc})
5422 This switch disables warnings for suspicious modulus values.
5424 @item -gnatwn
5425 @emph{Set normal warnings mode.}
5426 @cindex @option{-gnatwn} (@command{gcc})
5427 This switch sets normal warning mode, in which enabled warnings are
5428 issued and treated as warnings rather than errors. This is the default
5429 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5430 an explicit @option{-gnatws} or
5431 @option{-gnatwe}. It also cancels the effect of the
5432 implicit @option{-gnatwe} that is activated by the
5433 use of @option{-gnatg}.
5435 @item -gnatwo
5436 @emph{Activate warnings on address clause overlays.}
5437 @cindex @option{-gnatwo} (@command{gcc})
5438 @cindex Address Clauses, warnings
5439 This switch activates warnings for possibly unintended initialization
5440 effects of defining address clauses that cause one variable to overlap
5441 another. The default is that such warnings are generated.
5442 This warning can also be turned on using @option{-gnatwa}.
5444 @item -gnatwO
5445 @emph{Suppress warnings on address clause overlays.}
5446 @cindex @option{-gnatwO} (@command{gcc})
5447 This switch suppresses warnings on possibly unintended initialization
5448 effects of defining address clauses that cause one variable to overlap
5449 another.
5451 @item -gnatw.o
5452 @emph{Activate warnings on modified but unreferenced out parameters.}
5453 @cindex @option{-gnatw.o} (@command{gcc})
5454 This switch activates warnings for variables that are modified by using
5455 them as actuals for a call to a procedure with an out mode formal, where
5456 the resulting assigned value is never read. It is applicable in the case
5457 where there is more than one out mode formal. If there is only one out
5458 mode formal, the warning is issued by default (controlled by -gnatwu).
5459 The warning is suppressed for volatile
5460 variables and also for variables that are renamings of other variables
5461 or for which an address clause is given.
5462 The default is that these warnings are not given. Note that this warning
5463 is not included in -gnatwa, it must be activated explicitly.
5465 @item -gnatw.O
5466 @emph{Disable warnings on modified but unreferenced out parameters.}
5467 @cindex @option{-gnatw.O} (@command{gcc})
5468 This switch suppresses warnings for variables that are modified by using
5469 them as actuals for a call to a procedure with an out mode formal, where
5470 the resulting assigned value is never read.
5472 @item -gnatwp
5473 @emph{Activate warnings on ineffective pragma Inlines.}
5474 @cindex @option{-gnatwp} (@command{gcc})
5475 @cindex Inlining, warnings
5476 This switch activates warnings for failure of front end inlining
5477 (activated by @option{-gnatN}) to inline a particular call. There are
5478 many reasons for not being able to inline a call, including most
5479 commonly that the call is too complex to inline. The default is
5480 that such warnings are not given.
5481 This warning can also be turned on using @option{-gnatwa}.
5482 Warnings on ineffective inlining by the gcc back-end can be activated
5483 separately, using the gcc switch -Winline.
5485 @item -gnatwP
5486 @emph{Suppress warnings on ineffective pragma Inlines.}
5487 @cindex @option{-gnatwP} (@command{gcc})
5488 This switch suppresses warnings on ineffective pragma Inlines. If the
5489 inlining mechanism cannot inline a call, it will simply ignore the
5490 request silently.
5492 @item -gnatw.p
5493 @emph{Activate warnings on parameter ordering.}
5494 @cindex @option{-gnatw.p} (@command{gcc})
5495 @cindex Parameter order, warnings
5496 This switch activates warnings for cases of suspicious parameter
5497 ordering when the list of arguments are all simple identifiers that
5498 match the names of the formals, but are in a different order. The
5499 warning is suppressed if any use of named parameter notation is used,
5500 so this is the appropriate way to suppress a false positive (and
5501 serves to emphasize that the "misordering" is deliberate). The
5502 default is
5503 that such warnings are not given.
5504 This warning can also be turned on using @option{-gnatwa}.
5506 @item -gnatw.P
5507 @emph{Suppress warnings on parameter ordering.}
5508 @cindex @option{-gnatw.P} (@command{gcc})
5509 This switch suppresses warnings on cases of suspicious parameter
5510 ordering.
5512 @item -gnatwq
5513 @emph{Activate warnings on questionable missing parentheses.}
5514 @cindex @option{-gnatwq} (@command{gcc})
5515 @cindex Parentheses, warnings
5516 This switch activates warnings for cases where parentheses are not used and
5517 the result is potential ambiguity from a readers point of view. For example
5518 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5519 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5520 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5521 follow the rule of always parenthesizing to make the association clear, and
5522 this warning switch warns if such parentheses are not present. The default
5523 is that these warnings are given.
5524 This warning can also be turned on using @option{-gnatwa}.
5526 @item -gnatwQ
5527 @emph{Suppress warnings on questionable missing parentheses.}
5528 @cindex @option{-gnatwQ} (@command{gcc})
5529 This switch suppresses warnings for cases where the association is not
5530 clear and the use of parentheses is preferred.
5532 @item -gnatwr
5533 @emph{Activate warnings on redundant constructs.}
5534 @cindex @option{-gnatwr} (@command{gcc})
5535 This switch activates warnings for redundant constructs. The following
5536 is the current list of constructs regarded as redundant:
5538 @itemize @bullet
5539 @item
5540 Assignment of an item to itself.
5541 @item
5542 Type conversion that converts an expression to its own type.
5543 @item
5544 Use of the attribute @code{Base} where @code{typ'Base} is the same
5545 as @code{typ}.
5546 @item
5547 Use of pragma @code{Pack} when all components are placed by a record
5548 representation clause.
5549 @item
5550 Exception handler containing only a reraise statement (raise with no
5551 operand) which has no effect.
5552 @item
5553 Use of the operator abs on an operand that is known at compile time
5554 to be non-negative
5555 @item
5556 Comparison of boolean expressions to an explicit True value.
5557 @end itemize
5559 This warning can also be turned on using @option{-gnatwa}.
5560 The default is that warnings for redundant constructs are not given.
5562 @item -gnatwR
5563 @emph{Suppress warnings on redundant constructs.}
5564 @cindex @option{-gnatwR} (@command{gcc})
5565 This switch suppresses warnings for redundant constructs.
5567 @item -gnatw.r
5568 @emph{Activate warnings for object renaming function.}
5569 @cindex @option{-gnatw.r} (@command{gcc})
5570 This switch activates warnings for an object renaming that renames a
5571 function call, which is equivalent to a constant declaration (as
5572 opposed to renaming the function itself).  The default is that these
5573 warnings are given.  This warning can also be turned on using
5574 @option{-gnatwa}.
5576 @item -gnatw.R
5577 @emph{Suppress warnings for object renaming function.}
5578 @cindex @option{-gnatwT} (@command{gcc})
5579 This switch suppresses warnings for object renaming function.
5581 @item -gnatws
5582 @emph{Suppress all warnings.}
5583 @cindex @option{-gnatws} (@command{gcc})
5584 This switch completely suppresses the
5585 output of all warning messages from the GNAT front end.
5586 Note that it does not suppress warnings from the @command{gcc} back end.
5587 To suppress these back end warnings as well, use the switch @option{-w}
5588 in addition to @option{-gnatws}. Also this switch has no effect on the
5589 handling of style check messages.
5591 @item -gnatw.s
5592 @emph{Activate warnings on overridden size clauses.}
5593 @cindex @option{-gnatw.s} (@command{gcc})
5594 @cindex Record Representation (component sizes)
5595 This switch activates warnings on component clauses in record
5596 representation clauses where the length given overrides that
5597 specified by an explicit size clause for the component type. A
5598 warning is similarly given in the array case if a specified
5599 component size overrides an explicit size clause for the array
5600 component type.
5601 Note that @option{-gnatwa} does not affect the setting of this warning option.
5603 @item -gnatw.S
5604 @emph{Suppress warnings on overriddebn size clauses.}
5605 @cindex @option{-gnatw.S} (@command{gcc})
5606 This switch suppresses warnings on component clauses in record
5607 representation clauses that override size clauses, and similar
5608 warnings when an array component size overrides a size clause.
5610 @item -gnatwt
5611 @emph{Activate warnings for tracking of deleted conditional code.}
5612 @cindex @option{-gnatwt} (@command{gcc})
5613 @cindex Deactivated code, warnings
5614 @cindex Deleted code, warnings
5615 This switch activates warnings for tracking of code in conditionals (IF and
5616 CASE statements) that is detected to be dead code which cannot be executed, and
5617 which is removed by the front end. This warning is off by default, and is not
5618 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5619 useful for detecting deactivated code in certified applications.
5621 @item -gnatwT
5622 @emph{Suppress warnings for tracking of deleted conditional code.}
5623 @cindex @option{-gnatwT} (@command{gcc})
5624 This switch suppresses warnings for tracking of deleted conditional code.
5626 @item -gnatwu
5627 @emph{Activate warnings on unused entities.}
5628 @cindex @option{-gnatwu} (@command{gcc})
5629 This switch activates warnings to be generated for entities that
5630 are declared but not referenced, and for units that are @code{with}'ed
5631 and not
5632 referenced. In the case of packages, a warning is also generated if
5633 no entities in the package are referenced. This means that if the package
5634 is referenced but the only references are in @code{use}
5635 clauses or @code{renames}
5636 declarations, a warning is still generated. A warning is also generated
5637 for a generic package that is @code{with}'ed but never instantiated.
5638 In the case where a package or subprogram body is compiled, and there
5639 is a @code{with} on the corresponding spec
5640 that is only referenced in the body,
5641 a warning is also generated, noting that the
5642 @code{with} can be moved to the body. The default is that
5643 such warnings are not generated.
5644 This switch also activates warnings on unreferenced formals
5645 (it includes the effect of @option{-gnatwf}).
5646 This warning can also be turned on using @option{-gnatwa}.
5648 @item -gnatwU
5649 @emph{Suppress warnings on unused entities.}
5650 @cindex @option{-gnatwU} (@command{gcc})
5651 This switch suppresses warnings for unused entities and packages.
5652 It also turns off warnings on unreferenced formals (and thus includes
5653 the effect of @option{-gnatwF}).
5655 @item -gnatw.u
5656 @emph{Activate warnings on unordered enumeration types.}
5657 @cindex @option{-gnatw.u} (@command{gcc})
5658 This switch causes enumeration types to be considered as conceptually
5659 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5660 The effect is to generate warnings in clients that use explicit comparisons
5661 or subranges, since these constructs both treat objects of the type as
5662 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5663 which the type is declared, or its body or subunits.) Please refer to
5664 the description of pragma @code{Ordered} in the
5665 @cite{@value{EDITION} Reference Manual} for further details.
5667 @item -gnatw.U
5668 @emph{Deactivate warnings on unordered enumeration types.}
5669 @cindex @option{-gnatw.U} (@command{gcc})
5670 This switch causes all enumeration types to be considered as ordered, so
5671 that no warnings are given for comparisons or subranges for any type.
5673 @item -gnatwv
5674 @emph{Activate warnings on unassigned variables.}
5675 @cindex @option{-gnatwv} (@command{gcc})
5676 @cindex Unassigned variable warnings
5677 This switch activates warnings for access to variables which
5678 may not be properly initialized. The default is that
5679 such warnings are generated.
5680 This warning can also be turned on using @option{-gnatwa}.
5682 @item -gnatwV
5683 @emph{Suppress warnings on unassigned variables.}
5684 @cindex @option{-gnatwV} (@command{gcc})
5685 This switch suppresses warnings for access to variables which
5686 may not be properly initialized.
5687 For variables of a composite type, the warning can also be suppressed in
5688 Ada 2005 by using a default initialization with a box. For example, if
5689 Table is an array of records whose components are only partially uninitialized,
5690 then the following code:
5692 @smallexample @c ada
5693    Tab : Table := (others => <>);
5694 @end smallexample
5696 will suppress warnings on subsequent statements that access components
5697 of variable Tab.
5699 @item -gnatww
5700 @emph{Activate warnings on wrong low bound assumption.}
5701 @cindex @option{-gnatww} (@command{gcc})
5702 @cindex String indexing warnings
5703 This switch activates warnings for indexing an unconstrained string parameter
5704 with a literal or S'Length. This is a case where the code is assuming that the
5705 low bound is one, which is in general not true (for example when a slice is
5706 passed). The default is that such warnings are generated.
5707 This warning can also be turned on using @option{-gnatwa}.
5709 @item -gnatwW
5710 @emph{Suppress warnings on wrong low bound assumption.}
5711 @cindex @option{-gnatwW} (@command{gcc})
5712 This switch suppresses warnings for indexing an unconstrained string parameter
5713 with a literal or S'Length. Note that this warning can also be suppressed
5714 in a particular case by adding an
5715 assertion that the lower bound is 1,
5716 as shown in the following example.
5718 @smallexample @c ada
5719    procedure K (S : String) is
5720       pragma Assert (S'First = 1);
5721       @dots{}
5722 @end smallexample
5724 @item -gnatw.w
5725 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5726 @cindex @option{-gnatw.w} (@command{gcc})
5727 @cindex Warnings Off control
5728 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5729 where either the pragma is entirely useless (because it suppresses no
5730 warnings), or it could be replaced by @code{pragma Unreferenced} or
5731 @code{pragma Unmodified}.The default is that these warnings are not given.
5732 Note that this warning is not included in -gnatwa, it must be
5733 activated explicitly.
5735 @item -gnatw.W
5736 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5737 @cindex @option{-gnatw.W} (@command{gcc})
5738 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5740 @item -gnatwx
5741 @emph{Activate warnings on Export/Import pragmas.}
5742 @cindex @option{-gnatwx} (@command{gcc})
5743 @cindex Export/Import pragma warnings
5744 This switch activates warnings on Export/Import pragmas when
5745 the compiler detects a possible conflict between the Ada and
5746 foreign language calling sequences. For example, the use of
5747 default parameters in a convention C procedure is dubious
5748 because the C compiler cannot supply the proper default, so
5749 a warning is issued. The default is that such warnings are
5750 generated.
5751 This warning can also be turned on using @option{-gnatwa}.
5753 @item -gnatwX
5754 @emph{Suppress warnings on Export/Import pragmas.}
5755 @cindex @option{-gnatwX} (@command{gcc})
5756 This switch suppresses warnings on Export/Import pragmas.
5757 The sense of this is that you are telling the compiler that
5758 you know what you are doing in writing the pragma, and it
5759 should not complain at you.
5761 @item -gnatw.x
5762 @emph{Activate warnings for No_Exception_Propagation mode.}
5763 @cindex @option{-gnatwm} (@command{gcc})
5764 This switch activates warnings for exception usage when pragma Restrictions
5765 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5766 explicit exception raises which are not covered by a local handler, and for
5767 exception handlers which do not cover a local raise. The default is that these
5768 warnings are not given.
5770 @item -gnatw.X
5771 @emph{Disable warnings for No_Exception_Propagation mode.}
5772 This switch disables warnings for exception usage when pragma Restrictions
5773 (No_Exception_Propagation) is in effect.
5775 @item -gnatwy
5776 @emph{Activate warnings for Ada 2005 compatibility issues.}
5777 @cindex @option{-gnatwy} (@command{gcc})
5778 @cindex Ada 2005 compatibility issues warnings
5779 For the most part Ada 2005 is upwards compatible with Ada 95,
5780 but there are some exceptions (for example the fact that
5781 @code{interface} is now a reserved word in Ada 2005). This
5782 switch activates several warnings to help in identifying
5783 and correcting such incompatibilities. The default is that
5784 these warnings are generated. Note that at one point Ada 2005
5785 was called Ada 0Y, hence the choice of character.
5786 This warning can also be turned on using @option{-gnatwa}.
5788 @item -gnatwY
5789 @emph{Disable warnings for Ada 2005 compatibility issues.}
5790 @cindex @option{-gnatwY} (@command{gcc})
5791 @cindex Ada 2005 compatibility issues warnings
5792 This switch suppresses several warnings intended to help in identifying
5793 incompatibilities between Ada 95 and Ada 2005.
5795 @item -gnatwz
5796 @emph{Activate warnings on unchecked conversions.}
5797 @cindex @option{-gnatwz} (@command{gcc})
5798 @cindex Unchecked_Conversion warnings
5799 This switch activates warnings for unchecked conversions
5800 where the types are known at compile time to have different
5801 sizes. The default
5802 is that such warnings are generated. Warnings are also
5803 generated for subprogram pointers with different conventions,
5804 and, on VMS only, for data pointers with different conventions.
5805 This warning can also be turned on using @option{-gnatwa}.
5807 @item -gnatwZ
5808 @emph{Suppress warnings on unchecked conversions.}
5809 @cindex @option{-gnatwZ} (@command{gcc})
5810 This switch suppresses warnings for unchecked conversions
5811 where the types are known at compile time to have different
5812 sizes or conventions.
5814 @item ^-Wunused^WARNINGS=UNUSED^
5815 @cindex @option{-Wunused}
5816 The warnings controlled by the @option{-gnatw} switch are generated by
5817 the front end of the compiler. The @option{GCC} back end can provide
5818 additional warnings and they are controlled by the @option{-W} switch.
5819 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5820 warnings for entities that are declared but not referenced.
5822 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5823 @cindex @option{-Wuninitialized}
5824 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5825 the back end warning for uninitialized variables. This switch must be
5826 used in conjunction with an optimization level greater than zero.
5828 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5829 @cindex @option{-Wall}
5830 This switch enables all the above warnings from the @option{GCC} back end.
5831 The code generator detects a number of warning situations that are missed
5832 by the @option{GNAT} front end, and this switch can be used to activate them.
5833 The use of this switch also sets the default front end warning mode to
5834 @option{-gnatwa}, that is, most front end warnings activated as well.
5836 @item ^-w^/NO_BACK_END_WARNINGS^
5837 @cindex @option{-w}
5838 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5839 The use of this switch also sets the default front end warning mode to
5840 @option{-gnatws}, that is, front end warnings suppressed as well.
5842 @end table
5844 @noindent
5845 @ifclear vms
5846 A string of warning parameters can be used in the same parameter. For example:
5848 @smallexample
5849 -gnatwaLe
5850 @end smallexample
5852 @noindent
5853 will turn on all optional warnings except for elaboration pragma warnings,
5854 and also specify that warnings should be treated as errors.
5855 @end ifclear
5856 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5858 @table @option
5859 @c !sort!
5860 @item -gnatwC
5861 @item -gnatwD
5862 @item -gnatwF
5863 @item -gnatwg
5864 @item -gnatwH
5865 @item -gnatwi
5866 @item -gnatwJ
5867 @item -gnatwK
5868 @item -gnatwL
5869 @item -gnatwM
5870 @item -gnatwn
5871 @item -gnatwo
5872 @item -gnatwP
5873 @item -gnatwR
5874 @item -gnatwU
5875 @item -gnatwv
5876 @item -gnatwz
5877 @item -gnatwx
5879 @end table
5881 @node Debugging and Assertion Control
5882 @subsection Debugging and Assertion Control
5884 @table @option
5885 @item -gnata
5886 @cindex @option{-gnata} (@command{gcc})
5887 @findex Assert
5888 @findex Debug
5889 @cindex Assertions
5891 @noindent
5892 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5893 are ignored. This switch, where @samp{a} stands for assert, causes
5894 @code{Assert} and @code{Debug} pragmas to be activated.
5896 The pragmas have the form:
5898 @smallexample
5899 @cartouche
5900    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5901                       @var{static-string-expression}@r{]})
5902    @b{pragma} Debug (@var{procedure call})
5903 @end cartouche
5904 @end smallexample
5906 @noindent
5907 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5908 If the result is @code{True}, the pragma has no effect (other than
5909 possible side effects from evaluating the expression). If the result is
5910 @code{False}, the exception @code{Assert_Failure} declared in the package
5911 @code{System.Assertions} is
5912 raised (passing @var{static-string-expression}, if present, as the
5913 message associated with the exception). If no string expression is
5914 given the default is a string giving the file name and line number
5915 of the pragma.
5917 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5918 @code{pragma Debug} may appear within a declaration sequence, allowing
5919 debugging procedures to be called between declarations.
5921 @ifset vms
5922 @item /DEBUG@r{[}=debug-level@r{]}
5923 @itemx  /NODEBUG
5924 Specifies how much debugging information is to be included in
5925 the resulting object file where 'debug-level' is one of the following:
5926 @table @code
5927 @item   TRACEBACK
5928 Include both debugger symbol records and traceback
5929 the object file.
5930 This is the default setting.
5931 @item   ALL
5932 Include both debugger symbol records and traceback in
5933 object file.
5934 @item   NONE
5935 Excludes both debugger symbol records and traceback
5936 the object file. Same as /NODEBUG.
5937 @item   SYMBOLS
5938 Includes only debugger symbol records in the object
5939 file. Note that this doesn't include traceback information.
5940 @end table
5941 @end ifset
5942 @end table
5944 @node Validity Checking
5945 @subsection Validity Checking
5946 @findex Validity Checking
5948 @noindent
5949 The Ada Reference Manual defines the concept of invalid values (see
5950 RM 13.9.1). The primary source of invalid values is uninitialized
5951 variables. A scalar variable that is left uninitialized may contain
5952 an invalid value; the concept of invalid does not apply to access or
5953 composite types.
5955 It is an error to read an invalid value, but the RM does not require
5956 run-time checks to detect such errors, except for some minimal
5957 checking to prevent erroneous execution (i.e. unpredictable
5958 behavior). This corresponds to the @option{-gnatVd} switch below,
5959 which is the default. For example, by default, if the expression of a
5960 case statement is invalid, it will raise Constraint_Error rather than
5961 causing a wild jump, and if an array index on the left-hand side of an
5962 assignment is invalid, it will raise Constraint_Error rather than
5963 overwriting an arbitrary memory location.
5965 The @option{-gnatVa} may be used to enable additional validity checks,
5966 which are not required by the RM. These checks are often very
5967 expensive (which is why the RM does not require them). These checks
5968 are useful in tracking down uninitialized variables, but they are
5969 not usually recommended for production builds.
5971 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5972 control; you can enable whichever validity checks you desire. However,
5973 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5974 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5975 sufficient for non-debugging use.
5977 The @option{-gnatB} switch tells the compiler to assume that all
5978 values are valid (that is, within their declared subtype range)
5979 except in the context of a use of the Valid attribute. This means
5980 the compiler can generate more efficient code, since the range
5981 of values is better known at compile time. However, an uninitialized
5982 variable can cause wild jumps and memory corruption in this mode.
5984 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5985 checking mode as described below.
5986 @ifclear vms
5987 The @code{x} argument is a string of letters that
5988 indicate validity checks that are performed or not performed in addition
5989 to the default checks required by Ada as described above.
5990 @end ifclear
5991 @ifset vms
5992 The options allowed for this qualifier
5993 indicate validity checks that are performed or not performed in addition
5994 to the default checks required by Ada as described above.
5995 @end ifset
5997 @table @option
5998 @c !sort!
5999 @item -gnatVa
6000 @emph{All validity checks.}
6001 @cindex @option{-gnatVa} (@command{gcc})
6002 All validity checks are turned on.
6003 @ifclear vms
6004 That is, @option{-gnatVa} is
6005 equivalent to @option{gnatVcdfimorst}.
6006 @end ifclear
6008 @item -gnatVc
6009 @emph{Validity checks for copies.}
6010 @cindex @option{-gnatVc} (@command{gcc})
6011 The right hand side of assignments, and the initializing values of
6012 object declarations are validity checked.
6014 @item -gnatVd
6015 @emph{Default (RM) validity checks.}
6016 @cindex @option{-gnatVd} (@command{gcc})
6017 Some validity checks are done by default following normal Ada semantics
6018 (RM 13.9.1 (9-11)).
6019 A check is done in case statements that the expression is within the range
6020 of the subtype. If it is not, Constraint_Error is raised.
6021 For assignments to array components, a check is done that the expression used
6022 as index is within the range. If it is not, Constraint_Error is raised.
6023 Both these validity checks may be turned off using switch @option{-gnatVD}.
6024 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6025 switch @option{-gnatVd} will leave the checks turned on.
6026 Switch @option{-gnatVD} should be used only if you are sure that all such
6027 expressions have valid values. If you use this switch and invalid values
6028 are present, then the program is erroneous, and wild jumps or memory
6029 overwriting may occur.
6031 @item -gnatVe
6032 @emph{Validity checks for elementary components.}
6033 @cindex @option{-gnatVe} (@command{gcc})
6034 In the absence of this switch, assignments to record or array components are
6035 not validity checked, even if validity checks for assignments generally
6036 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6037 require valid data, but assignment of individual components does. So for
6038 example, there is a difference between copying the elements of an array with a
6039 slice assignment, compared to assigning element by element in a loop. This
6040 switch allows you to turn off validity checking for components, even when they
6041 are assigned component by component.
6043 @item -gnatVf
6044 @emph{Validity checks for floating-point values.}
6045 @cindex @option{-gnatVf} (@command{gcc})
6046 In the absence of this switch, validity checking occurs only for discrete
6047 values. If @option{-gnatVf} is specified, then validity checking also applies
6048 for floating-point values, and NaNs and infinities are considered invalid,
6049 as well as out of range values for constrained types. Note that this means
6050 that standard IEEE infinity mode is not allowed. The exact contexts
6051 in which floating-point values are checked depends on the setting of other
6052 options. For example,
6053 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6054 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6055 (the order does not matter) specifies that floating-point parameters of mode
6056 @code{in} should be validity checked.
6058 @item -gnatVi
6059 @emph{Validity checks for @code{in} mode parameters}
6060 @cindex @option{-gnatVi} (@command{gcc})
6061 Arguments for parameters of mode @code{in} are validity checked in function
6062 and procedure calls at the point of call.
6064 @item -gnatVm
6065 @emph{Validity checks for @code{in out} mode parameters.}
6066 @cindex @option{-gnatVm} (@command{gcc})
6067 Arguments for parameters of mode @code{in out} are validity checked in
6068 procedure calls at the point of call. The @code{'m'} here stands for
6069 modify, since this concerns parameters that can be modified by the call.
6070 Note that there is no specific option to test @code{out} parameters,
6071 but any reference within the subprogram will be tested in the usual
6072 manner, and if an invalid value is copied back, any reference to it
6073 will be subject to validity checking.
6075 @item -gnatVn
6076 @emph{No validity checks.}
6077 @cindex @option{-gnatVn} (@command{gcc})
6078 This switch turns off all validity checking, including the default checking
6079 for case statements and left hand side subscripts. Note that the use of
6080 the switch @option{-gnatp} suppresses all run-time checks, including
6081 validity checks, and thus implies @option{-gnatVn}. When this switch
6082 is used, it cancels any other @option{-gnatV} previously issued.
6084 @item -gnatVo
6085 @emph{Validity checks for operator and attribute operands.}
6086 @cindex @option{-gnatVo} (@command{gcc})
6087 Arguments for predefined operators and attributes are validity checked.
6088 This includes all operators in package @code{Standard},
6089 the shift operators defined as intrinsic in package @code{Interfaces}
6090 and operands for attributes such as @code{Pos}. Checks are also made
6091 on individual component values for composite comparisons, and on the
6092 expressions in type conversions and qualified expressions. Checks are
6093 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6095 @item -gnatVp
6096 @emph{Validity checks for parameters.}
6097 @cindex @option{-gnatVp} (@command{gcc})
6098 This controls the treatment of parameters within a subprogram (as opposed
6099 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6100 of parameters on a call. If either of these call options is used, then
6101 normally an assumption is made within a subprogram that the input arguments
6102 have been validity checking at the point of call, and do not need checking
6103 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6104 is not made, and parameters are not assumed to be valid, so their validity
6105 will be checked (or rechecked) within the subprogram.
6107 @item -gnatVr
6108 @emph{Validity checks for function returns.}
6109 @cindex @option{-gnatVr} (@command{gcc})
6110 The expression in @code{return} statements in functions is validity
6111 checked.
6113 @item -gnatVs
6114 @emph{Validity checks for subscripts.}
6115 @cindex @option{-gnatVs} (@command{gcc})
6116 All subscripts expressions are checked for validity, whether they appear
6117 on the right side or left side (in default mode only left side subscripts
6118 are validity checked).
6120 @item -gnatVt
6121 @emph{Validity checks for tests.}
6122 @cindex @option{-gnatVt} (@command{gcc})
6123 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6124 statements are checked, as well as guard expressions in entry calls.
6126 @end table
6128 @noindent
6129 The @option{-gnatV} switch may be followed by
6130 ^a string of letters^a list of options^
6131 to turn on a series of validity checking options.
6132 For example,
6133 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6134 specifies that in addition to the default validity checking, copies and
6135 function return expressions are to be validity checked.
6136 In order to make it easier
6137 to specify the desired combination of effects,
6138 @ifclear vms
6139 the upper case letters @code{CDFIMORST} may
6140 be used to turn off the corresponding lower case option.
6141 @end ifclear
6142 @ifset vms
6143 the prefix @code{NO} on an option turns off the corresponding validity
6144 checking:
6145 @itemize @bullet
6146 @item @code{NOCOPIES}
6147 @item @code{NODEFAULT}
6148 @item @code{NOFLOATS}
6149 @item @code{NOIN_PARAMS}
6150 @item @code{NOMOD_PARAMS}
6151 @item @code{NOOPERANDS}
6152 @item @code{NORETURNS}
6153 @item @code{NOSUBSCRIPTS}
6154 @item @code{NOTESTS}
6155 @end itemize
6156 @end ifset
6157 Thus
6158 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6159 turns on all validity checking options except for
6160 checking of @code{@b{in out}} procedure arguments.
6162 The specification of additional validity checking generates extra code (and
6163 in the case of @option{-gnatVa} the code expansion can be substantial).
6164 However, these additional checks can be very useful in detecting
6165 uninitialized variables, incorrect use of unchecked conversion, and other
6166 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6167 is useful in conjunction with the extra validity checking, since this
6168 ensures that wherever possible uninitialized variables have invalid values.
6170 See also the pragma @code{Validity_Checks} which allows modification of
6171 the validity checking mode at the program source level, and also allows for
6172 temporary disabling of validity checks.
6174 @node Style Checking
6175 @subsection Style Checking
6176 @findex Style checking
6178 @noindent
6179 The @option{-gnaty^x^(option,option,@dots{})^} switch
6180 @cindex @option{-gnaty} (@command{gcc})
6181 causes the compiler to
6182 enforce specified style rules. A limited set of style rules has been used
6183 in writing the GNAT sources themselves. This switch allows user programs
6184 to activate all or some of these checks. If the source program fails a
6185 specified style check, an appropriate message is given, preceded by
6186 the character sequence ``(style)''. This message does not prevent
6187 successful compilation (unless the @option{-gnatwe} switch is used).
6189 Note that this is by no means intended to be a general facility for
6190 checking arbitrary coding standards. It is simply an embedding of the
6191 style rules we have chosen for the GNAT sources. If you are starting
6192 a project which does not have established style standards, you may
6193 find it useful to adopt the entire set of GNAT coding standards, or
6194 some subset of them. If you already have an established set of coding
6195 standards, then it may be that selected style checking options do
6196 indeed correspond to choices you have made, but for general checking
6197 of an existing set of coding rules, you should look to the gnatcheck
6198 tool, which is designed for that purpose.
6200 @ifset vms
6201 @code{(option,option,@dots{})} is a sequence of keywords
6202 @end ifset
6203 @ifclear vms
6204 The string @var{x} is a sequence of letters or digits
6205 @end ifclear
6206 indicating the particular style
6207 checks to be performed. The following checks are defined:
6209 @table @option
6210 @c !sort!
6211 @item 0-9
6212 @emph{Specify indentation level.}
6213 If a digit from 1-9 appears
6214 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6215 then proper indentation is checked, with the digit indicating the
6216 indentation level required. A value of zero turns off this style check.
6217 The general style of required indentation is as specified by
6218 the examples in the Ada Reference Manual. Full line comments must be
6219 aligned with the @code{--} starting on a column that is a multiple of
6220 the alignment level, or they may be aligned the same way as the following
6221 non-blank line (this is useful when full line comments appear in the middle
6222 of a statement.
6224 @item ^a^ATTRIBUTE^
6225 @emph{Check attribute casing.}
6226 Attribute names, including the case of keywords such as @code{digits}
6227 used as attributes names, must be written in mixed case, that is, the
6228 initial letter and any letter following an underscore must be uppercase.
6229 All other letters must be lowercase.
6231 @item ^A^ARRAY_INDEXES^
6232 @emph{Use of array index numbers in array attributes.}
6233 When using the array attributes First, Last, Range,
6234 or Length, the index number must be omitted for one-dimensional arrays
6235 and is required for multi-dimensional arrays.
6237 @item ^b^BLANKS^
6238 @emph{Blanks not allowed at statement end.}
6239 Trailing blanks are not allowed at the end of statements. The purpose of this
6240 rule, together with h (no horizontal tabs), is to enforce a canonical format
6241 for the use of blanks to separate source tokens.
6243 @item ^B^BOOLEAN_OPERATORS^
6244 @emph{Check Boolean operators.}
6245 The use of AND/OR operators is not permitted except in the cases of modular
6246 operands, array operands, and simple stand-alone boolean variables or
6247 boolean constants. In all other cases AND THEN/OR ELSE are required.
6249 @item ^c^COMMENTS^
6250 @emph{Check comments.}
6251 Comments must meet the following set of rules:
6253 @itemize @bullet
6255 @item
6256 The ``@code{--}'' that starts the column must either start in column one,
6257 or else at least one blank must precede this sequence.
6259 @item
6260 Comments that follow other tokens on a line must have at least one blank
6261 following the ``@code{--}'' at the start of the comment.
6263 @item
6264 Full line comments must have at least two blanks following the
6265 ``@code{--}'' that starts the comment, with the following exceptions.
6267 @item
6268 A line consisting only of the ``@code{--}'' characters, possibly preceded
6269 by blanks is permitted.
6271 @item
6272 A comment starting with ``@code{--x}'' where @code{x} is a special character
6273 is permitted.
6274 This allows proper processing of the output generated by specialized tools
6275 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6276 annotation
6277 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6278 special character is defined as being in one of the ASCII ranges
6279 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6280 Note that this usage is not permitted
6281 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6283 @item
6284 A line consisting entirely of minus signs, possibly preceded by blanks, is
6285 permitted. This allows the construction of box comments where lines of minus
6286 signs are used to form the top and bottom of the box.
6288 @item
6289 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6290 least one blank follows the initial ``@code{--}''. Together with the preceding
6291 rule, this allows the construction of box comments, as shown in the following
6292 example:
6293 @smallexample
6294 ---------------------------
6295 -- This is a box comment --
6296 -- with two text lines.  --
6297 ---------------------------
6298 @end smallexample
6299 @end itemize
6301 @item ^d^DOS_LINE_ENDINGS^
6302 @emph{Check no DOS line terminators present.}
6303 All lines must be terminated by a single ASCII.LF
6304 character (in particular the DOS line terminator sequence CR/LF is not
6305 allowed).
6307 @item ^e^END^
6308 @emph{Check end/exit labels.}
6309 Optional labels on @code{end} statements ending subprograms and on
6310 @code{exit} statements exiting named loops, are required to be present.
6312 @item ^f^VTABS^
6313 @emph{No form feeds or vertical tabs.}
6314 Neither form feeds nor vertical tab characters are permitted
6315 in the source text.
6317 @item ^g^GNAT^
6318 @emph{GNAT style mode}
6319 The set of style check switches is set to match that used by the GNAT sources.
6320 This may be useful when developing code that is eventually intended to be
6321 incorporated into GNAT. For further details, see GNAT sources.
6323 @item ^h^HTABS^
6324 @emph{No horizontal tabs.}
6325 Horizontal tab characters are not permitted in the source text.
6326 Together with the b (no blanks at end of line) check, this
6327 enforces a canonical form for the use of blanks to separate
6328 source tokens.
6330 @item ^i^IF_THEN^
6331 @emph{Check if-then layout.}
6332 The keyword @code{then} must appear either on the same
6333 line as corresponding @code{if}, or on a line on its own, lined
6334 up under the @code{if} with at least one non-blank line in between
6335 containing all or part of the condition to be tested.
6337 @item ^I^IN_MODE^
6338 @emph{check mode IN keywords}
6339 Mode @code{in} (the default mode) is not
6340 allowed to be given explicitly. @code{in out} is fine,
6341 but not @code{in} on its own.
6343 @item ^k^KEYWORD^
6344 @emph{Check keyword casing.}
6345 All keywords must be in lower case (with the exception of keywords
6346 such as @code{digits} used as attribute names to which this check
6347 does not apply).
6349 @item ^l^LAYOUT^
6350 @emph{Check layout.}
6351 Layout of statement and declaration constructs must follow the
6352 recommendations in the Ada Reference Manual, as indicated by the
6353 form of the syntax rules. For example an @code{else} keyword must
6354 be lined up with the corresponding @code{if} keyword.
6356 There are two respects in which the style rule enforced by this check
6357 option are more liberal than those in the Ada Reference Manual. First
6358 in the case of record declarations, it is permissible to put the
6359 @code{record} keyword on the same line as the @code{type} keyword, and
6360 then the @code{end} in @code{end record} must line up under @code{type}.
6361 This is also permitted when the type declaration is split on two lines.
6362 For example, any of the following three layouts is acceptable:
6364 @smallexample @c ada
6365 @cartouche
6366 type q is record
6367    a : integer;
6368    b : integer;
6369 end record;
6371 type q is
6372    record
6373       a : integer;
6374       b : integer;
6375    end record;
6377 type q is
6378    record
6379       a : integer;
6380       b : integer;
6381 end record;
6383 @end cartouche
6384 @end smallexample
6386 @noindent
6387 Second, in the case of a block statement, a permitted alternative
6388 is to put the block label on the same line as the @code{declare} or
6389 @code{begin} keyword, and then line the @code{end} keyword up under
6390 the block label. For example both the following are permitted:
6392 @smallexample @c ada
6393 @cartouche
6394 Block : declare
6395    A : Integer := 3;
6396 begin
6397    Proc (A, A);
6398 end Block;
6400 Block :
6401    declare
6402       A : Integer := 3;
6403    begin
6404       Proc (A, A);
6405    end Block;
6406 @end cartouche
6407 @end smallexample
6409 @noindent
6410 The same alternative format is allowed for loops. For example, both of
6411 the following are permitted:
6413 @smallexample @c ada
6414 @cartouche
6415 Clear : while J < 10 loop
6416    A (J) := 0;
6417 end loop Clear;
6419 Clear :
6420    while J < 10 loop
6421       A (J) := 0;
6422    end loop Clear;
6423 @end cartouche
6424 @end smallexample
6426 @item ^Lnnn^MAX_NESTING=nnn^
6427 @emph{Set maximum nesting level}
6428 The maximum level of nesting of constructs (including subprograms, loops,
6429 blocks, packages, and conditionals) may not exceed the given value
6430 @option{nnn}. A value of zero disconnects this style check.
6432 @item ^m^LINE_LENGTH^
6433 @emph{Check maximum line length.}
6434 The length of source lines must not exceed 79 characters, including
6435 any trailing blanks. The value of 79 allows convenient display on an
6436 80 character wide device or window, allowing for possible special
6437 treatment of 80 character lines. Note that this count is of
6438 characters in the source text. This means that a tab character counts
6439 as one character in this count but a wide character sequence counts as
6440 a single character (however many bytes are needed in the encoding).
6442 @item ^Mnnn^MAX_LENGTH=nnn^
6443 @emph{Set maximum line length.}
6444 The length of lines must not exceed the
6445 given value @option{nnn}. The maximum value that can be specified is 32767.
6447 @item ^n^STANDARD_CASING^
6448 @emph{Check casing of entities in Standard.}
6449 Any identifier from Standard must be cased
6450 to match the presentation in the Ada Reference Manual (for example,
6451 @code{Integer} and @code{ASCII.NUL}).
6453 @item ^N^NONE^
6454 @emph{Turn off all style checks}
6455 All style check options are turned off.
6457 @item ^o^ORDERED_SUBPROGRAMS^
6458 @emph{Check order of subprogram bodies.}
6459 All subprogram bodies in a given scope
6460 (e.g.@: a package body) must be in alphabetical order. The ordering
6461 rule uses normal Ada rules for comparing strings, ignoring casing
6462 of letters, except that if there is a trailing numeric suffix, then
6463 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6464 before Junk10).
6466 @item ^O^OVERRIDING_INDICATORS^
6467 @emph{Check that overriding subprograms are explicitly marked as such.}
6468 The declaration of a primitive operation of a type extension that overrides
6469 an inherited operation must carry an overriding indicator.
6471 @item ^p^PRAGMA^
6472 @emph{Check pragma casing.}
6473 Pragma names must be written in mixed case, that is, the
6474 initial letter and any letter following an underscore must be uppercase.
6475 All other letters must be lowercase.
6477 @item ^r^REFERENCES^
6478 @emph{Check references.}
6479 All identifier references must be cased in the same way as the
6480 corresponding declaration. No specific casing style is imposed on
6481 identifiers. The only requirement is for consistency of references
6482 with declarations.
6484 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6485 @emph{Check no statements after THEN/ELSE.}
6486 No statements are allowed
6487 on the same line as a THEN or ELSE keyword following the
6488 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6489 and a special exception allows a pragma to appear after ELSE.
6491 @item ^s^SPECS^
6492 @emph{Check separate specs.}
6493 Separate declarations (``specs'') are required for subprograms (a
6494 body is not allowed to serve as its own declaration). The only
6495 exception is that parameterless library level procedures are
6496 not required to have a separate declaration. This exception covers
6497 the most frequent form of main program procedures.
6499 @item ^t^TOKEN^
6500 @emph{Check token spacing.}
6501 The following token spacing rules are enforced:
6503 @itemize @bullet
6505 @item
6506 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6508 @item
6509 The token @code{=>} must be surrounded by spaces.
6511 @item
6512 The token @code{<>} must be preceded by a space or a left parenthesis.
6514 @item
6515 Binary operators other than @code{**} must be surrounded by spaces.
6516 There is no restriction on the layout of the @code{**} binary operator.
6518 @item
6519 Colon must be surrounded by spaces.
6521 @item
6522 Colon-equal (assignment, initialization) must be surrounded by spaces.
6524 @item
6525 Comma must be the first non-blank character on the line, or be
6526 immediately preceded by a non-blank character, and must be followed
6527 by a space.
6529 @item
6530 If the token preceding a left parenthesis ends with a letter or digit, then
6531 a space must separate the two tokens.
6533 @item
6534 if the token following a right parenthesis starts with a letter or digit, then
6535 a space must separate the two tokens.
6537 @item
6538 A right parenthesis must either be the first non-blank character on
6539 a line, or it must be preceded by a non-blank character.
6541 @item
6542 A semicolon must not be preceded by a space, and must not be followed by
6543 a non-blank character.
6545 @item
6546 A unary plus or minus may not be followed by a space.
6548 @item
6549 A vertical bar must be surrounded by spaces.
6550 @end itemize
6552 @item ^u^UNNECESSARY_BLANK_LINES^
6553 @emph{Check unnecessary blank lines.}
6554 Unnecessary blank lines are not allowed. A blank line is considered
6555 unnecessary if it appears at the end of the file, or if more than
6556 one blank line occurs in sequence.
6558 @item ^x^XTRA_PARENS^
6559 @emph{Check extra parentheses.}
6560 Unnecessary extra level of parentheses (C-style) are not allowed
6561 around conditions in @code{if} statements, @code{while} statements and
6562 @code{exit} statements.
6564 @item ^y^ALL_BUILTIN^
6565 @emph{Set all standard style check options}
6566 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6567 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6568 @option{-gnatyS}, @option{-gnatyLnnn},
6569 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6571 @ifclear vms
6572 @item -
6573 @emph{Remove style check options}
6574 This causes any subsequent options in the string to act as canceling the
6575 corresponding style check option. To cancel maximum nesting level control,
6576 use @option{L} parameter witout any integer value after that, because any
6577 digit following @option{-} in the parameter string of the @option{-gnaty}
6578 option will be threated as canceling indentation check. The same is true
6579 for @option{M} parameter. @option{y} and @option{N} parameters are not
6580 allowed after @option{-}.
6582 @item +
6583 This causes any subsequent options in the string to enable the corresponding
6584 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6585 if any.
6586 @end ifclear
6588 @ifset vms
6589 @item NOxxx
6590 @emph{Removing style check options}
6591 If the name of a style check is preceded by @option{NO} then the corresponding
6592 style check is turned off. For example @option{NOCOMMENTS} turns off style
6593 checking for comments.
6594 @end ifset
6595 @end table
6597 @noindent
6598 In the above rules, appearing in column one is always permitted, that is,
6599 counts as meeting either a requirement for a required preceding space,
6600 or as meeting a requirement for no preceding space.
6602 Appearing at the end of a line is also always permitted, that is, counts
6603 as meeting either a requirement for a following space, or as meeting
6604 a requirement for no following space.
6606 @noindent
6607 If any of these style rules is violated, a message is generated giving
6608 details on the violation. The initial characters of such messages are
6609 always ``@code{(style)}''. Note that these messages are treated as warning
6610 messages, so they normally do not prevent the generation of an object
6611 file. The @option{-gnatwe} switch can be used to treat warning messages,
6612 including style messages, as fatal errors.
6614 The switch
6615 @ifclear vms
6616 @option{-gnaty} on its own (that is not
6617 followed by any letters or digits), then the effect is equivalent
6618 to the use of @option{-gnatyy}, as described above, that is all
6619 built-in standard style check options are enabled.
6621 @end ifclear
6622 @ifset vms
6623 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6624 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6625 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6626 @end ifset
6628 The switch
6629 @ifclear vms
6630 @option{-gnatyN}
6631 @end ifclear
6632 @ifset vms
6633 /STYLE_CHECKS=NONE
6634 @end ifset
6635 clears any previously set style checks.
6637 @node Run-Time Checks
6638 @subsection Run-Time Checks
6639 @cindex Division by zero
6640 @cindex Access before elaboration
6641 @cindex Checks, division by zero
6642 @cindex Checks, access before elaboration
6643 @cindex Checks, stack overflow checking
6645 @noindent
6646 By default, the following checks are suppressed: integer overflow
6647 checks, stack overflow checks, and checks for access before
6648 elaboration on subprogram calls. All other checks, including range
6649 checks and array bounds checks, are turned on by default. The
6650 following @command{gcc} switches refine this default behavior.
6652 @table @option
6653 @c !sort!
6654 @item -gnatp
6655 @cindex @option{-gnatp} (@command{gcc})
6656 @cindex Suppressing checks
6657 @cindex Checks, suppressing
6658 @findex Suppress
6659 This switch causes the unit to be compiled
6660 as though @code{pragma Suppress (All_checks)}
6661 had been present in the source. Validity checks are also eliminated (in
6662 other words @option{-gnatp} also implies @option{-gnatVn}.
6663 Use this switch to improve the performance
6664 of the code at the expense of safety in the presence of invalid data or
6665 program bugs.
6667 Note that when checks are suppressed, the compiler is allowed, but not
6668 required, to omit the checking code. If the run-time cost of the
6669 checking code is zero or near-zero, the compiler will generate it even
6670 if checks are suppressed. In particular, if the compiler can prove
6671 that a certain check will necessarily fail, it will generate code to
6672 do an unconditional ``raise'', even if checks are suppressed. The
6673 compiler warns in this case. Another case in which checks may not be
6674 eliminated is when they are embedded in certain run time routines such
6675 as math library routines.
6677 Of course, run-time checks are omitted whenever the compiler can prove
6678 that they will not fail, whether or not checks are suppressed.
6680 Note that if you suppress a check that would have failed, program
6681 execution is erroneous, which means the behavior is totally
6682 unpredictable. The program might crash, or print wrong answers, or
6683 do anything else. It might even do exactly what you wanted it to do
6684 (and then it might start failing mysteriously next week or next
6685 year). The compiler will generate code based on the assumption that
6686 the condition being checked is true, which can result in disaster if
6687 that assumption is wrong.
6689 The @option{-gnatp} switch has no effect if a subsequent
6690 @option{-gnat-p} switch appears.
6692 @item -gnat-p
6693 @cindex @option{-gnat-p} (@command{gcc})
6694 @cindex Suppressing checks
6695 @cindex Checks, suppressing
6696 @findex Suppress
6697 This switch cancels the effect of a previous @option{gnatp} switch.
6699 @item -gnato
6700 @cindex @option{-gnato} (@command{gcc})
6701 @cindex Overflow checks
6702 @cindex Check, overflow
6703 Enables overflow checking for integer operations.
6704 This causes GNAT to generate slower and larger executable
6705 programs by adding code to check for overflow (resulting in raising
6706 @code{Constraint_Error} as required by standard Ada
6707 semantics). These overflow checks correspond to situations in which
6708 the true value of the result of an operation may be outside the base
6709 range of the result type. The following example shows the distinction:
6711 @smallexample @c ada
6712 X1 : Integer := "Integer'Last";
6713 X2 : Integer range 1 .. 5 := "5";
6714 X3 : Integer := "Integer'Last";
6715 X4 : Integer range 1 .. 5 := "5";
6716 F  : Float := "2.0E+20";
6717 @dots{}
6718 X1 := X1 + 1;
6719 X2 := X2 + 1;
6720 X3 := Integer (F);
6721 X4 := Integer (F);
6722 @end smallexample
6724 @noindent
6725 Note that if explicit values are assigned at compile time, the
6726 compiler may be able to detect overflow at compile time, in which case
6727 no actual run-time checking code is required, and Constraint_Error
6728 will be raised unconditionally, with or without
6729 @option{-gnato}. That's why the assigned values in the above fragment
6730 are in quotes, the meaning is "assign a value not known to the
6731 compiler that happens to be equal to ...". The remaining discussion
6732 assumes that the compiler cannot detect the values at compile time.
6734 Here the first addition results in a value that is outside the base range
6735 of Integer, and hence requires an overflow check for detection of the
6736 constraint error. Thus the first assignment to @code{X1} raises a
6737 @code{Constraint_Error} exception only if @option{-gnato} is set.
6739 The second increment operation results in a violation of the explicit
6740 range constraint; such range checks are performed by default, and are
6741 unaffected by @option{-gnato}.
6743 The two conversions of @code{F} both result in values that are outside
6744 the base range of type @code{Integer} and thus will raise
6745 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6746 The fact that the result of the second conversion is assigned to
6747 variable @code{X4} with a restricted range is irrelevant, since the problem
6748 is in the conversion, not the assignment.
6750 Basically the rule is that in the default mode (@option{-gnato} not
6751 used), the generated code assures that all integer variables stay
6752 within their declared ranges, or within the base range if there is
6753 no declared range. This prevents any serious problems like indexes
6754 out of range for array operations.
6756 What is not checked in default mode is an overflow that results in
6757 an in-range, but incorrect value. In the above example, the assignments
6758 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6759 range of the target variable, but the result is wrong in the sense that
6760 it is too large to be represented correctly. Typically the assignment
6761 to @code{X1} will result in wrap around to the largest negative number.
6762 The conversions of @code{F} will result in some @code{Integer} value
6763 and if that integer value is out of the @code{X4} range then the
6764 subsequent assignment would generate an exception.
6766 @findex Machine_Overflows
6767 Note that the @option{-gnato} switch does not affect the code generated
6768 for any floating-point operations; it applies only to integer
6769 semantics).
6770 For floating-point, GNAT has the @code{Machine_Overflows}
6771 attribute set to @code{False} and the normal mode of operation is to
6772 generate IEEE NaN and infinite values on overflow or invalid operations
6773 (such as dividing 0.0 by 0.0).
6775 The reason that we distinguish overflow checking from other kinds of
6776 range constraint checking is that a failure of an overflow check, unlike
6777 for example the failure of a range check, can result in an incorrect
6778 value, but cannot cause random memory destruction (like an out of range
6779 subscript), or a wild jump (from an out of range case value). Overflow
6780 checking is also quite expensive in time and space, since in general it
6781 requires the use of double length arithmetic.
6783 Note again that @option{-gnato} is off by default, so overflow checking is
6784 not performed in default mode. This means that out of the box, with the
6785 default settings, GNAT does not do all the checks expected from the
6786 language description in the Ada Reference Manual. If you want all constraint
6787 checks to be performed, as described in this Manual, then you must
6788 explicitly use the -gnato switch either on the @command{gnatmake} or
6789 @command{gcc} command.
6791 @item -gnatE
6792 @cindex @option{-gnatE} (@command{gcc})
6793 @cindex Elaboration checks
6794 @cindex Check, elaboration
6795 Enables dynamic checks for access-before-elaboration
6796 on subprogram calls and generic instantiations.
6797 Note that @option{-gnatE} is not necessary for safety, because in the
6798 default mode, GNAT ensures statically that the checks would not fail.
6799 For full details of the effect and use of this switch,
6800 @xref{Compiling Using gcc}.
6802 @item -fstack-check
6803 @cindex @option{-fstack-check} (@command{gcc})
6804 @cindex Stack Overflow Checking
6805 @cindex Checks, stack overflow checking
6806 Activates stack overflow checking. For full details of the effect and use of
6807 this switch see @ref{Stack Overflow Checking}.
6808 @end table
6810 @findex Unsuppress
6811 @noindent
6812 The setting of these switches only controls the default setting of the
6813 checks. You may modify them using either @code{Suppress} (to remove
6814 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6815 the program source.
6817 @node Using gcc for Syntax Checking
6818 @subsection Using @command{gcc} for Syntax Checking
6819 @table @option
6820 @item -gnats
6821 @cindex @option{-gnats} (@command{gcc})
6822 @ifclear vms
6824 @noindent
6825 The @code{s} stands for ``syntax''.
6826 @end ifclear
6828 Run GNAT in syntax checking only mode. For
6829 example, the command
6831 @smallexample
6832 $ gcc -c -gnats x.adb
6833 @end smallexample
6835 @noindent
6836 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6837 series of files in a single command
6838 @ifclear vms
6839 , and can use wild cards to specify such a group of files.
6840 Note that you must specify the @option{-c} (compile
6841 only) flag in addition to the @option{-gnats} flag.
6842 @end ifclear
6844 You may use other switches in conjunction with @option{-gnats}. In
6845 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6846 format of any generated error messages.
6848 When the source file is empty or contains only empty lines and/or comments,
6849 the output is a warning:
6851 @smallexample
6852 $ gcc -c -gnats -x ada toto.txt
6853 toto.txt:1:01: warning: empty file, contains no compilation units
6855 @end smallexample
6857 Otherwise, the output is simply the error messages, if any. No object file or
6858 ALI file is generated by a syntax-only compilation. Also, no units other
6859 than the one specified are accessed. For example, if a unit @code{X}
6860 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6861 check only mode does not access the source file containing unit
6862 @code{Y}.
6864 @cindex Multiple units, syntax checking
6865 Normally, GNAT allows only a single unit in a source file. However, this
6866 restriction does not apply in syntax-check-only mode, and it is possible
6867 to check a file containing multiple compilation units concatenated
6868 together. This is primarily used by the @code{gnatchop} utility
6869 (@pxref{Renaming Files Using gnatchop}).
6870 @end table
6872 @node Using gcc for Semantic Checking
6873 @subsection Using @command{gcc} for Semantic Checking
6874 @table @option
6875 @item -gnatc
6876 @cindex @option{-gnatc} (@command{gcc})
6878 @ifclear vms
6879 @noindent
6880 The @code{c} stands for ``check''.
6881 @end ifclear
6882 Causes the compiler to operate in semantic check mode,
6883 with full checking for all illegalities specified in the
6884 Ada Reference Manual, but without generation of any object code
6885 (no object file is generated).
6887 Because dependent files must be accessed, you must follow the GNAT
6888 semantic restrictions on file structuring to operate in this mode:
6890 @itemize @bullet
6891 @item
6892 The needed source files must be accessible
6893 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6895 @item
6896 Each file must contain only one compilation unit.
6898 @item
6899 The file name and unit name must match (@pxref{File Naming Rules}).
6900 @end itemize
6902 The output consists of error messages as appropriate. No object file is
6903 generated. An @file{ALI} file is generated for use in the context of
6904 cross-reference tools, but this file is marked as not being suitable
6905 for binding (since no object file is generated).
6906 The checking corresponds exactly to the notion of
6907 legality in the Ada Reference Manual.
6909 Any unit can be compiled in semantics-checking-only mode, including
6910 units that would not normally be compiled (subunits,
6911 and specifications where a separate body is present).
6912 @end table
6914 @node Compiling Different Versions of Ada
6915 @subsection Compiling Different Versions of Ada
6917 @noindent
6918 The switches described in this section allow you to explicitly specify
6919 the version of the Ada language that your programs are written in.
6920 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6921 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6922 indicate Ada 83 compatibility mode.
6924 @table @option
6925 @cindex Compatibility with Ada 83
6927 @item -gnat83 (Ada 83 Compatibility Mode)
6928 @cindex @option{-gnat83} (@command{gcc})
6929 @cindex ACVC, Ada 83 tests
6930 @cindex Ada 83 mode
6932 @noindent
6933 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6934 specifies that the program is to be compiled in Ada 83 mode. With
6935 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6936 semantics where this can be done easily.
6937 It is not possible to guarantee this switch does a perfect
6938 job; some subtle tests, such as are
6939 found in earlier ACVC tests (and that have been removed from the ACATS suite
6940 for Ada 95), might not compile correctly.
6941 Nevertheless, this switch may be useful in some circumstances, for example
6942 where, due to contractual reasons, existing code needs to be maintained
6943 using only Ada 83 features.
6945 With few exceptions (most notably the need to use @code{<>} on
6946 @cindex Generic formal parameters
6947 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6948 reserved words, and the use of packages
6949 with optional bodies), it is not necessary to specify the
6950 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6951 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6952 a correct Ada 83 program is usually also a correct program
6953 in these later versions of the language standard.
6954 For further information, please refer to @ref{Compatibility and Porting Guide}.
6956 @item -gnat95 (Ada 95 mode)
6957 @cindex @option{-gnat95} (@command{gcc})
6958 @cindex Ada 95 mode
6960 @noindent
6961 This switch directs the compiler to implement the Ada 95 version of the
6962 language.
6963 Since Ada 95 is almost completely upwards
6964 compatible with Ada 83, Ada 83 programs may generally be compiled using
6965 this switch (see the description of the @option{-gnat83} switch for further
6966 information about Ada 83 mode).
6967 If an Ada 2005 program is compiled in Ada 95 mode,
6968 uses of the new Ada 2005 features will cause error
6969 messages or warnings.
6971 This switch also can be used to cancel the effect of a previous
6972 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6973 switch earlier in the command line.
6975 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6976 @cindex @option{-gnat05} (@command{gcc})
6977 @cindex @option{-gnat2005} (@command{gcc})
6978 @cindex Ada 2005 mode
6980 @noindent
6981 This switch directs the compiler to implement the Ada 2005 version of the
6982 language, as documented in the official Ada standards document.
6983 Since Ada 2005 is almost completely upwards
6984 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6985 may generally be compiled using this switch (see the description of the
6986 @option{-gnat83} and @option{-gnat95} switches for further
6987 information).
6989 @ifset PROEDITION
6990 Note that even though Ada 2005 is the current official version of the
6991 language, GNAT still compiles in Ada 95 mode by default, so if you are
6992 using Ada 2005 features in your program, you must use this switch (or
6993 the equivalent Ada_05 or Ada_2005 configuration pragmas).
6994 @end ifset
6996 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6997 @cindex @option{-gnat12} (@command{gcc})
6998 @cindex @option{-gnat2012} (@command{gcc})
6999 @cindex Ada 2012 mode
7001 @noindent
7002 This switch directs the compiler to implement the Ada 2012 version of the
7003 language.
7004 Since Ada 2012 is almost completely upwards
7005 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7006 Ada 83 and Ada 95 programs
7007 may generally be compiled using this switch (see the description of the
7008 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7009 for further information).
7011 For information about the approved ``Ada Issues'' that have been incorporated
7012 into Ada 2012, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
7013 Included with GNAT releases is a file @file{features-ada12} that describes
7014 the set of implemented Ada 2012 features.
7016 @item -gnatX (Enable GNAT Extensions)
7017 @cindex @option{-gnatX} (@command{gcc})
7018 @cindex Ada language extensions
7019 @cindex GNAT extensions
7021 @noindent
7022 This switch directs the compiler to implement the latest version of the
7023 language (currently Ada 2012) and also to enable certain GNAT implementation
7024 extensions that are not part of any Ada standard. For a full list of these
7025 extensions, see the GNAT reference manual.
7027 @end table
7029 @node Character Set Control
7030 @subsection Character Set Control
7031 @table @option
7032 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7033 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7035 @noindent
7036 Normally GNAT recognizes the Latin-1 character set in source program
7037 identifiers, as described in the Ada Reference Manual.
7038 This switch causes
7039 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7040 single character ^^or word^ indicating the character set, as follows:
7042 @table @code
7043 @item 1
7044 ISO 8859-1 (Latin-1) identifiers
7046 @item 2
7047 ISO 8859-2 (Latin-2) letters allowed in identifiers
7049 @item 3
7050 ISO 8859-3 (Latin-3) letters allowed in identifiers
7052 @item 4
7053 ISO 8859-4 (Latin-4) letters allowed in identifiers
7055 @item 5
7056 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7058 @item 9
7059 ISO 8859-15 (Latin-9) letters allowed in identifiers
7061 @item ^p^PC^
7062 IBM PC letters (code page 437) allowed in identifiers
7064 @item ^8^PC850^
7065 IBM PC letters (code page 850) allowed in identifiers
7067 @item ^f^FULL_UPPER^
7068 Full upper-half codes allowed in identifiers
7070 @item ^n^NO_UPPER^
7071 No upper-half codes allowed in identifiers
7073 @item ^w^WIDE^
7074 Wide-character codes (that is, codes greater than 255)
7075 allowed in identifiers
7076 @end table
7078 @xref{Foreign Language Representation}, for full details on the
7079 implementation of these character sets.
7081 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7082 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7083 Specify the method of encoding for wide characters.
7084 @var{e} is one of the following:
7086 @table @code
7088 @item ^h^HEX^
7089 Hex encoding (brackets coding also recognized)
7091 @item ^u^UPPER^
7092 Upper half encoding (brackets encoding also recognized)
7094 @item ^s^SHIFT_JIS^
7095 Shift/JIS encoding (brackets encoding also recognized)
7097 @item ^e^EUC^
7098 EUC encoding (brackets encoding also recognized)
7100 @item ^8^UTF8^
7101 UTF-8 encoding (brackets encoding also recognized)
7103 @item ^b^BRACKETS^
7104 Brackets encoding only (default value)
7105 @end table
7106 For full details on these encoding
7107 methods see @ref{Wide Character Encodings}.
7108 Note that brackets coding is always accepted, even if one of the other
7109 options is specified, so for example @option{-gnatW8} specifies that both
7110 brackets and UTF-8 encodings will be recognized. The units that are
7111 with'ed directly or indirectly will be scanned using the specified
7112 representation scheme, and so if one of the non-brackets scheme is
7113 used, it must be used consistently throughout the program. However,
7114 since brackets encoding is always recognized, it may be conveniently
7115 used in standard libraries, allowing these libraries to be used with
7116 any of the available coding schemes.
7117 scheme.
7119 If no @option{-gnatW?} parameter is present, then the default
7120 representation is normally Brackets encoding only. However, if the
7121 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7122 byte order mark or BOM for UTF-8), then these three characters are
7123 skipped and the default representation for the file is set to UTF-8.
7125 Note that the wide character representation that is specified (explicitly
7126 or by default) for the main program also acts as the default encoding used
7127 for Wide_Text_IO files if not specifically overridden by a WCEM form
7128 parameter.
7130 @end table
7131 @node File Naming Control
7132 @subsection File Naming Control
7134 @table @option
7135 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7136 @cindex @option{-gnatk} (@command{gcc})
7137 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7138 1-999, indicates the maximum allowable length of a file name (not
7139 including the @file{.ads} or @file{.adb} extension). The default is not
7140 to enable file name krunching.
7142 For the source file naming rules, @xref{File Naming Rules}.
7143 @end table
7145 @node Subprogram Inlining Control
7146 @subsection Subprogram Inlining Control
7148 @table @option
7149 @c !sort!
7150 @item -gnatn
7151 @cindex @option{-gnatn} (@command{gcc})
7152 @ifclear vms
7153 The @code{n} here is intended to suggest the first syllable of the
7154 word ``inline''.
7155 @end ifclear
7156 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7157 inlining to actually occur, optimization must be enabled. To enable
7158 inlining of subprograms specified by pragma @code{Inline},
7159 you must also specify this switch.
7160 In the absence of this switch, GNAT does not attempt
7161 inlining and does not need to access the bodies of
7162 subprograms for which @code{pragma Inline} is specified if they are not
7163 in the current unit.
7165 If you specify this switch the compiler will access these bodies,
7166 creating an extra source dependency for the resulting object file, and
7167 where possible, the call will be inlined.
7168 For further details on when inlining is possible
7169 see @ref{Inlining of Subprograms}.
7171 @item -gnatN
7172 @cindex @option{-gnatN} (@command{gcc})
7173 This switch activates front-end inlining which also
7174 generates additional dependencies.
7176 When using a gcc-based back end (in practice this means using any version
7177 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7178 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7179 Historically front end inlining was more extensive than the gcc back end
7180 inlining, but that is no longer the case.
7181 @end table
7183 @node Auxiliary Output Control
7184 @subsection Auxiliary Output Control
7186 @table @option
7187 @item -gnatt
7188 @cindex @option{-gnatt} (@command{gcc})
7189 @cindex Writing internal trees
7190 @cindex Internal trees, writing to file
7191 Causes GNAT to write the internal tree for a unit to a file (with the
7192 extension @file{.adt}.
7193 This not normally required, but is used by separate analysis tools.
7194 Typically
7195 these tools do the necessary compilations automatically, so you should
7196 not have to specify this switch in normal operation.
7197 Note that the combination of switches @option{-gnatct}
7198 generates a tree in the form required by ASIS applications.
7200 @item -gnatu
7201 @cindex @option{-gnatu} (@command{gcc})
7202 Print a list of units required by this compilation on @file{stdout}.
7203 The listing includes all units on which the unit being compiled depends
7204 either directly or indirectly.
7206 @ifclear vms
7207 @item -pass-exit-codes
7208 @cindex @option{-pass-exit-codes} (@command{gcc})
7209 If this switch is not used, the exit code returned by @command{gcc} when
7210 compiling multiple files indicates whether all source files have
7211 been successfully used to generate object files or not.
7213 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7214 exit status and allows an integrated development environment to better
7215 react to a compilation failure. Those exit status are:
7217 @table @asis
7218 @item 5
7219 There was an error in at least one source file.
7220 @item 3
7221 At least one source file did not generate an object file.
7222 @item 2
7223 The compiler died unexpectedly (internal error for example).
7224 @item 0
7225 An object file has been generated for every source file.
7226 @end table
7227 @end ifclear
7228 @end table
7230 @node Debugging Control
7231 @subsection Debugging Control
7233 @table @option
7234 @c !sort!
7235 @cindex Debugging options
7236 @ifclear vms
7237 @item -gnatd@var{x}
7238 @cindex @option{-gnatd} (@command{gcc})
7239 Activate internal debugging switches. @var{x} is a letter or digit, or
7240 string of letters or digits, which specifies the type of debugging
7241 outputs desired. Normally these are used only for internal development
7242 or system debugging purposes. You can find full documentation for these
7243 switches in the body of the @code{Debug} unit in the compiler source
7244 file @file{debug.adb}.
7245 @end ifclear
7247 @item -gnatG[=nn]
7248 @cindex @option{-gnatG} (@command{gcc})
7249 This switch causes the compiler to generate auxiliary output containing
7250 a pseudo-source listing of the generated expanded code. Like most Ada
7251 compilers, GNAT works by first transforming the high level Ada code into
7252 lower level constructs. For example, tasking operations are transformed
7253 into calls to the tasking run-time routines. A unique capability of GNAT
7254 is to list this expanded code in a form very close to normal Ada source.
7255 This is very useful in understanding the implications of various Ada
7256 usage on the efficiency of the generated code. There are many cases in
7257 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7258 generate a lot of run-time code. By using @option{-gnatG} you can identify
7259 these cases, and consider whether it may be desirable to modify the coding
7260 approach to improve efficiency.
7262 The optional parameter @code{nn} if present after -gnatG specifies an
7263 alternative maximum line length that overrides the normal default of 72.
7264 This value is in the range 40-999999, values less than 40 being silently
7265 reset to 40. The equal sign is optional.
7267 The format of the output is very similar to standard Ada source, and is
7268 easily understood by an Ada programmer. The following special syntactic
7269 additions correspond to low level features used in the generated code that
7270 do not have any exact analogies in pure Ada source form. The following
7271 is a partial list of these special constructions. See the spec
7272 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7274 If the switch @option{-gnatL} is used in conjunction with
7275 @cindex @option{-gnatL} (@command{gcc})
7276 @option{-gnatG}, then the original source lines are interspersed
7277 in the expanded source (as comment lines with the original line number).
7279 @table @code
7280 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7281 Shows the storage pool being used for an allocator.
7283 @item at end @var{procedure-name};
7284 Shows the finalization (cleanup) procedure for a scope.
7286 @item (if @var{expr} then @var{expr} else @var{expr})
7287 Conditional expression equivalent to the @code{x?y:z} construction in C.
7289 @item @var{target}^^^(@var{source})
7290 A conversion with floating-point truncation instead of rounding.
7292 @item @var{target}?(@var{source})
7293 A conversion that bypasses normal Ada semantic checking. In particular
7294 enumeration types and fixed-point types are treated simply as integers.
7296 @item @var{target}?^^^(@var{source})
7297 Combines the above two cases.
7299 @item @var{x} #/ @var{y}
7300 @itemx @var{x} #mod @var{y}
7301 @itemx @var{x} #* @var{y}
7302 @itemx @var{x} #rem @var{y}
7303 A division or multiplication of fixed-point values which are treated as
7304 integers without any kind of scaling.
7306 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7307 Shows the storage pool associated with a @code{free} statement.
7309 @item [subtype or type declaration]
7310 Used to list an equivalent declaration for an internally generated
7311 type that is referenced elsewhere in the listing.
7313 @c @item freeze @var{type-name} @ovar{actions}
7314 @c Expanding @ovar macro inline (explanation in macro def comments)
7315 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7316 Shows the point at which @var{type-name} is frozen, with possible
7317 associated actions to be performed at the freeze point.
7319 @item reference @var{itype}
7320 Reference (and hence definition) to internal type @var{itype}.
7322 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7323 Intrinsic function call.
7325 @item @var{label-name} : label
7326 Declaration of label @var{labelname}.
7328 @item #$ @var{subprogram-name}
7329 An implicit call to a run-time support routine
7330 (to meet the requirement of H.3.1(9) in a
7331 convenient manner).
7333 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7334 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7335 @var{expr}, but handled more efficiently).
7337 @item [constraint_error]
7338 Raise the @code{Constraint_Error} exception.
7340 @item @var{expression}'reference
7341 A pointer to the result of evaluating @var{expression}.
7343 @item @var{target-type}!(@var{source-expression})
7344 An unchecked conversion of @var{source-expression} to @var{target-type}.
7346 @item [@var{numerator}/@var{denominator}]
7347 Used to represent internal real literals (that) have no exact
7348 representation in base 2-16 (for example, the result of compile time
7349 evaluation of the expression 1.0/27.0).
7350 @end table
7352 @item -gnatD[=nn]
7353 @cindex @option{-gnatD} (@command{gcc})
7354 When used in conjunction with @option{-gnatG}, this switch causes
7355 the expanded source, as described above for
7356 @option{-gnatG} to be written to files with names
7357 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7358 instead of to the standard output file. For
7359 example, if the source file name is @file{hello.adb}, then a file
7360 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7361 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7362 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7363 you to do source level debugging using the generated code which is
7364 sometimes useful for complex code, for example to find out exactly
7365 which part of a complex construction raised an exception. This switch
7366 also suppress generation of cross-reference information (see
7367 @option{-gnatx}) since otherwise the cross-reference information
7368 would refer to the @file{^.dg^.DG^} file, which would cause
7369 confusion since this is not the original source file.
7371 Note that @option{-gnatD} actually implies @option{-gnatG}
7372 automatically, so it is not necessary to give both options.
7373 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7375 If the switch @option{-gnatL} is used in conjunction with
7376 @cindex @option{-gnatL} (@command{gcc})
7377 @option{-gnatDG}, then the original source lines are interspersed
7378 in the expanded source (as comment lines with the original line number).
7380 The optional parameter @code{nn} if present after -gnatD specifies an
7381 alternative maximum line length that overrides the normal default of 72.
7382 This value is in the range 40-999999, values less than 40 being silently
7383 reset to 40. The equal sign is optional.
7385 @item -gnatr
7386 @cindex @option{-gnatr} (@command{gcc})
7387 @cindex pragma Restrictions
7388 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7389 so that violation of restrictions causes warnings rather than illegalities.
7390 This is useful during the development process when new restrictions are added
7391 or investigated. The switch also causes pragma Profile to be treated as
7392 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7393 restriction warnings rather than restrictions.
7395 @ifclear vms
7396 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7397 @cindex @option{-gnatR} (@command{gcc})
7398 This switch controls output from the compiler of a listing showing
7399 representation information for declared types and objects. For
7400 @option{-gnatR0}, no information is output (equivalent to omitting
7401 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7402 so @option{-gnatR} with no parameter has the same effect), size and alignment
7403 information is listed for declared array and record types. For
7404 @option{-gnatR2}, size and alignment information is listed for all
7405 declared types and objects. Finally @option{-gnatR3} includes symbolic
7406 expressions for values that are computed at run time for
7407 variant records. These symbolic expressions have a mostly obvious
7408 format with #n being used to represent the value of the n'th
7409 discriminant. See source files @file{repinfo.ads/adb} in the
7410 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7411 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7412 the output is to a file with the name @file{^file.rep^file_REP^} where
7413 file is the name of the corresponding source file.
7414 @end ifclear
7415 @ifset vms
7416 @item /REPRESENTATION_INFO
7417 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7418 This qualifier controls output from the compiler of a listing showing
7419 representation information for declared types and objects. For
7420 @option{/REPRESENTATION_INFO=NONE}, no information is output
7421 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7422 @option{/REPRESENTATION_INFO} without option is equivalent to
7423 @option{/REPRESENTATION_INFO=ARRAYS}.
7424 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7425 information is listed for declared array and record types. For
7426 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7427 is listed for all expression information for values that are computed
7428 at run time for variant records. These symbolic expressions have a mostly
7429 obvious format with #n being used to represent the value of the n'th
7430 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7431 @code{GNAT} sources for full details on the format of
7432 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7433 If _FILE is added at the end of an option
7434 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7435 then the output is to a file with the name @file{file_REP} where
7436 file is the name of the corresponding source file.
7437 @end ifset
7438 Note that it is possible for record components to have zero size. In
7439 this case, the component clause uses an obvious extension of permitted
7440 Ada syntax, for example @code{at 0 range 0 .. -1}.
7442 Representation information requires that code be generated (since it is the
7443 code generator that lays out complex data structures). If an attempt is made
7444 to output representation information when no code is generated, for example
7445 when a subunit is compiled on its own, then no information can be generated
7446 and the compiler outputs a message to this effect.
7448 @item -gnatS
7449 @cindex @option{-gnatS} (@command{gcc})
7450 The use of the switch @option{-gnatS} for an
7451 Ada compilation will cause the compiler to output a
7452 representation of package Standard in a form very
7453 close to standard Ada. It is not quite possible to
7454 do this entirely in standard Ada (since new
7455 numeric base types cannot be created in standard
7456 Ada), but the output is easily
7457 readable to any Ada programmer, and is useful to
7458 determine the characteristics of target dependent
7459 types in package Standard.
7461 @item -gnatx
7462 @cindex @option{-gnatx} (@command{gcc})
7463 Normally the compiler generates full cross-referencing information in
7464 the @file{ALI} file. This information is used by a number of tools,
7465 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7466 suppresses this information. This saves some space and may slightly
7467 speed up compilation, but means that these tools cannot be used.
7468 @end table
7470 @node Exception Handling Control
7471 @subsection Exception Handling Control
7473 @noindent
7474 GNAT uses two methods for handling exceptions at run-time. The
7475 @code{setjmp/longjmp} method saves the context when entering
7476 a frame with an exception handler. Then when an exception is
7477 raised, the context can be restored immediately, without the
7478 need for tracing stack frames. This method provides very fast
7479 exception propagation, but introduces significant overhead for
7480 the use of exception handlers, even if no exception is raised.
7482 The other approach is called ``zero cost'' exception handling.
7483 With this method, the compiler builds static tables to describe
7484 the exception ranges. No dynamic code is required when entering
7485 a frame containing an exception handler. When an exception is
7486 raised, the tables are used to control a back trace of the
7487 subprogram invocation stack to locate the required exception
7488 handler. This method has considerably poorer performance for
7489 the propagation of exceptions, but there is no overhead for
7490 exception handlers if no exception is raised. Note that in this
7491 mode and in the context of mixed Ada and C/C++ programming,
7492 to propagate an exception through a C/C++ code, the C/C++ code
7493 must be compiled with the @option{-funwind-tables} GCC's
7494 option.
7496 The following switches may be used to control which of the
7497 two exception handling methods is used.
7499 @table @option
7500 @c !sort!
7502 @item --RTS=sjlj
7503 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7504 This switch causes the setjmp/longjmp run-time (when available) to be used
7505 for exception handling. If the default
7506 mechanism for the target is zero cost exceptions, then
7507 this switch can be used to modify this default, and must be
7508 used for all units in the partition.
7509 This option is rarely used. One case in which it may be
7510 advantageous is if you have an application where exception
7511 raising is common and the overall performance of the
7512 application is improved by favoring exception propagation.
7514 @item --RTS=zcx
7515 @cindex @option{--RTS=zcx} (@command{gnatmake})
7516 @cindex Zero Cost Exceptions
7517 This switch causes the zero cost approach to be used
7518 for exception handling. If this is the default mechanism for the
7519 target (see below), then this switch is unneeded. If the default
7520 mechanism for the target is setjmp/longjmp exceptions, then
7521 this switch can be used to modify this default, and must be
7522 used for all units in the partition.
7523 This option can only be used if the zero cost approach
7524 is available for the target in use, otherwise it will generate an error.
7525 @end table
7527 @noindent
7528 The same option @option{--RTS} must be used both for @command{gcc}
7529 and @command{gnatbind}. Passing this option to @command{gnatmake}
7530 (@pxref{Switches for gnatmake}) will ensure the required consistency
7531 through the compilation and binding steps.
7533 @node Units to Sources Mapping Files
7534 @subsection Units to Sources Mapping Files
7536 @table @option
7538 @item -gnatem=@var{path}
7539 @cindex @option{-gnatem} (@command{gcc})
7540 A mapping file is a way to communicate to the compiler two mappings:
7541 from unit names to file names (without any directory information) and from
7542 file names to path names (with full directory information). These mappings
7543 are used by the compiler to short-circuit the path search.
7545 The use of mapping files is not required for correct operation of the
7546 compiler, but mapping files can improve efficiency, particularly when
7547 sources are read over a slow network connection. In normal operation,
7548 you need not be concerned with the format or use of mapping files,
7549 and the @option{-gnatem} switch is not a switch that you would use
7550 explicitly. It is intended primarily for use by automatic tools such as
7551 @command{gnatmake} running under the project file facility. The
7552 description here of the format of mapping files is provided
7553 for completeness and for possible use by other tools.
7555 A mapping file is a sequence of sets of three lines. In each set, the
7556 first line is the unit name, in lower case, with @code{%s} appended
7557 for specs and @code{%b} appended for bodies; the second line is the
7558 file name; and the third line is the path name.
7560 Example:
7561 @smallexample
7562    main%b
7563    main.2.ada
7564    /gnat/project1/sources/main.2.ada
7565 @end smallexample
7567 When the switch @option{-gnatem} is specified, the compiler will
7568 create in memory the two mappings from the specified file. If there is
7569 any problem (nonexistent file, truncated file or duplicate entries),
7570 no mapping will be created.
7572 Several @option{-gnatem} switches may be specified; however, only the
7573 last one on the command line will be taken into account.
7575 When using a project file, @command{gnatmake} creates a temporary
7576 mapping file and communicates it to the compiler using this switch.
7578 @end table
7580 @node Integrated Preprocessing
7581 @subsection Integrated Preprocessing
7583 @noindent
7584 GNAT sources may be preprocessed immediately before compilation.
7585 In this case, the actual
7586 text of the source is not the text of the source file, but is derived from it
7587 through a process called preprocessing. Integrated preprocessing is specified
7588 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7589 indicates, through a text file, the preprocessing data to be used.
7590 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7592 @noindent
7593 Note that when integrated preprocessing is used, the output from the
7594 preprocessor is not written to any external file. Instead it is passed
7595 internally to the compiler. If you need to preserve the result of
7596 preprocessing in a file, then you should use @command{gnatprep}
7597 to perform the desired preprocessing in stand-alone mode.
7599 @noindent
7600 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7601 used when Integrated Preprocessing is used. The reason is that preprocessing
7602 with another Preprocessing Data file without changing the sources will
7603 not trigger recompilation without this switch.
7605 @noindent
7606 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7607 always trigger recompilation for sources that are preprocessed,
7608 because @command{gnatmake} cannot compute the checksum of the source after
7609 preprocessing.
7611 @noindent
7612 The actual preprocessing function is described in details in section
7613 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7614 preprocessing is triggered and parameterized.
7616 @table @code
7618 @item -gnatep=@var{file}
7619 @cindex @option{-gnatep} (@command{gcc})
7620 This switch indicates to the compiler the file name (without directory
7621 information) of the preprocessor data file to use. The preprocessor data file
7622 should be found in the source directories.
7624 @noindent
7625 A preprocessing data file is a text file with significant lines indicating
7626 how should be preprocessed either a specific source or all sources not
7627 mentioned in other lines. A significant line is a nonempty, non-comment line.
7628 Comments are similar to Ada comments.
7630 @noindent
7631 Each significant line starts with either a literal string or the character '*'.
7632 A literal string is the file name (without directory information) of the source
7633 to preprocess. A character '*' indicates the preprocessing for all the sources
7634 that are not specified explicitly on other lines (order of the lines is not
7635 significant). It is an error to have two lines with the same file name or two
7636 lines starting with the character '*'.
7638 @noindent
7639 After the file name or the character '*', another optional literal string
7640 indicating the file name of the definition file to be used for preprocessing
7641 (@pxref{Form of Definitions File}). The definition files are found by the
7642 compiler in one of the source directories. In some cases, when compiling
7643 a source in a directory other than the current directory, if the definition
7644 file is in the current directory, it may be necessary to add the current
7645 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7646 the compiler would not find the definition file.
7648 @noindent
7649 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7650 be found. Those ^switches^switches^ are:
7652 @table @code
7654 @item -b
7655 Causes both preprocessor lines and the lines deleted by
7656 preprocessing to be replaced by blank lines, preserving the line number.
7657 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7658 it cancels the effect of @option{-c}.
7660 @item -c
7661 Causes both preprocessor lines and the lines deleted
7662 by preprocessing to be retained as comments marked
7663 with the special string ``@code{--! }''.
7665 @item -Dsymbol=value
7666 Define or redefine a symbol, associated with value. A symbol is an Ada
7667 identifier, or an Ada reserved word, with the exception of @code{if},
7668 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7669 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7670 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7671 same name defined in a definition file.
7673 @item -s
7674 Causes a sorted list of symbol names and values to be
7675 listed on the standard output file.
7677 @item -u
7678 Causes undefined symbols to be treated as having the value @code{FALSE}
7679 in the context
7680 of a preprocessor test. In the absence of this option, an undefined symbol in
7681 a @code{#if} or @code{#elsif} test will be treated as an error.
7683 @end table
7685 @noindent
7686 Examples of valid lines in a preprocessor data file:
7688 @smallexample
7689   "toto.adb"  "prep.def" -u
7690   --  preprocess "toto.adb", using definition file "prep.def",
7691   --  undefined symbol are False.
7693   * -c -DVERSION=V101
7694   --  preprocess all other sources without a definition file;
7695   --  suppressed lined are commented; symbol VERSION has the value V101.
7697   "titi.adb" "prep2.def" -s
7698   --  preprocess "titi.adb", using definition file "prep2.def";
7699   --  list all symbols with their values.
7700 @end smallexample
7702 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7703 @cindex @option{-gnateD} (@command{gcc})
7704 Define or redefine a preprocessing symbol, associated with value. If no value
7705 is given on the command line, then the value of the symbol is @code{True}.
7706 A symbol is an identifier, following normal Ada (case-insensitive)
7707 rules for its syntax, and value is any sequence (including an empty sequence)
7708 of characters from the set (letters, digits, period, underline).
7709 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7710 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7712 @noindent
7713 A symbol declared with this ^switch^switch^ on the command line replaces a
7714 symbol with the same name either in a definition file or specified with a
7715 ^switch^switch^ -D in the preprocessor data file.
7717 @noindent
7718 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7720 @item -gnateG
7721 When integrated preprocessing is performed and the preprocessor modifies
7722 the source text, write the result of this preprocessing into a file
7723 <source>^.prep^_prep^.
7725 @end table
7727 @node Code Generation Control
7728 @subsection Code Generation Control
7730 @noindent
7732 The GCC technology provides a wide range of target dependent
7733 @option{-m} switches for controlling
7734 details of code generation with respect to different versions of
7735 architectures. This includes variations in instruction sets (e.g.@:
7736 different members of the power pc family), and different requirements
7737 for optimal arrangement of instructions (e.g.@: different members of
7738 the x86 family). The list of available @option{-m} switches may be
7739 found in the GCC documentation.
7741 Use of these @option{-m} switches may in some cases result in improved
7742 code performance.
7744 The GNAT Pro technology is tested and qualified without any
7745 @option{-m} switches,
7746 so generally the most reliable approach is to avoid the use of these
7747 switches. However, we generally expect most of these switches to work
7748 successfully with GNAT Pro, and many customers have reported successful
7749 use of these options.
7751 Our general advice is to avoid the use of @option{-m} switches unless
7752 special needs lead to requirements in this area. In particular,
7753 there is no point in using @option{-m} switches to improve performance
7754 unless you actually see a performance improvement.
7756 @ifset vms
7757 @node Return Codes
7758 @subsection Return Codes
7759 @cindex Return Codes
7760 @cindex @option{/RETURN_CODES=VMS}
7762 @noindent
7763 On VMS, GNAT compiled programs return POSIX-style codes by default,
7764 e.g.@: @option{/RETURN_CODES=POSIX}.
7766 To enable VMS style return codes, use GNAT BIND and LINK with the option
7767 @option{/RETURN_CODES=VMS}. For example:
7769 @smallexample
7770 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7771 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7772 @end smallexample
7774 @noindent
7775 Programs built with /RETURN_CODES=VMS are suitable to be called in
7776 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7777 are suitable for spawning with appropriate GNAT RTL routines.
7779 @end ifset
7781 @node Search Paths and the Run-Time Library (RTL)
7782 @section Search Paths and the Run-Time Library (RTL)
7784 @noindent
7785 With the GNAT source-based library system, the compiler must be able to
7786 find source files for units that are needed by the unit being compiled.
7787 Search paths are used to guide this process.
7789 The compiler compiles one source file whose name must be given
7790 explicitly on the command line. In other words, no searching is done
7791 for this file. To find all other source files that are needed (the most
7792 common being the specs of units), the compiler examines the following
7793 directories, in the following order:
7795 @enumerate
7796 @item
7797 The directory containing the source file of the main unit being compiled
7798 (the file name on the command line).
7800 @item
7801 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7802 @command{gcc} command line, in the order given.
7804 @item
7805 @findex ADA_PRJ_INCLUDE_FILE
7806 Each of the directories listed in the text file whose name is given
7807 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7809 @noindent
7810 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7811 driver when project files are used. It should not normally be set
7812 by other means.
7814 @item
7815 @findex ADA_INCLUDE_PATH
7816 Each of the directories listed in the value of the
7817 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7818 @ifclear vms
7819 Construct this value
7820 exactly as the @env{PATH} environment variable: a list of directory
7821 names separated by colons (semicolons when working with the NT version).
7822 @end ifclear
7823 @ifset vms
7824 Normally, define this value as a logical name containing a comma separated
7825 list of directory names.
7827 This variable can also be defined by means of an environment string
7828 (an argument to the HP C exec* set of functions).
7830 Logical Name:
7831 @smallexample
7832 DEFINE ANOTHER_PATH FOO:[BAG]
7833 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7834 @end smallexample
7836 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7837 first, followed by the standard Ada
7838 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7839 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7840 (Text_IO, Sequential_IO, etc)
7841 instead of the standard Ada packages. Thus, in order to get the standard Ada
7842 packages by default, ADA_INCLUDE_PATH must be redefined.
7843 @end ifset
7845 @item
7846 The content of the @file{ada_source_path} file which is part of the GNAT
7847 installation tree and is used to store standard libraries such as the
7848 GNAT Run Time Library (RTL) source files.
7849 @ifclear vms
7850 @ref{Installing a library}
7851 @end ifclear
7852 @end enumerate
7854 @noindent
7855 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7856 inhibits the use of the directory
7857 containing the source file named in the command line. You can still
7858 have this directory on your search path, but in this case it must be
7859 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7861 Specifying the switch @option{-nostdinc}
7862 inhibits the search of the default location for the GNAT Run Time
7863 Library (RTL) source files.
7865 The compiler outputs its object files and ALI files in the current
7866 working directory.
7867 @ifclear vms
7868 Caution: The object file can be redirected with the @option{-o} switch;
7869 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7870 so the @file{ALI} file will not go to the right place. Therefore, you should
7871 avoid using the @option{-o} switch.
7872 @end ifclear
7874 @findex System.IO
7875 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7876 children make up the GNAT RTL, together with the simple @code{System.IO}
7877 package used in the @code{"Hello World"} example. The sources for these units
7878 are needed by the compiler and are kept together in one directory. Not
7879 all of the bodies are needed, but all of the sources are kept together
7880 anyway. In a normal installation, you need not specify these directory
7881 names when compiling or binding. Either the environment variables or
7882 the built-in defaults cause these files to be found.
7884 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7885 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7886 consisting of child units of @code{GNAT}. This is a collection of generally
7887 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7888 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7890 Besides simplifying access to the RTL, a major use of search paths is
7891 in compiling sources from multiple directories. This can make
7892 development environments much more flexible.
7894 @node Order of Compilation Issues
7895 @section Order of Compilation Issues
7897 @noindent
7898 If, in our earlier example, there was a spec for the @code{hello}
7899 procedure, it would be contained in the file @file{hello.ads}; yet this
7900 file would not have to be explicitly compiled. This is the result of the
7901 model we chose to implement library management. Some of the consequences
7902 of this model are as follows:
7904 @itemize @bullet
7905 @item
7906 There is no point in compiling specs (except for package
7907 specs with no bodies) because these are compiled as needed by clients. If
7908 you attempt a useless compilation, you will receive an error message.
7909 It is also useless to compile subunits because they are compiled as needed
7910 by the parent.
7912 @item
7913 There are no order of compilation requirements: performing a
7914 compilation never obsoletes anything. The only way you can obsolete
7915 something and require recompilations is to modify one of the
7916 source files on which it depends.
7918 @item
7919 There is no library as such, apart from the ALI files
7920 (@pxref{The Ada Library Information Files}, for information on the format
7921 of these files). For now we find it convenient to create separate ALI files,
7922 but eventually the information therein may be incorporated into the object
7923 file directly.
7925 @item
7926 When you compile a unit, the source files for the specs of all units
7927 that it @code{with}'s, all its subunits, and the bodies of any generics it
7928 instantiates must be available (reachable by the search-paths mechanism
7929 described above), or you will receive a fatal error message.
7930 @end itemize
7932 @node Examples
7933 @section Examples
7935 @noindent
7936 The following are some typical Ada compilation command line examples:
7938 @table @code
7939 @item $ gcc -c xyz.adb
7940 Compile body in file @file{xyz.adb} with all default options.
7942 @ifclear vms
7943 @item $ gcc -c -O2 -gnata xyz-def.adb
7944 @end ifclear
7945 @ifset vms
7946 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7947 @end ifset
7949 Compile the child unit package in file @file{xyz-def.adb} with extensive
7950 optimizations, and pragma @code{Assert}/@code{Debug} statements
7951 enabled.
7953 @item $ gcc -c -gnatc abc-def.adb
7954 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7955 mode.
7956 @end table
7958 @node Binding Using gnatbind
7959 @chapter Binding Using @code{gnatbind}
7960 @findex gnatbind
7962 @menu
7963 * Running gnatbind::
7964 * Switches for gnatbind::
7965 * Command-Line Access::
7966 * Search Paths for gnatbind::
7967 * Examples of gnatbind Usage::
7968 @end menu
7970 @noindent
7971 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7972 to bind compiled GNAT objects.
7974 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7975 driver (see @ref{The GNAT Driver and Project Files}).
7977 The @code{gnatbind} program performs four separate functions:
7979 @enumerate
7980 @item
7981 Checks that a program is consistent, in accordance with the rules in
7982 Chapter 10 of the Ada Reference Manual. In particular, error
7983 messages are generated if a program uses inconsistent versions of a
7984 given unit.
7986 @item
7987 Checks that an acceptable order of elaboration exists for the program
7988 and issues an error message if it cannot find an order of elaboration
7989 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7991 @item
7992 Generates a main program incorporating the given elaboration order.
7993 This program is a small Ada package (body and spec) that
7994 must be subsequently compiled
7995 using the GNAT compiler. The necessary compilation step is usually
7996 performed automatically by @command{gnatlink}. The two most important
7997 functions of this program
7998 are to call the elaboration routines of units in an appropriate order
7999 and to call the main program.
8001 @item
8002 Determines the set of object files required by the given main program.
8003 This information is output in the forms of comments in the generated program,
8004 to be read by the @command{gnatlink} utility used to link the Ada application.
8005 @end enumerate
8007 @node Running gnatbind
8008 @section Running @code{gnatbind}
8010 @noindent
8011 The form of the @code{gnatbind} command is
8013 @smallexample
8014 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8015 @c Expanding @ovar macro inline (explanation in macro def comments)
8016 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8017 @end smallexample
8019 @noindent
8020 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8021 unit body. @code{gnatbind} constructs an Ada
8022 package in two files whose names are
8023 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8024 For example, if given the
8025 parameter @file{hello.ali}, for a main program contained in file
8026 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8027 and @file{b~hello.adb}.
8029 When doing consistency checking, the binder takes into consideration
8030 any source files it can locate. For example, if the binder determines
8031 that the given main program requires the package @code{Pack}, whose
8032 @file{.ALI}
8033 file is @file{pack.ali} and whose corresponding source spec file is
8034 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8035 (using the same search path conventions as previously described for the
8036 @command{gcc} command). If it can locate this source file, it checks that
8037 the time stamps
8038 or source checksums of the source and its references to in @file{ALI} files
8039 match. In other words, any @file{ALI} files that mentions this spec must have
8040 resulted from compiling this version of the source file (or in the case
8041 where the source checksums match, a version close enough that the
8042 difference does not matter).
8044 @cindex Source files, use by binder
8045 The effect of this consistency checking, which includes source files, is
8046 that the binder ensures that the program is consistent with the latest
8047 version of the source files that can be located at bind time. Editing a
8048 source file without compiling files that depend on the source file cause
8049 error messages to be generated by the binder.
8051 For example, suppose you have a main program @file{hello.adb} and a
8052 package @code{P}, from file @file{p.ads} and you perform the following
8053 steps:
8055 @enumerate
8056 @item
8057 Enter @code{gcc -c hello.adb} to compile the main program.
8059 @item
8060 Enter @code{gcc -c p.ads} to compile package @code{P}.
8062 @item
8063 Edit file @file{p.ads}.
8065 @item
8066 Enter @code{gnatbind hello}.
8067 @end enumerate
8069 @noindent
8070 At this point, the file @file{p.ali} contains an out-of-date time stamp
8071 because the file @file{p.ads} has been edited. The attempt at binding
8072 fails, and the binder generates the following error messages:
8074 @smallexample
8075 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8076 error: "p.ads" has been modified and must be recompiled
8077 @end smallexample
8079 @noindent
8080 Now both files must be recompiled as indicated, and then the bind can
8081 succeed, generating a main program. You need not normally be concerned
8082 with the contents of this file, but for reference purposes a sample
8083 binder output file is given in @ref{Example of Binder Output File}.
8085 In most normal usage, the default mode of @command{gnatbind} which is to
8086 generate the main package in Ada, as described in the previous section.
8087 In particular, this means that any Ada programmer can read and understand
8088 the generated main program. It can also be debugged just like any other
8089 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8090 @command{gnatbind} and @command{gnatlink}.
8092 @node Switches for gnatbind
8093 @section Switches for @command{gnatbind}
8095 @noindent
8096 The following switches are available with @code{gnatbind}; details will
8097 be presented in subsequent sections.
8099 @menu
8100 * Consistency-Checking Modes::
8101 * Binder Error Message Control::
8102 * Elaboration Control::
8103 * Output Control::
8104 * Dynamic Allocation Control::
8105 * Binding with Non-Ada Main Programs::
8106 * Binding Programs with No Main Subprogram::
8107 @end menu
8109 @table @option
8110 @c !sort!
8112 @item --version
8113 @cindex @option{--version} @command{gnatbind}
8114 Display Copyright and version, then exit disregarding all other options.
8116 @item --help
8117 @cindex @option{--help} @command{gnatbind}
8118 If @option{--version} was not used, display usage, then exit disregarding
8119 all other options.
8121 @item -a
8122 @cindex @option{-a} @command{gnatbind}
8123 Indicates that, if supported by the platform, the adainit procedure should
8124 be treated as an initialisation routine by the linker (a constructor). This
8125 is intended to be used by the Project Manager to automatically initialize
8126 shared Stand-Alone Libraries.
8128 @item ^-aO^/OBJECT_SEARCH^
8129 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8130 Specify directory to be searched for ALI files.
8132 @item ^-aI^/SOURCE_SEARCH^
8133 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8134 Specify directory to be searched for source file.
8136 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8137 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8138 Output ALI list (to standard output or to the named file).
8140 @item ^-b^/REPORT_ERRORS=BRIEF^
8141 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8142 Generate brief messages to @file{stderr} even if verbose mode set.
8144 @item ^-c^/NOOUTPUT^
8145 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8146 Check only, no generation of binder output file.
8148 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8149 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8150 This switch can be used to change the default task stack size value
8151 to a specified size @var{nn}, which is expressed in bytes by default, or
8152 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8153 with @var{m}.
8154 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8155 in effect, to completing all task specs with
8156 @smallexample @c ada
8157    pragma Storage_Size (nn);
8158 @end smallexample
8159 When they do not already have such a pragma.
8161 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8162 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8163 This switch can be used to change the default secondary stack size value
8164 to a specified size @var{nn}, which is expressed in bytes by default, or
8165 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8166 with @var{m}.
8168 The secondary stack is used to deal with functions that return a variable
8169 sized result, for example a function returning an unconstrained
8170 String. There are two ways in which this secondary stack is allocated.
8172 For most targets, the secondary stack is growing on demand and is allocated
8173 as a chain of blocks in the heap. The -D option is not very
8174 relevant. It only give some control over the size of the allocated
8175 blocks (whose size is the minimum of the default secondary stack size value,
8176 and the actual size needed for the current allocation request).
8178 For certain targets, notably VxWorks 653,
8179 the secondary stack is allocated by carving off a fixed ratio chunk of the
8180 primary task stack. The -D option is used to define the
8181 size of the environment task's secondary stack.
8183 @item ^-e^/ELABORATION_DEPENDENCIES^
8184 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8185 Output complete list of elaboration-order dependencies.
8187 @item ^-E^/STORE_TRACEBACKS^
8188 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8189 Store tracebacks in exception occurrences when the target supports it.
8190 @ignore
8191 @c The following may get moved to an appendix
8192 This option is currently supported on the following targets:
8193 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8194 @end ignore
8195 See also the packages @code{GNAT.Traceback} and
8196 @code{GNAT.Traceback.Symbolic} for more information.
8197 @ifclear vms
8198 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8199 @command{gcc} option.
8200 @end ifclear
8202 @item ^-F^/FORCE_ELABS_FLAGS^
8203 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8204 Force the checks of elaboration flags. @command{gnatbind} does not normally
8205 generate checks of elaboration flags for the main executable, except when
8206 a Stand-Alone Library is used. However, there are cases when this cannot be
8207 detected by gnatbind. An example is importing an interface of a Stand-Alone
8208 Library through a pragma Import and only specifying through a linker switch
8209 this Stand-Alone Library. This switch is used to guarantee that elaboration
8210 flag checks are generated.
8212 @item ^-h^/HELP^
8213 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8214 Output usage (help) information
8216 @item ^-H32^/32_MALLOC^
8217 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8218 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8219 For further details see @ref{Dynamic Allocation Control}.
8221 @item ^-H64^/64_MALLOC^
8222 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8223 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8224 @cindex @code{__gnat_malloc}
8225 For further details see @ref{Dynamic Allocation Control}.
8227 @item ^-I^/SEARCH^
8228 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8229 Specify directory to be searched for source and ALI files.
8231 @item ^-I-^/NOCURRENT_DIRECTORY^
8232 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8233 Do not look for sources in the current directory where @code{gnatbind} was
8234 invoked, and do not look for ALI files in the directory containing the
8235 ALI file named in the @code{gnatbind} command line.
8237 @item ^-l^/ORDER_OF_ELABORATION^
8238 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8239 Output chosen elaboration order.
8241 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8242 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8243 Bind the units for library building. In this case the adainit and
8244 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8245 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8246 ^@var{xxx}final^@var{XXX}FINAL^.
8247 Implies ^-n^/NOCOMPILE^.
8248 @ifclear vms
8249 (@xref{GNAT and Libraries}, for more details.)
8250 @end ifclear
8251 @ifset vms
8252 On OpenVMS, these init and final procedures are exported in uppercase
8253 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8254 the init procedure will be "TOTOINIT" and the exported name of the final
8255 procedure will be "TOTOFINAL".
8256 @end ifset
8258 @item ^-Mxyz^/RENAME_MAIN=xyz^
8259 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8260 Rename generated main program from main to xyz. This option is
8261 supported on cross environments only.
8263 @item ^-m^/ERROR_LIMIT=^@var{n}
8264 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8265 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8266 in the range 1..999999. The default value if no switch is
8267 given is 9999. If the number of warnings reaches this limit, then a
8268 message is output and further warnings are suppressed, the bind
8269 continues in this case. If the number of errors reaches this
8270 limit, then a message is output and the bind is abandoned.
8271 A value of zero means that no limit is enforced. The equal
8272 sign is optional.
8274 @ifset unw
8275 Furthermore, under Windows, the sources pointed to by the libraries path
8276 set in the registry are not searched for.
8277 @end ifset
8279 @item ^-n^/NOMAIN^
8280 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8281 No main program.
8283 @item -nostdinc
8284 @cindex @option{-nostdinc} (@command{gnatbind})
8285 Do not look for sources in the system default directory.
8287 @item -nostdlib
8288 @cindex @option{-nostdlib} (@command{gnatbind})
8289 Do not look for library files in the system default directory.
8291 @item --RTS=@var{rts-path}
8292 @cindex @option{--RTS} (@code{gnatbind})
8293 Specifies the default location of the runtime library. Same meaning as the
8294 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8296 @item ^-o ^/OUTPUT=^@var{file}
8297 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8298 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8299 Note that if this option is used, then linking must be done manually,
8300 gnatlink cannot be used.
8302 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8303 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8304 Output object list (to standard output or to the named file).
8306 @item ^-p^/PESSIMISTIC_ELABORATION^
8307 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8308 Pessimistic (worst-case) elaboration order
8310 @item ^-R^-R^
8311 @cindex @option{^-R^-R^} (@command{gnatbind})
8312 Output closure source list.
8314 @item ^-s^/READ_SOURCES=ALL^
8315 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8316 Require all source files to be present.
8318 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8319 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8320 Specifies the value to be used when detecting uninitialized scalar
8321 objects with pragma Initialize_Scalars.
8322 The @var{xxx} ^string specified with the switch^option^ may be either
8323 @itemize @bullet
8324 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8325 @item ``@option{^lo^LOW^}'' for the lowest possible value
8326 @item ``@option{^hi^HIGH^}'' for the highest possible value
8327 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8328 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8329 @end itemize
8331 In addition, you can specify @option{-Sev} to indicate that the value is
8332 to be set at run time. In this case, the program will look for an environment
8333 @cindex GNAT_INIT_SCALARS
8334 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8335 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8336 If no environment variable is found, or if it does not have a valid value,
8337 then the default is @option{in} (invalid values).
8339 @ifclear vms
8340 @item -static
8341 @cindex @option{-static} (@code{gnatbind})
8342 Link against a static GNAT run time.
8344 @item -shared
8345 @cindex @option{-shared} (@code{gnatbind})
8346 Link against a shared GNAT run time when available.
8347 @end ifclear
8349 @item ^-t^/NOTIME_STAMP_CHECK^
8350 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8351 Tolerate time stamp and other consistency errors
8353 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8354 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8355 Set the time slice value to @var{n} milliseconds. If the system supports
8356 the specification of a specific time slice value, then the indicated value
8357 is used. If the system does not support specific time slice values, but
8358 does support some general notion of round-robin scheduling, then any
8359 nonzero value will activate round-robin scheduling.
8361 A value of zero is treated specially. It turns off time
8362 slicing, and in addition, indicates to the tasking run time that the
8363 semantics should match as closely as possible the Annex D
8364 requirements of the Ada RM, and in particular sets the default
8365 scheduling policy to @code{FIFO_Within_Priorities}.
8367 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8368 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8369 Enable dynamic stack usage, with @var{n} results stored and displayed
8370 at program termination. A result is generated when a task
8371 terminates. Results that can't be stored are displayed on the fly, at
8372 task termination. This option is currently not supported on Itanium
8373 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8375 @item ^-v^/REPORT_ERRORS=VERBOSE^
8376 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8377 Verbose mode. Write error messages, header, summary output to
8378 @file{stdout}.
8380 @ifclear vms
8381 @item -w@var{x}
8382 @cindex @option{-w} (@code{gnatbind})
8383 Warning mode (@var{x}=s/e for suppress/treat as error)
8384 @end ifclear
8386 @ifset vms
8387 @item /WARNINGS=NORMAL
8388 @cindex @option{/WARNINGS} (@code{gnatbind})
8389 Normal warnings mode. Warnings are issued but ignored
8391 @item /WARNINGS=SUPPRESS
8392 @cindex @option{/WARNINGS} (@code{gnatbind})
8393 All warning messages are suppressed
8395 @item /WARNINGS=ERROR
8396 @cindex @option{/WARNINGS} (@code{gnatbind})
8397 Warning messages are treated as fatal errors
8398 @end ifset
8400 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8401 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8402 Override default wide character encoding for standard Text_IO files.
8404 @item ^-x^/READ_SOURCES=NONE^
8405 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8406 Exclude source files (check object consistency only).
8408 @ifset vms
8409 @item /READ_SOURCES=AVAILABLE
8410 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8411 Default mode, in which sources are checked for consistency only if
8412 they are available.
8413 @end ifset
8415 @item ^-y^/ENABLE_LEAP_SECONDS^
8416 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8417 Enable leap seconds support in @code{Ada.Calendar} and its children.
8419 @item ^-z^/ZERO_MAIN^
8420 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8421 No main subprogram.
8422 @end table
8424 @ifclear vms
8425 @noindent
8426 You may obtain this listing of switches by running @code{gnatbind} with
8427 no arguments.
8428 @end ifclear
8430 @node Consistency-Checking Modes
8431 @subsection Consistency-Checking Modes
8433 @noindent
8434 As described earlier, by default @code{gnatbind} checks
8435 that object files are consistent with one another and are consistent
8436 with any source files it can locate. The following switches control binder
8437 access to sources.
8439 @table @option
8440 @c !sort!
8441 @item ^-s^/READ_SOURCES=ALL^
8442 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8443 Require source files to be present. In this mode, the binder must be
8444 able to locate all source files that are referenced, in order to check
8445 their consistency. In normal mode, if a source file cannot be located it
8446 is simply ignored. If you specify this switch, a missing source
8447 file is an error.
8449 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8450 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8451 Override default wide character encoding for standard Text_IO files.
8452 Normally the default wide character encoding method used for standard
8453 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8454 the main source input (see description of switch
8455 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8456 use of this switch for the binder (which has the same set of
8457 possible arguments) overrides this default as specified.
8459 @item ^-x^/READ_SOURCES=NONE^
8460 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8461 Exclude source files. In this mode, the binder only checks that ALI
8462 files are consistent with one another. Source files are not accessed.
8463 The binder runs faster in this mode, and there is still a guarantee that
8464 the resulting program is self-consistent.
8465 If a source file has been edited since it was last compiled, and you
8466 specify this switch, the binder will not detect that the object
8467 file is out of date with respect to the source file. Note that this is the
8468 mode that is automatically used by @command{gnatmake} because in this
8469 case the checking against sources has already been performed by
8470 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8472 @ifset vms
8473 @item /READ_SOURCES=AVAILABLE
8474 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8475 This is the default mode in which source files are checked if they are
8476 available, and ignored if they are not available.
8477 @end ifset
8478 @end table
8480 @node Binder Error Message Control
8481 @subsection Binder Error Message Control
8483 @noindent
8484 The following switches provide control over the generation of error
8485 messages from the binder:
8487 @table @option
8488 @c !sort!
8489 @item ^-v^/REPORT_ERRORS=VERBOSE^
8490 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8491 Verbose mode. In the normal mode, brief error messages are generated to
8492 @file{stderr}. If this switch is present, a header is written
8493 to @file{stdout} and any error messages are directed to @file{stdout}.
8494 All that is written to @file{stderr} is a brief summary message.
8496 @item ^-b^/REPORT_ERRORS=BRIEF^
8497 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8498 Generate brief error messages to @file{stderr} even if verbose mode is
8499 specified. This is relevant only when used with the
8500 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8502 @ifclear vms
8503 @item -m@var{n}
8504 @cindex @option{-m} (@code{gnatbind})
8505 Limits the number of error messages to @var{n}, a decimal integer in the
8506 range 1-999. The binder terminates immediately if this limit is reached.
8508 @item -M@var{xxx}
8509 @cindex @option{-M} (@code{gnatbind})
8510 Renames the generated main program from @code{main} to @code{xxx}.
8511 This is useful in the case of some cross-building environments, where
8512 the actual main program is separate from the one generated
8513 by @code{gnatbind}.
8514 @end ifclear
8516 @item ^-ws^/WARNINGS=SUPPRESS^
8517 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8518 @cindex Warnings
8519 Suppress all warning messages.
8521 @item ^-we^/WARNINGS=ERROR^
8522 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8523 Treat any warning messages as fatal errors.
8525 @ifset vms
8526 @item /WARNINGS=NORMAL
8527 Standard mode with warnings generated, but warnings do not get treated
8528 as errors.
8529 @end ifset
8531 @item ^-t^/NOTIME_STAMP_CHECK^
8532 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8533 @cindex Time stamp checks, in binder
8534 @cindex Binder consistency checks
8535 @cindex Consistency checks, in binder
8536 The binder performs a number of consistency checks including:
8538 @itemize @bullet
8539 @item
8540 Check that time stamps of a given source unit are consistent
8541 @item
8542 Check that checksums of a given source unit are consistent
8543 @item
8544 Check that consistent versions of @code{GNAT} were used for compilation
8545 @item
8546 Check consistency of configuration pragmas as required
8547 @end itemize
8549 @noindent
8550 Normally failure of such checks, in accordance with the consistency
8551 requirements of the Ada Reference Manual, causes error messages to be
8552 generated which abort the binder and prevent the output of a binder
8553 file and subsequent link to obtain an executable.
8555 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8556 into warnings, so that
8557 binding and linking can continue to completion even in the presence of such
8558 errors. The result may be a failed link (due to missing symbols), or a
8559 non-functional executable which has undefined semantics.
8560 @emph{This means that
8561 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8562 with extreme care.}
8563 @end table
8565 @node Elaboration Control
8566 @subsection Elaboration Control
8568 @noindent
8569 The following switches provide additional control over the elaboration
8570 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8572 @table @option
8573 @item ^-p^/PESSIMISTIC_ELABORATION^
8574 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8575 Normally the binder attempts to choose an elaboration order that is
8576 likely to minimize the likelihood of an elaboration order error resulting
8577 in raising a @code{Program_Error} exception. This switch reverses the
8578 action of the binder, and requests that it deliberately choose an order
8579 that is likely to maximize the likelihood of an elaboration error.
8580 This is useful in ensuring portability and avoiding dependence on
8581 accidental fortuitous elaboration ordering.
8583 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8584 switch if dynamic
8585 elaboration checking is used (@option{-gnatE} switch used for compilation).
8586 This is because in the default static elaboration mode, all necessary
8587 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8588 These implicit pragmas are still respected by the binder in
8589 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8590 safe elaboration order is assured.
8591 @end table
8593 @node Output Control
8594 @subsection Output Control
8596 @noindent
8597 The following switches allow additional control over the output
8598 generated by the binder.
8600 @table @option
8601 @c !sort!
8603 @item ^-c^/NOOUTPUT^
8604 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8605 Check only. Do not generate the binder output file. In this mode the
8606 binder performs all error checks but does not generate an output file.
8608 @item ^-e^/ELABORATION_DEPENDENCIES^
8609 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8610 Output complete list of elaboration-order dependencies, showing the
8611 reason for each dependency. This output can be rather extensive but may
8612 be useful in diagnosing problems with elaboration order. The output is
8613 written to @file{stdout}.
8615 @item ^-h^/HELP^
8616 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8617 Output usage information. The output is written to @file{stdout}.
8619 @item ^-K^/LINKER_OPTION_LIST^
8620 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8621 Output linker options to @file{stdout}. Includes library search paths,
8622 contents of pragmas Ident and Linker_Options, and libraries added
8623 by @code{gnatbind}.
8625 @item ^-l^/ORDER_OF_ELABORATION^
8626 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8627 Output chosen elaboration order. The output is written to @file{stdout}.
8629 @item ^-O^/OBJECT_LIST^
8630 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8631 Output full names of all the object files that must be linked to provide
8632 the Ada component of the program. The output is written to @file{stdout}.
8633 This list includes the files explicitly supplied and referenced by the user
8634 as well as implicitly referenced run-time unit files. The latter are
8635 omitted if the corresponding units reside in shared libraries. The
8636 directory names for the run-time units depend on the system configuration.
8638 @item ^-o ^/OUTPUT=^@var{file}
8639 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8640 Set name of output file to @var{file} instead of the normal
8641 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8642 binder generated body filename.
8643 Note that if this option is used, then linking must be done manually.
8644 It is not possible to use gnatlink in this case, since it cannot locate
8645 the binder file.
8647 @item ^-r^/RESTRICTION_LIST^
8648 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8649 Generate list of @code{pragma Restrictions} that could be applied to
8650 the current unit. This is useful for code audit purposes, and also may
8651 be used to improve code generation in some cases.
8653 @end table
8655 @node Dynamic Allocation Control
8656 @subsection Dynamic Allocation Control
8658 @noindent
8659 The heap control switches -- @option{-H32} and @option{-H64} --
8660 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8661 They only affect compiler-generated allocations via @code{__gnat_malloc};
8662 explicit calls to @code{malloc} and related functions from the C
8663 run-time library are unaffected.
8665 @table @option
8666 @item -H32
8667 Allocate memory on 32-bit heap
8669 @item -H64
8670 Allocate memory on 64-bit heap.  This is the default
8671 unless explicitly overridden by a @code{'Size} clause on the access type.
8672 @end table
8674 @ifset vms
8675 @noindent
8676 See also @ref{Access types and 32/64-bit allocation}.
8677 @end ifset
8678 @ifclear vms
8679 @noindent
8680 These switches are only effective on VMS platforms.
8681 @end ifclear
8684 @node Binding with Non-Ada Main Programs
8685 @subsection Binding with Non-Ada Main Programs
8687 @noindent
8688 In our description so far we have assumed that the main
8689 program is in Ada, and that the task of the binder is to generate a
8690 corresponding function @code{main} that invokes this Ada main
8691 program. GNAT also supports the building of executable programs where
8692 the main program is not in Ada, but some of the called routines are
8693 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8694 The following switch is used in this situation:
8696 @table @option
8697 @item ^-n^/NOMAIN^
8698 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8699 No main program. The main program is not in Ada.
8700 @end table
8702 @noindent
8703 In this case, most of the functions of the binder are still required,
8704 but instead of generating a main program, the binder generates a file
8705 containing the following callable routines:
8707 @table @code
8708 @item adainit
8709 @findex adainit
8710 You must call this routine to initialize the Ada part of the program by
8711 calling the necessary elaboration routines. A call to @code{adainit} is
8712 required before the first call to an Ada subprogram.
8714 Note that it is assumed that the basic execution environment must be setup
8715 to be appropriate for Ada execution at the point where the first Ada
8716 subprogram is called. In particular, if the Ada code will do any
8717 floating-point operations, then the FPU must be setup in an appropriate
8718 manner. For the case of the x86, for example, full precision mode is
8719 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8720 that the FPU is in the right state.
8722 @item adafinal
8723 @findex adafinal
8724 You must call this routine to perform any library-level finalization
8725 required by the Ada subprograms. A call to @code{adafinal} is required
8726 after the last call to an Ada subprogram, and before the program
8727 terminates.
8728 @end table
8730 @noindent
8731 If the @option{^-n^/NOMAIN^} switch
8732 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8733 @cindex Binder, multiple input files
8734 is given, more than one ALI file may appear on
8735 the command line for @code{gnatbind}. The normal @dfn{closure}
8736 calculation is performed for each of the specified units. Calculating
8737 the closure means finding out the set of units involved by tracing
8738 @code{with} references. The reason it is necessary to be able to
8739 specify more than one ALI file is that a given program may invoke two or
8740 more quite separate groups of Ada units.
8742 The binder takes the name of its output file from the last specified ALI
8743 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8744 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8745 The output is an Ada unit in source form that can be compiled with GNAT.
8746 This compilation occurs automatically as part of the @command{gnatlink}
8747 processing.
8749 Currently the GNAT run time requires a FPU using 80 bits mode
8750 precision. Under targets where this is not the default it is required to
8751 call GNAT.Float_Control.Reset before using floating point numbers (this
8752 include float computation, float input and output) in the Ada code. A
8753 side effect is that this could be the wrong mode for the foreign code
8754 where floating point computation could be broken after this call.
8756 @node Binding Programs with No Main Subprogram
8757 @subsection Binding Programs with No Main Subprogram
8759 @noindent
8760 It is possible to have an Ada program which does not have a main
8761 subprogram. This program will call the elaboration routines of all the
8762 packages, then the finalization routines.
8764 The following switch is used to bind programs organized in this manner:
8766 @table @option
8767 @item ^-z^/ZERO_MAIN^
8768 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8769 Normally the binder checks that the unit name given on the command line
8770 corresponds to a suitable main subprogram. When this switch is used,
8771 a list of ALI files can be given, and the execution of the program
8772 consists of elaboration of these units in an appropriate order. Note
8773 that the default wide character encoding method for standard Text_IO
8774 files is always set to Brackets if this switch is set (you can use
8775 the binder switch
8776 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8777 @end table
8779 @node Command-Line Access
8780 @section Command-Line Access
8782 @noindent
8783 The package @code{Ada.Command_Line} provides access to the command-line
8784 arguments and program name. In order for this interface to operate
8785 correctly, the two variables
8787 @smallexample
8788 @group
8789 int gnat_argc;
8790 char **gnat_argv;
8791 @end group
8792 @end smallexample
8794 @noindent
8795 @findex gnat_argv
8796 @findex gnat_argc
8797 are declared in one of the GNAT library routines. These variables must
8798 be set from the actual @code{argc} and @code{argv} values passed to the
8799 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8800 generates the C main program to automatically set these variables.
8801 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8802 set these variables. If they are not set, the procedures in
8803 @code{Ada.Command_Line} will not be available, and any attempt to use
8804 them will raise @code{Constraint_Error}. If command line access is
8805 required, your main program must set @code{gnat_argc} and
8806 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8809 @node Search Paths for gnatbind
8810 @section Search Paths for @code{gnatbind}
8812 @noindent
8813 The binder takes the name of an ALI file as its argument and needs to
8814 locate source files as well as other ALI files to verify object consistency.
8816 For source files, it follows exactly the same search rules as @command{gcc}
8817 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8818 directories searched are:
8820 @enumerate
8821 @item
8822 The directory containing the ALI file named in the command line, unless
8823 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8825 @item
8826 All directories specified by @option{^-I^/SEARCH^}
8827 switches on the @code{gnatbind}
8828 command line, in the order given.
8830 @item
8831 @findex ADA_PRJ_OBJECTS_FILE
8832 Each of the directories listed in the text file whose name is given
8833 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8835 @noindent
8836 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8837 driver when project files are used. It should not normally be set
8838 by other means.
8840 @item
8841 @findex ADA_OBJECTS_PATH
8842 Each of the directories listed in the value of the
8843 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8844 @ifset unw
8845 Construct this value
8846 exactly as the @env{PATH} environment variable: a list of directory
8847 names separated by colons (semicolons when working with the NT version
8848 of GNAT).
8849 @end ifset
8850 @ifset vms
8851 Normally, define this value as a logical name containing a comma separated
8852 list of directory names.
8854 This variable can also be defined by means of an environment string
8855 (an argument to the HP C exec* set of functions).
8857 Logical Name:
8858 @smallexample
8859 DEFINE ANOTHER_PATH FOO:[BAG]
8860 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8861 @end smallexample
8863 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8864 first, followed by the standard Ada
8865 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8866 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8867 (Text_IO, Sequential_IO, etc)
8868 instead of the standard Ada packages. Thus, in order to get the standard Ada
8869 packages by default, ADA_OBJECTS_PATH must be redefined.
8870 @end ifset
8872 @item
8873 The content of the @file{ada_object_path} file which is part of the GNAT
8874 installation tree and is used to store standard libraries such as the
8875 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8876 specified.
8877 @ifclear vms
8878 @ref{Installing a library}
8879 @end ifclear
8880 @end enumerate
8882 @noindent
8883 In the binder the switch @option{^-I^/SEARCH^}
8884 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8885 is used to specify both source and
8886 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8887 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8888 instead if you want to specify
8889 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8890 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8891 if you want to specify library paths
8892 only. This means that for the binder
8893 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8894 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8895 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8896 The binder generates the bind file (a C language source file) in the
8897 current working directory.
8899 @findex Ada
8900 @findex System
8901 @findex Interfaces
8902 @findex GNAT
8903 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8904 children make up the GNAT Run-Time Library, together with the package
8905 GNAT and its children, which contain a set of useful additional
8906 library functions provided by GNAT. The sources for these units are
8907 needed by the compiler and are kept together in one directory. The ALI
8908 files and object files generated by compiling the RTL are needed by the
8909 binder and the linker and are kept together in one directory, typically
8910 different from the directory containing the sources. In a normal
8911 installation, you need not specify these directory names when compiling
8912 or binding. Either the environment variables or the built-in defaults
8913 cause these files to be found.
8915 Besides simplifying access to the RTL, a major use of search paths is
8916 in compiling sources from multiple directories. This can make
8917 development environments much more flexible.
8919 @node Examples of gnatbind Usage
8920 @section Examples of @code{gnatbind} Usage
8922 @noindent
8923 This section contains a number of examples of using the GNAT binding
8924 utility @code{gnatbind}.
8926 @table @code
8927 @item gnatbind hello
8928 The main program @code{Hello} (source program in @file{hello.adb}) is
8929 bound using the standard switch settings. The generated main program is
8930 @file{b~hello.adb}. This is the normal, default use of the binder.
8932 @ifclear vms
8933 @item gnatbind hello -o mainprog.adb
8934 @end ifclear
8935 @ifset vms
8936 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8937 @end ifset
8938 The main program @code{Hello} (source program in @file{hello.adb}) is
8939 bound using the standard switch settings. The generated main program is
8940 @file{mainprog.adb} with the associated spec in
8941 @file{mainprog.ads}. Note that you must specify the body here not the
8942 spec. Note that if this option is used, then linking must be done manually,
8943 since gnatlink will not be able to find the generated file.
8944 @end table
8946 @c ------------------------------------
8947 @node Linking Using gnatlink
8948 @chapter Linking Using @command{gnatlink}
8949 @c ------------------------------------
8950 @findex gnatlink
8952 @noindent
8953 This chapter discusses @command{gnatlink}, a tool that links
8954 an Ada program and builds an executable file. This utility
8955 invokes the system linker ^(via the @command{gcc} command)^^
8956 with a correct list of object files and library references.
8957 @command{gnatlink} automatically determines the list of files and
8958 references for the Ada part of a program. It uses the binder file
8959 generated by the @command{gnatbind} to determine this list.
8961 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8962 driver (see @ref{The GNAT Driver and Project Files}).
8964 @menu
8965 * Running gnatlink::
8966 * Switches for gnatlink::
8967 @end menu
8969 @node Running gnatlink
8970 @section Running @command{gnatlink}
8972 @noindent
8973 The form of the @command{gnatlink} command is
8975 @smallexample
8976 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8977 @c            @ovar{non-Ada objects} @ovar{linker options}
8978 @c Expanding @ovar macro inline (explanation in macro def comments)
8979 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8980            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8982 @end smallexample
8984 @noindent
8985 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8986 non-Ada objects
8987 or linker options) may be in any order, provided that no non-Ada object may
8988 be mistaken for a main @file{ALI} file.
8989 Any file name @file{F} without the @file{.ali}
8990 extension will be taken as the main @file{ALI} file if a file exists
8991 whose name is the concatenation of @file{F} and @file{.ali}.
8993 @noindent
8994 @file{@var{mainprog}.ali} references the ALI file of the main program.
8995 The @file{.ali} extension of this file can be omitted. From this
8996 reference, @command{gnatlink} locates the corresponding binder file
8997 @file{b~@var{mainprog}.adb} and, using the information in this file along
8998 with the list of non-Ada objects and linker options, constructs a
8999 linker command file to create the executable.
9001 The arguments other than the @command{gnatlink} switches and the main
9002 @file{ALI} file are passed to the linker uninterpreted.
9003 They typically include the names of
9004 object files for units written in other languages than Ada and any library
9005 references required to resolve references in any of these foreign language
9006 units, or in @code{Import} pragmas in any Ada units.
9008 @var{linker options} is an optional list of linker specific
9009 switches.
9010 The default linker called by gnatlink is @command{gcc} which in
9011 turn calls the appropriate system linker.
9012 Standard options for the linker such as @option{-lmy_lib} or
9013 @option{-Ldir} can be added as is.
9014 For options that are not recognized by
9015 @command{gcc} as linker options, use the @command{gcc} switches
9016 @option{-Xlinker} or @option{-Wl,}.
9017 Refer to the GCC documentation for
9018 details. Here is an example showing how to generate a linker map:
9020 @smallexample
9021 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9022 @end smallexample
9024 Using @var{linker options} it is possible to set the program stack and
9025 heap size.
9026 @ifset unw
9027 See @ref{Setting Stack Size from gnatlink} and
9028 @ref{Setting Heap Size from gnatlink}.
9029 @end ifset
9031 @command{gnatlink} determines the list of objects required by the Ada
9032 program and prepends them to the list of objects passed to the linker.
9033 @command{gnatlink} also gathers any arguments set by the use of
9034 @code{pragma Linker_Options} and adds them to the list of arguments
9035 presented to the linker.
9037 @ifset vms
9038 @command{gnatlink} accepts the following types of extra files on the command
9039 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9040 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9041 handled according to their extension.
9042 @end ifset
9044 @node Switches for gnatlink
9045 @section Switches for @command{gnatlink}
9047 @noindent
9048 The following switches are available with the @command{gnatlink} utility:
9050 @table @option
9051 @c !sort!
9053 @item --version
9054 @cindex @option{--version} @command{gnatlink}
9055 Display Copyright and version, then exit disregarding all other options.
9057 @item --help
9058 @cindex @option{--help} @command{gnatlink}
9059 If @option{--version} was not used, display usage, then exit disregarding
9060 all other options.
9062 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9063 @cindex Command line length
9064 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9065 On some targets, the command line length is limited, and @command{gnatlink}
9066 will generate a separate file for the linker if the list of object files
9067 is too long.
9068 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9069 to be generated even if
9070 the limit is not exceeded. This is useful in some cases to deal with
9071 special situations where the command line length is exceeded.
9073 @item ^-g^/DEBUG^
9074 @cindex Debugging information, including
9075 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9076 The option to include debugging information causes the Ada bind file (in
9077 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9078 @option{^-g^/DEBUG^}.
9079 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9080 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9081 Without @option{^-g^/DEBUG^}, the binder removes these files by
9082 default. The same procedure apply if a C bind file was generated using
9083 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9084 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9086 @item ^-n^/NOCOMPILE^
9087 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9088 Do not compile the file generated by the binder. This may be used when
9089 a link is rerun with different options, but there is no need to recompile
9090 the binder file.
9092 @item ^-v^/VERBOSE^
9093 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9094 Causes additional information to be output, including a full list of the
9095 included object files. This switch option is most useful when you want
9096 to see what set of object files are being used in the link step.
9098 @item ^-v -v^/VERBOSE/VERBOSE^
9099 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9100 Very verbose mode. Requests that the compiler operate in verbose mode when
9101 it compiles the binder file, and that the system linker run in verbose mode.
9103 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9104 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9105 @var{exec-name} specifies an alternate name for the generated
9106 executable program. If this switch is omitted, the executable has the same
9107 name as the main unit. For example, @code{gnatlink try.ali} creates
9108 an executable called @file{^try^TRY.EXE^}.
9110 @ifclear vms
9111 @item -b @var{target}
9112 @cindex @option{-b} (@command{gnatlink})
9113 Compile your program to run on @var{target}, which is the name of a
9114 system configuration. You must have a GNAT cross-compiler built if
9115 @var{target} is not the same as your host system.
9117 @item -B@var{dir}
9118 @cindex @option{-B} (@command{gnatlink})
9119 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9120 from @var{dir} instead of the default location. Only use this switch
9121 when multiple versions of the GNAT compiler are available.
9122 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9123 for further details. You would normally use the @option{-b} or
9124 @option{-V} switch instead.
9126 @item --GCC=@var{compiler_name}
9127 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9128 Program used for compiling the binder file. The default is
9129 @command{gcc}. You need to use quotes around @var{compiler_name} if
9130 @code{compiler_name} contains spaces or other separator characters.
9131 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9132 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9133 inserted after your command name. Thus in the above example the compiler
9134 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9135 A limitation of this syntax is that the name and path name of the executable
9136 itself must not include any embedded spaces. If the compiler executable is
9137 different from the default one (gcc or <prefix>-gcc), then the back-end
9138 switches in the ALI file are not used to compile the binder generated source.
9139 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9140 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9141 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9142 is taken into account. However, all the additional switches are also taken
9143 into account. Thus,
9144 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9145 @option{--GCC="bar -x -y -z -t"}.
9147 @item --LINK=@var{name}
9148 @cindex @option{--LINK=} (@command{gnatlink})
9149 @var{name} is the name of the linker to be invoked. This is especially
9150 useful in mixed language programs since languages such as C++ require
9151 their own linker to be used. When this switch is omitted, the default
9152 name for the linker is @command{gcc}. When this switch is used, the
9153 specified linker is called instead of @command{gcc} with exactly the same
9154 parameters that would have been passed to @command{gcc} so if the desired
9155 linker requires different parameters it is necessary to use a wrapper
9156 script that massages the parameters before invoking the real linker. It
9157 may be useful to control the exact invocation by using the verbose
9158 switch.
9160 @end ifclear
9162 @ifset vms
9163 @item /DEBUG=TRACEBACK
9164 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9165 This qualifier causes sufficient information to be included in the
9166 executable file to allow a traceback, but does not include the full
9167 symbol information needed by the debugger.
9169 @item /IDENTIFICATION="<string>"
9170 @code{"<string>"} specifies the string to be stored in the image file
9171 identification field in the image header.
9172 It overrides any pragma @code{Ident} specified string.
9174 @item /NOINHIBIT-EXEC
9175 Generate the executable file even if there are linker warnings.
9177 @item /NOSTART_FILES
9178 Don't link in the object file containing the ``main'' transfer address.
9179 Used when linking with a foreign language main program compiled with an
9180 HP compiler.
9182 @item /STATIC
9183 Prefer linking with object libraries over sharable images, even without
9184 /DEBUG.
9185 @end ifset
9187 @end table
9189 @node The GNAT Make Program gnatmake
9190 @chapter The GNAT Make Program @command{gnatmake}
9191 @findex gnatmake
9193 @menu
9194 * Running gnatmake::
9195 * Switches for gnatmake::
9196 * Mode Switches for gnatmake::
9197 * Notes on the Command Line::
9198 * How gnatmake Works::
9199 * Examples of gnatmake Usage::
9200 @end menu
9201 @noindent
9202 A typical development cycle when working on an Ada program consists of
9203 the following steps:
9205 @enumerate
9206 @item
9207 Edit some sources to fix bugs.
9209 @item
9210 Add enhancements.
9212 @item
9213 Compile all sources affected.
9215 @item
9216 Rebind and relink.
9218 @item
9219 Test.
9220 @end enumerate
9222 @noindent
9223 The third step can be tricky, because not only do the modified files
9224 @cindex Dependency rules
9225 have to be compiled, but any files depending on these files must also be
9226 recompiled. The dependency rules in Ada can be quite complex, especially
9227 in the presence of overloading, @code{use} clauses, generics and inlined
9228 subprograms.
9230 @command{gnatmake} automatically takes care of the third and fourth steps
9231 of this process. It determines which sources need to be compiled,
9232 compiles them, and binds and links the resulting object files.
9234 Unlike some other Ada make programs, the dependencies are always
9235 accurately recomputed from the new sources. The source based approach of
9236 the GNAT compilation model makes this possible. This means that if
9237 changes to the source program cause corresponding changes in
9238 dependencies, they will always be tracked exactly correctly by
9239 @command{gnatmake}.
9241 @node Running gnatmake
9242 @section Running @command{gnatmake}
9244 @noindent
9245 The usual form of the @command{gnatmake} command is
9247 @smallexample
9248 @c $ gnatmake @ovar{switches} @var{file_name}
9249 @c       @ovar{file_names} @ovar{mode_switches}
9250 @c Expanding @ovar macro inline (explanation in macro def comments)
9251 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9252       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9253 @end smallexample
9255 @noindent
9256 The only required argument is one @var{file_name}, which specifies
9257 a compilation unit that is a main program. Several @var{file_names} can be
9258 specified: this will result in several executables being built.
9259 If @code{switches} are present, they can be placed before the first
9260 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9261 If @var{mode_switches} are present, they must always be placed after
9262 the last @var{file_name} and all @code{switches}.
9264 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9265 extension may be omitted from the @var{file_name} arguments. However, if
9266 you are using non-standard extensions, then it is required that the
9267 extension be given. A relative or absolute directory path can be
9268 specified in a @var{file_name}, in which case, the input source file will
9269 be searched for in the specified directory only. Otherwise, the input
9270 source file will first be searched in the directory where
9271 @command{gnatmake} was invoked and if it is not found, it will be search on
9272 the source path of the compiler as described in
9273 @ref{Search Paths and the Run-Time Library (RTL)}.
9275 All @command{gnatmake} output (except when you specify
9276 @option{^-M^/DEPENDENCIES_LIST^}) is to
9277 @file{stderr}. The output produced by the
9278 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9279 @file{stdout}.
9281 @node Switches for gnatmake
9282 @section Switches for @command{gnatmake}
9284 @noindent
9285 You may specify any of the following switches to @command{gnatmake}:
9287 @table @option
9288 @c !sort!
9290 @item --version
9291 @cindex @option{--version} @command{gnatmake}
9292 Display Copyright and version, then exit disregarding all other options.
9294 @item --help
9295 @cindex @option{--help} @command{gnatmake}
9296 If @option{--version} was not used, display usage, then exit disregarding
9297 all other options.
9299 @ifclear vms
9300 @item --GCC=@var{compiler_name}
9301 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9302 Program used for compiling. The default is `@command{gcc}'. You need to use
9303 quotes around @var{compiler_name} if @code{compiler_name} contains
9304 spaces or other separator characters. As an example @option{--GCC="foo -x
9305 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9306 compiler. A limitation of this syntax is that the name and path name of
9307 the executable itself must not include any embedded spaces. Note that
9308 switch @option{-c} is always inserted after your command name. Thus in the
9309 above example the compiler command that will be used by @command{gnatmake}
9310 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9311 used, only the last @var{compiler_name} is taken into account. However,
9312 all the additional switches are also taken into account. Thus,
9313 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9314 @option{--GCC="bar -x -y -z -t"}.
9316 @item --GNATBIND=@var{binder_name}
9317 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9318 Program used for binding. The default is `@code{gnatbind}'. You need to
9319 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9320 or other separator characters. As an example @option{--GNATBIND="bar -x
9321 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9322 binder. Binder switches that are normally appended by @command{gnatmake}
9323 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9324 A limitation of this syntax is that the name and path name of the executable
9325 itself must not include any embedded spaces.
9327 @item --GNATLINK=@var{linker_name}
9328 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9329 Program used for linking. The default is `@command{gnatlink}'. You need to
9330 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9331 or other separator characters. As an example @option{--GNATLINK="lan -x
9332 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9333 linker. Linker switches that are normally appended by @command{gnatmake} to
9334 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9335 A limitation of this syntax is that the name and path name of the executable
9336 itself must not include any embedded spaces.
9338 @end ifclear
9340 @item ^--subdirs^/SUBDIRS^=subdir
9341 Actual object directory of each project file is the subdirectory subdir of the
9342 object directory specified or defaulted in the project file.
9344 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9345 Disallow simultaneous compilations in the same object directory when
9346 project files are used.
9348 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9349 By default, shared library projects are not allowed to import static library
9350 projects. When this switch is used on the command line, this restriction is
9351 relaxed.
9353 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9354 Specify a source info file. This switch is active only when project files
9355 are used. If the source info file is specified as a relative path, then it is
9356 relative to the object directory of the main project. If the source info file
9357 does not exist, then after the Project Manager has successfully parsed and
9358 processed the project files and found the sources, it creates the source info
9359 file. If the source info file already exists and can be read successfully,
9360 then the Project Manager will get all the needed information about the sources
9361 from the source info file and will not look for them. This reduces the time
9362 to process the project files, especially when looking for sources that take a
9363 long time. If the source info file exists but cannot be parsed successfully,
9364 the Project Manager will attempt to recreate it. If the Project Manager fails
9365 to create the source info file, a message is issued, but gnatmake does not
9366 fail.
9368 @ifclear vms
9369 @item --create-map-file
9370 When linking an executable, create a map file. The name of the map file
9371 has the same name as the executable with extension ".map".
9373 @item --create-map-file=mapfile
9374 When linking an executable, create a map file. The name of the map file is
9375 "mapfile".
9377 @end ifclear
9379 @item ^-a^/ALL_FILES^
9380 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9381 Consider all files in the make process, even the GNAT internal system
9382 files (for example, the predefined Ada library files), as well as any
9383 locked files. Locked files are files whose ALI file is write-protected.
9384 By default,
9385 @command{gnatmake} does not check these files,
9386 because the assumption is that the GNAT internal files are properly up
9387 to date, and also that any write protected ALI files have been properly
9388 installed. Note that if there is an installation problem, such that one
9389 of these files is not up to date, it will be properly caught by the
9390 binder.
9391 You may have to specify this switch if you are working on GNAT
9392 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9393 in conjunction with @option{^-f^/FORCE_COMPILE^}
9394 if you need to recompile an entire application,
9395 including run-time files, using special configuration pragmas,
9396 such as a @code{Normalize_Scalars} pragma.
9398 By default
9399 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9400 internal files with
9401 @ifclear vms
9402 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9403 @end ifclear
9404 @ifset vms
9405 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9406 @end ifset
9408 @item ^-b^/ACTIONS=BIND^
9409 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9410 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9411 compilation and binding, but no link.
9412 Can be combined with @option{^-l^/ACTIONS=LINK^}
9413 to do binding and linking. When not combined with
9414 @option{^-c^/ACTIONS=COMPILE^}
9415 all the units in the closure of the main program must have been previously
9416 compiled and must be up to date. The root unit specified by @var{file_name}
9417 may be given without extension, with the source extension or, if no GNAT
9418 Project File is specified, with the ALI file extension.
9420 @item ^-c^/ACTIONS=COMPILE^
9421 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9422 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9423 is also specified. Do not perform linking, except if both
9424 @option{^-b^/ACTIONS=BIND^} and
9425 @option{^-l^/ACTIONS=LINK^} are also specified.
9426 If the root unit specified by @var{file_name} is not a main unit, this is the
9427 default. Otherwise @command{gnatmake} will attempt binding and linking
9428 unless all objects are up to date and the executable is more recent than
9429 the objects.
9431 @item ^-C^/MAPPING^
9432 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9433 Use a temporary mapping file. A mapping file is a way to communicate
9434 to the compiler two mappings: from unit names to file names (without
9435 any directory information) and from file names to path names (with
9436 full directory information). A mapping file can make the compiler's
9437 file searches faster, especially if there are many source directories,
9438 or the sources are read over a slow network connection. If
9439 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9440 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9441 is initially populated based on the project file. If
9442 @option{^-C^/MAPPING^} is used without
9443 @option{^-P^/PROJECT_FILE^},
9444 the mapping file is initially empty. Each invocation of the compiler
9445 will add any newly accessed sources to the mapping file.
9447 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9448 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9449 Use a specific mapping file. The file, specified as a path name (absolute or
9450 relative) by this switch, should already exist, otherwise the switch is
9451 ineffective. The specified mapping file will be communicated to the compiler.
9452 This switch is not compatible with a project file
9453 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9454 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9456 @item ^-d^/DISPLAY_PROGRESS^
9457 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9458 Display progress for each source, up to date or not, as a single line
9460 @smallexample
9461 completed x out of y (zz%)
9462 @end smallexample
9464 If the file needs to be compiled this is displayed after the invocation of
9465 the compiler. These lines are displayed even in quiet output mode.
9467 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9468 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9469 Put all object files and ALI file in directory @var{dir}.
9470 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9471 and ALI files go in the current working directory.
9473 This switch cannot be used when using a project file.
9475 @ifclear vms
9476 @item -eL
9477 @cindex @option{-eL} (@command{gnatmake})
9478 @cindex symbolic links
9479 Follow all symbolic links when processing project files.
9480 This should be used if your project uses symbolic links for files or
9481 directories, but is not needed in other cases.
9483 @cindex naming scheme
9484 This also assumes that no directory matches the naming scheme for files (for
9485 instance that you do not have a directory called "sources.ads" when using the
9486 default GNAT naming scheme).
9488 When you do not have to use this switch (ie by default), gnatmake is able to
9489 save a lot of system calls (several per source file and object file), which
9490 can result in a significant speed up to load and manipulate a project file,
9491 especially when using source files from a remote system.
9493 @end ifclear
9495 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9496 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9497 Output the commands for the compiler, the binder and the linker
9498 on ^standard output^SYS$OUTPUT^,
9499 instead of ^standard error^SYS$ERROR^.
9501 @item ^-f^/FORCE_COMPILE^
9502 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9503 Force recompilations. Recompile all sources, even though some object
9504 files may be up to date, but don't recompile predefined or GNAT internal
9505 files or locked files (files with a write-protected ALI file),
9506 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9508 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9509 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9510 When using project files, if some errors or warnings are detected during
9511 parsing and verbose mode is not in effect (no use of switch
9512 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9513 file, rather than its simple file name.
9515 @item ^-g^/DEBUG^
9516 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9517 Enable debugging. This switch is simply passed to the compiler and to the
9518 linker.
9520 @item ^-i^/IN_PLACE^
9521 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9522 In normal mode, @command{gnatmake} compiles all object files and ALI files
9523 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9524 then instead object files and ALI files that already exist are overwritten
9525 in place. This means that once a large project is organized into separate
9526 directories in the desired manner, then @command{gnatmake} will automatically
9527 maintain and update this organization. If no ALI files are found on the
9528 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9529 the new object and ALI files are created in the
9530 directory containing the source being compiled. If another organization
9531 is desired, where objects and sources are kept in different directories,
9532 a useful technique is to create dummy ALI files in the desired directories.
9533 When detecting such a dummy file, @command{gnatmake} will be forced to
9534 recompile the corresponding source file, and it will be put the resulting
9535 object and ALI files in the directory where it found the dummy file.
9537 @item ^-j^/PROCESSES=^@var{n}
9538 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9539 @cindex Parallel make
9540 Use @var{n} processes to carry out the (re)compilations. On a
9541 multiprocessor machine compilations will occur in parallel. In the
9542 event of compilation errors, messages from various compilations might
9543 get interspersed (but @command{gnatmake} will give you the full ordered
9544 list of failing compiles at the end). If this is problematic, rerun
9545 the make process with n set to 1 to get a clean list of messages.
9547 @item ^-k^/CONTINUE_ON_ERROR^
9548 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9549 Keep going. Continue as much as possible after a compilation error. To
9550 ease the programmer's task in case of compilation errors, the list of
9551 sources for which the compile fails is given when @command{gnatmake}
9552 terminates.
9554 If @command{gnatmake} is invoked with several @file{file_names} and with this
9555 switch, if there are compilation errors when building an executable,
9556 @command{gnatmake} will not attempt to build the following executables.
9558 @item ^-l^/ACTIONS=LINK^
9559 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9560 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9561 and linking. Linking will not be performed if combined with
9562 @option{^-c^/ACTIONS=COMPILE^}
9563 but not with @option{^-b^/ACTIONS=BIND^}.
9564 When not combined with @option{^-b^/ACTIONS=BIND^}
9565 all the units in the closure of the main program must have been previously
9566 compiled and must be up to date, and the main program needs to have been bound.
9567 The root unit specified by @var{file_name}
9568 may be given without extension, with the source extension or, if no GNAT
9569 Project File is specified, with the ALI file extension.
9571 @item ^-m^/MINIMAL_RECOMPILATION^
9572 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9573 Specify that the minimum necessary amount of recompilations
9574 be performed. In this mode @command{gnatmake} ignores time
9575 stamp differences when the only
9576 modifications to a source file consist in adding/removing comments,
9577 empty lines, spaces or tabs. This means that if you have changed the
9578 comments in a source file or have simply reformatted it, using this
9579 switch will tell @command{gnatmake} not to recompile files that depend on it
9580 (provided other sources on which these files depend have undergone no
9581 semantic modifications). Note that the debugging information may be
9582 out of date with respect to the sources if the @option{-m} switch causes
9583 a compilation to be switched, so the use of this switch represents a
9584 trade-off between compilation time and accurate debugging information.
9586 @item ^-M^/DEPENDENCIES_LIST^
9587 @cindex Dependencies, producing list
9588 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9589 Check if all objects are up to date. If they are, output the object
9590 dependences to @file{stdout} in a form that can be directly exploited in
9591 a @file{Makefile}. By default, each source file is prefixed with its
9592 (relative or absolute) directory name. This name is whatever you
9593 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9594 and @option{^-I^/SEARCH^} switches. If you use
9595 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9596 @option{^-q^/QUIET^}
9597 (see below), only the source file names,
9598 without relative paths, are output. If you just specify the
9599 @option{^-M^/DEPENDENCIES_LIST^}
9600 switch, dependencies of the GNAT internal system files are omitted. This
9601 is typically what you want. If you also specify
9602 the @option{^-a^/ALL_FILES^} switch,
9603 dependencies of the GNAT internal files are also listed. Note that
9604 dependencies of the objects in external Ada libraries (see switch
9605 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9606 are never reported.
9608 @item ^-n^/DO_OBJECT_CHECK^
9609 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9610 Don't compile, bind, or link. Checks if all objects are up to date.
9611 If they are not, the full name of the first file that needs to be
9612 recompiled is printed.
9613 Repeated use of this option, followed by compiling the indicated source
9614 file, will eventually result in recompiling all required units.
9616 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9617 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9618 Output executable name. The name of the final executable program will be
9619 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9620 name for the executable will be the name of the input file in appropriate form
9621 for an executable file on the host system.
9623 This switch cannot be used when invoking @command{gnatmake} with several
9624 @file{file_names}.
9626 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9627 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9628 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9629 automatically missing object directories, library directories and exec
9630 directories.
9632 @item ^-P^/PROJECT_FILE=^@var{project}
9633 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9634 Use project file @var{project}. Only one such switch can be used.
9635 @xref{gnatmake and Project Files}.
9637 @item ^-q^/QUIET^
9638 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9639 Quiet. When this flag is not set, the commands carried out by
9640 @command{gnatmake} are displayed.
9642 @item ^-s^/SWITCH_CHECK/^
9643 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9644 Recompile if compiler switches have changed since last compilation.
9645 All compiler switches but -I and -o are taken into account in the
9646 following way:
9647 orders between different ``first letter'' switches are ignored, but
9648 orders between same switches are taken into account. For example,
9649 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9650 is equivalent to @option{-O -g}.
9652 This switch is recommended when Integrated Preprocessing is used.
9654 @item ^-u^/UNIQUE^
9655 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9656 Unique. Recompile at most the main files. It implies -c. Combined with
9657 -f, it is equivalent to calling the compiler directly. Note that using
9658 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9659 (@pxref{Project Files and Main Subprograms}).
9661 @item ^-U^/ALL_PROJECTS^
9662 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9663 When used without a project file or with one or several mains on the command
9664 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9665 on the command line, all sources of all project files are checked and compiled
9666 if not up to date, and libraries are rebuilt, if necessary.
9668 @item ^-v^/REASONS^
9669 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9670 Verbose. Display the reason for all recompilations @command{gnatmake}
9671 decides are necessary, with the highest verbosity level.
9673 @item ^-vl^/LOW_VERBOSITY^
9674 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9675 Verbosity level Low. Display fewer lines than in verbosity Medium.
9677 @item ^-vm^/MEDIUM_VERBOSITY^
9678 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9679 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9681 @item ^-vh^/HIGH_VERBOSITY^
9682 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9683 Verbosity level High. Equivalent to ^-v^/REASONS^.
9685 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9686 Indicate the verbosity of the parsing of GNAT project files.
9687 @xref{Switches Related to Project Files}.
9689 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9690 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9691 Indicate that sources that are not part of any Project File may be compiled.
9692 Normally, when using Project Files, only sources that are part of a Project
9693 File may be compile. When this switch is used, a source outside of all Project
9694 Files may be compiled. The ALI file and the object file will be put in the
9695 object directory of the main Project. The compilation switches used will only
9696 be those specified on the command line. Even when
9697 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9698 command line need to be sources of a project file.
9700 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9701 Indicate that external variable @var{name} has the value @var{value}.
9702 The Project Manager will use this value for occurrences of
9703 @code{external(name)} when parsing the project file.
9704 @xref{Switches Related to Project Files}.
9706 @item ^-z^/NOMAIN^
9707 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9708 No main subprogram. Bind and link the program even if the unit name
9709 given on the command line is a package name. The resulting executable
9710 will execute the elaboration routines of the package and its closure,
9711 then the finalization routines.
9713 @end table
9715 @table @asis
9716 @item @command{gcc} @asis{switches}
9717 @ifclear vms
9718 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9719 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9720 @end ifclear
9721 @ifset vms
9722 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9723 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9724 automatically treated as a compiler switch, and passed on to all
9725 compilations that are carried out.
9726 @end ifset
9727 @end table
9729 @noindent
9730 Source and library search path switches:
9732 @table @option
9733 @c !sort!
9734 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9735 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9736 When looking for source files also look in directory @var{dir}.
9737 The order in which source files search is undertaken is
9738 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9740 @item ^-aL^/SKIP_MISSING=^@var{dir}
9741 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9742 Consider @var{dir} as being an externally provided Ada library.
9743 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9744 files have been located in directory @var{dir}. This allows you to have
9745 missing bodies for the units in @var{dir} and to ignore out of date bodies
9746 for the same units. You still need to specify
9747 the location of the specs for these units by using the switches
9748 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9749 or @option{^-I^/SEARCH=^@var{dir}}.
9750 Note: this switch is provided for compatibility with previous versions
9751 of @command{gnatmake}. The easier method of causing standard libraries
9752 to be excluded from consideration is to write-protect the corresponding
9753 ALI files.
9755 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9756 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9757 When searching for library and object files, look in directory
9758 @var{dir}. The order in which library files are searched is described in
9759 @ref{Search Paths for gnatbind}.
9761 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9762 @cindex Search paths, for @command{gnatmake}
9763 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9764 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9765 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9767 @item ^-I^/SEARCH=^@var{dir}
9768 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9769 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9770 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9772 @item ^-I-^/NOCURRENT_DIRECTORY^
9773 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9774 @cindex Source files, suppressing search
9775 Do not look for source files in the directory containing the source
9776 file named in the command line.
9777 Do not look for ALI or object files in the directory
9778 where @command{gnatmake} was invoked.
9780 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9781 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9782 @cindex Linker libraries
9783 Add directory @var{dir} to the list of directories in which the linker
9784 will search for libraries. This is equivalent to
9785 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9786 @ifclear vms
9787 Furthermore, under Windows, the sources pointed to by the libraries path
9788 set in the registry are not searched for.
9789 @end ifclear
9791 @item -nostdinc
9792 @cindex @option{-nostdinc} (@command{gnatmake})
9793 Do not look for source files in the system default directory.
9795 @item -nostdlib
9796 @cindex @option{-nostdlib} (@command{gnatmake})
9797 Do not look for library files in the system default directory.
9799 @item --RTS=@var{rts-path}
9800 @cindex @option{--RTS} (@command{gnatmake})
9801 Specifies the default location of the runtime library. GNAT looks for the
9802 runtime
9803 in the following directories, and stops as soon as a valid runtime is found
9804 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9805 @file{ada_object_path} present):
9807 @itemize @bullet
9808 @item <current directory>/$rts_path
9810 @item <default-search-dir>/$rts_path
9812 @item <default-search-dir>/rts-$rts_path
9813 @end itemize
9815 @noindent
9816 The selected path is handled like a normal RTS path.
9818 @end table
9820 @node Mode Switches for gnatmake
9821 @section Mode Switches for @command{gnatmake}
9823 @noindent
9824 The mode switches (referred to as @code{mode_switches}) allow the
9825 inclusion of switches that are to be passed to the compiler itself, the
9826 binder or the linker. The effect of a mode switch is to cause all
9827 subsequent switches up to the end of the switch list, or up to the next
9828 mode switch, to be interpreted as switches to be passed on to the
9829 designated component of GNAT.
9831 @table @option
9832 @c !sort!
9833 @item -cargs @var{switches}
9834 @cindex @option{-cargs} (@command{gnatmake})
9835 Compiler switches. Here @var{switches} is a list of switches
9836 that are valid switches for @command{gcc}. They will be passed on to
9837 all compile steps performed by @command{gnatmake}.
9839 @item -bargs @var{switches}
9840 @cindex @option{-bargs} (@command{gnatmake})
9841 Binder switches. Here @var{switches} is a list of switches
9842 that are valid switches for @code{gnatbind}. They will be passed on to
9843 all bind steps performed by @command{gnatmake}.
9845 @item -largs @var{switches}
9846 @cindex @option{-largs} (@command{gnatmake})
9847 Linker switches. Here @var{switches} is a list of switches
9848 that are valid switches for @command{gnatlink}. They will be passed on to
9849 all link steps performed by @command{gnatmake}.
9851 @item -margs @var{switches}
9852 @cindex @option{-margs} (@command{gnatmake})
9853 Make switches. The switches are directly interpreted by @command{gnatmake},
9854 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9855 or @option{-largs}.
9856 @end table
9858 @node Notes on the Command Line
9859 @section Notes on the Command Line
9861 @noindent
9862 This section contains some additional useful notes on the operation
9863 of the @command{gnatmake} command.
9865 @itemize @bullet
9866 @item
9867 @cindex Recompilation, by @command{gnatmake}
9868 If @command{gnatmake} finds no ALI files, it recompiles the main program
9869 and all other units required by the main program.
9870 This means that @command{gnatmake}
9871 can be used for the initial compile, as well as during subsequent steps of
9872 the development cycle.
9874 @item
9875 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9876 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9877 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9878 warning.
9880 @item
9881 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9882 is used to specify both source and
9883 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9884 instead if you just want to specify
9885 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9886 if you want to specify library paths
9887 only.
9889 @item
9890 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9891 This may conveniently be used to exclude standard libraries from
9892 consideration and in particular it means that the use of the
9893 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9894 unless @option{^-a^/ALL_FILES^} is also specified.
9896 @item
9897 @command{gnatmake} has been designed to make the use of Ada libraries
9898 particularly convenient. Assume you have an Ada library organized
9899 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9900 of your Ada compilation units,
9901 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9902 specs of these units, but no bodies. Then to compile a unit
9903 stored in @code{main.adb}, which uses this Ada library you would just type
9905 @smallexample
9906 @ifclear vms
9907 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9908 @end ifclear
9909 @ifset vms
9910 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9911            /SKIP_MISSING=@i{[OBJ_DIR]} main
9912 @end ifset
9913 @end smallexample
9915 @item
9916 Using @command{gnatmake} along with the
9917 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9918 switch provides a mechanism for avoiding unnecessary recompilations. Using
9919 this switch,
9920 you can update the comments/format of your
9921 source files without having to recompile everything. Note, however, that
9922 adding or deleting lines in a source files may render its debugging
9923 info obsolete. If the file in question is a spec, the impact is rather
9924 limited, as that debugging info will only be useful during the
9925 elaboration phase of your program. For bodies the impact can be more
9926 significant. In all events, your debugger will warn you if a source file
9927 is more recent than the corresponding object, and alert you to the fact
9928 that the debugging information may be out of date.
9929 @end itemize
9931 @node How gnatmake Works
9932 @section How @command{gnatmake} Works
9934 @noindent
9935 Generally @command{gnatmake} automatically performs all necessary
9936 recompilations and you don't need to worry about how it works. However,
9937 it may be useful to have some basic understanding of the @command{gnatmake}
9938 approach and in particular to understand how it uses the results of
9939 previous compilations without incorrectly depending on them.
9941 First a definition: an object file is considered @dfn{up to date} if the
9942 corresponding ALI file exists and if all the source files listed in the
9943 dependency section of this ALI file have time stamps matching those in
9944 the ALI file. This means that neither the source file itself nor any
9945 files that it depends on have been modified, and hence there is no need
9946 to recompile this file.
9948 @command{gnatmake} works by first checking if the specified main unit is up
9949 to date. If so, no compilations are required for the main unit. If not,
9950 @command{gnatmake} compiles the main program to build a new ALI file that
9951 reflects the latest sources. Then the ALI file of the main unit is
9952 examined to find all the source files on which the main program depends,
9953 and @command{gnatmake} recursively applies the above procedure on all these
9954 files.
9956 This process ensures that @command{gnatmake} only trusts the dependencies
9957 in an existing ALI file if they are known to be correct. Otherwise it
9958 always recompiles to determine a new, guaranteed accurate set of
9959 dependencies. As a result the program is compiled ``upside down'' from what may
9960 be more familiar as the required order of compilation in some other Ada
9961 systems. In particular, clients are compiled before the units on which
9962 they depend. The ability of GNAT to compile in any order is critical in
9963 allowing an order of compilation to be chosen that guarantees that
9964 @command{gnatmake} will recompute a correct set of new dependencies if
9965 necessary.
9967 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9968 imported by several of the executables, it will be recompiled at most once.
9970 Note: when using non-standard naming conventions
9971 (@pxref{Using Other File Names}), changing through a configuration pragmas
9972 file the version of a source and invoking @command{gnatmake} to recompile may
9973 have no effect, if the previous version of the source is still accessible
9974 by @command{gnatmake}. It may be necessary to use the switch
9975 ^-f^/FORCE_COMPILE^.
9977 @node Examples of gnatmake Usage
9978 @section Examples of @command{gnatmake} Usage
9980 @table @code
9981 @item gnatmake hello.adb
9982 Compile all files necessary to bind and link the main program
9983 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9984 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9986 @item gnatmake main1 main2 main3
9987 Compile all files necessary to bind and link the main programs
9988 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9989 (containing unit @code{Main2}) and @file{main3.adb}
9990 (containing unit @code{Main3}) and bind and link the resulting object files
9991 to generate three executable files @file{^main1^MAIN1.EXE^},
9992 @file{^main2^MAIN2.EXE^}
9993 and @file{^main3^MAIN3.EXE^}.
9995 @ifclear vms
9996 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9997 @end ifclear
9999 @ifset vms
10000 @item gnatmake Main_Unit /QUIET
10001 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10002 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10003 @end ifset
10004 Compile all files necessary to bind and link the main program unit
10005 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10006 be done with optimization level 2 and the order of elaboration will be
10007 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10008 displaying commands it is executing.
10009 @end table
10011 @c *************************
10012 @node Improving Performance
10013 @chapter Improving Performance
10014 @cindex Improving performance
10016 @noindent
10017 This chapter presents several topics related to program performance.
10018 It first describes some of the tradeoffs that need to be considered
10019 and some of the techniques for making your program run faster.
10020 It then documents the @command{gnatelim} tool and unused subprogram/data
10021 elimination feature, which can reduce the size of program executables.
10023 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
10024 driver (see @ref{The GNAT Driver and Project Files}).
10026 @ifnottex
10027 @menu
10028 * Performance Considerations::
10029 * Text_IO Suggestions::
10030 * Reducing Size of Ada Executables with gnatelim::
10031 * Reducing Size of Executables with unused subprogram/data elimination::
10032 @end menu
10033 @end ifnottex
10035 @c *****************************
10036 @node Performance Considerations
10037 @section Performance Considerations
10039 @noindent
10040 The GNAT system provides a number of options that allow a trade-off
10041 between
10043 @itemize @bullet
10044 @item
10045 performance of the generated code
10047 @item
10048 speed of compilation
10050 @item
10051 minimization of dependences and recompilation
10053 @item
10054 the degree of run-time checking.
10055 @end itemize
10057 @noindent
10058 The defaults (if no options are selected) aim at improving the speed
10059 of compilation and minimizing dependences, at the expense of performance
10060 of the generated code:
10062 @itemize @bullet
10063 @item
10064 no optimization
10066 @item
10067 no inlining of subprogram calls
10069 @item
10070 all run-time checks enabled except overflow and elaboration checks
10071 @end itemize
10073 @noindent
10074 These options are suitable for most program development purposes. This
10075 chapter describes how you can modify these choices, and also provides
10076 some guidelines on debugging optimized code.
10078 @menu
10079 * Controlling Run-Time Checks::
10080 * Use of Restrictions::
10081 * Optimization Levels::
10082 * Debugging Optimized Code::
10083 * Inlining of Subprograms::
10084 * Other Optimization Switches::
10085 * Optimization and Strict Aliasing::
10087 @ifset vms
10088 * Coverage Analysis::
10089 @end ifset
10090 @end menu
10092 @node Controlling Run-Time Checks
10093 @subsection Controlling Run-Time Checks
10095 @noindent
10096 By default, GNAT generates all run-time checks, except integer overflow
10097 checks, stack overflow checks, and checks for access before elaboration on
10098 subprogram calls. The latter are not required in default mode, because all
10099 necessary checking is done at compile time.
10100 @cindex @option{-gnatp} (@command{gcc})
10101 @cindex @option{-gnato} (@command{gcc})
10102 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10103 be modified. @xref{Run-Time Checks}.
10105 Our experience is that the default is suitable for most development
10106 purposes.
10108 We treat integer overflow specially because these
10109 are quite expensive and in our experience are not as important as other
10110 run-time checks in the development process. Note that division by zero
10111 is not considered an overflow check, and divide by zero checks are
10112 generated where required by default.
10114 Elaboration checks are off by default, and also not needed by default, since
10115 GNAT uses a static elaboration analysis approach that avoids the need for
10116 run-time checking. This manual contains a full chapter discussing the issue
10117 of elaboration checks, and if the default is not satisfactory for your use,
10118 you should read this chapter.
10120 For validity checks, the minimal checks required by the Ada Reference
10121 Manual (for case statements and assignments to array elements) are on
10122 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10123 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10124 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10125 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10126 are also suppressed entirely if @option{-gnatp} is used.
10128 @cindex Overflow checks
10129 @cindex Checks, overflow
10130 @findex Suppress
10131 @findex Unsuppress
10132 @cindex pragma Suppress
10133 @cindex pragma Unsuppress
10134 Note that the setting of the switches controls the default setting of
10135 the checks. They may be modified using either @code{pragma Suppress} (to
10136 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10137 checks) in the program source.
10139 @node Use of Restrictions
10140 @subsection Use of Restrictions
10142 @noindent
10143 The use of pragma Restrictions allows you to control which features are
10144 permitted in your program. Apart from the obvious point that if you avoid
10145 relatively expensive features like finalization (enforceable by the use
10146 of pragma Restrictions (No_Finalization), the use of this pragma does not
10147 affect the generated code in most cases.
10149 One notable exception to this rule is that the possibility of task abort
10150 results in some distributed overhead, particularly if finalization or
10151 exception handlers are used. The reason is that certain sections of code
10152 have to be marked as non-abortable.
10154 If you use neither the @code{abort} statement, nor asynchronous transfer
10155 of control (@code{select @dots{} then abort}), then this distributed overhead
10156 is removed, which may have a general positive effect in improving
10157 overall performance.  Especially code involving frequent use of tasking
10158 constructs and controlled types will show much improved performance.
10159 The relevant restrictions pragmas are
10161 @smallexample @c ada
10162    pragma Restrictions (No_Abort_Statements);
10163    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10164 @end smallexample
10166 @noindent
10167 It is recommended that these restriction pragmas be used if possible. Note
10168 that this also means that you can write code without worrying about the
10169 possibility of an immediate abort at any point.
10171 @node Optimization Levels
10172 @subsection Optimization Levels
10173 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10175 @noindent
10176 Without any optimization ^option,^qualifier,^
10177 the compiler's goal is to reduce the cost of
10178 compilation and to make debugging produce the expected results.
10179 Statements are independent: if you stop the program with a breakpoint between
10180 statements, you can then assign a new value to any variable or change
10181 the program counter to any other statement in the subprogram and get exactly
10182 the results you would expect from the source code.
10184 Turning on optimization makes the compiler attempt to improve the
10185 performance and/or code size at the expense of compilation time and
10186 possibly the ability to debug the program.
10188 If you use multiple
10189 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10190 the last such option is the one that is effective.
10192 @noindent
10193 The default is optimization off. This results in the fastest compile
10194 times, but GNAT makes absolutely no attempt to optimize, and the
10195 generated programs are considerably larger and slower than when
10196 optimization is enabled. You can use the
10197 @ifclear vms
10198 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10199 @option{-O2}, @option{-O3}, and @option{-Os})
10200 @end ifclear
10201 @ifset vms
10202 @code{OPTIMIZE} qualifier
10203 @end ifset
10204 to @command{gcc} to control the optimization level:
10206 @table @option
10207 @item ^-O0^/OPTIMIZE=NONE^
10208 No optimization (the default);
10209 generates unoptimized code but has
10210 the fastest compilation time.
10212 Note that many other compilers do fairly extensive optimization
10213 even if ``no optimization'' is specified. With gcc, it is
10214 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10215 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10216 really does mean no optimization at all. This difference between
10217 gcc and other compilers should be kept in mind when doing
10218 performance comparisons.
10220 @item ^-O1^/OPTIMIZE=SOME^
10221 Moderate optimization;
10222 optimizes reasonably well but does not
10223 degrade compilation time significantly.
10225 @item ^-O2^/OPTIMIZE=ALL^
10226 @ifset vms
10227 @itemx /OPTIMIZE=DEVELOPMENT
10228 @end ifset
10229 Full optimization;
10230 generates highly optimized code and has
10231 the slowest compilation time.
10233 @item ^-O3^/OPTIMIZE=INLINING^
10234 Full optimization as in @option{-O2};
10235 also uses more aggressive automatic inlining of subprograms within a unit
10236 (@pxref{Inlining of Subprograms}) and attemps to vectorize loops.
10238 @item ^-Os^/OPTIMIZE=SPACE^
10239 Optimize space usage (code and data) of resulting program.
10240 @end table
10242 @noindent
10243 Higher optimization levels perform more global transformations on the
10244 program and apply more expensive analysis algorithms in order to generate
10245 faster and more compact code. The price in compilation time, and the
10246 resulting improvement in execution time,
10247 both depend on the particular application and the hardware environment.
10248 You should experiment to find the best level for your application.
10250 Since the precise set of optimizations done at each level will vary from
10251 release to release (and sometime from target to target), it is best to think
10252 of the optimization settings in general terms.
10253 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10254 the GNU Compiler Collection (GCC)}, for details about
10255 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10256 individually enable or disable specific optimizations.
10258 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10259 been tested extensively at all optimization levels. There are some bugs
10260 which appear only with optimization turned on, but there have also been
10261 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10262 level of optimization does not improve the reliability of the code
10263 generator, which in practice is highly reliable at all optimization
10264 levels.
10266 Note regarding the use of @option{-O3}: The use of this optimization level
10267 is generally discouraged with GNAT, since it often results in larger
10268 executables which may run more slowly. See further discussion of this point
10269 in @ref{Inlining of Subprograms}.
10271 @node Debugging Optimized Code
10272 @subsection Debugging Optimized Code
10273 @cindex Debugging optimized code
10274 @cindex Optimization and debugging
10276 @noindent
10277 Although it is possible to do a reasonable amount of debugging at
10278 @ifclear vms
10279 nonzero optimization levels,
10280 the higher the level the more likely that
10281 @end ifclear
10282 @ifset vms
10283 @option{/OPTIMIZE} settings other than @code{NONE},
10284 such settings will make it more likely that
10285 @end ifset
10286 source-level constructs will have been eliminated by optimization.
10287 For example, if a loop is strength-reduced, the loop
10288 control variable may be completely eliminated and thus cannot be
10289 displayed in the debugger.
10290 This can only happen at @option{-O2} or @option{-O3}.
10291 Explicit temporary variables that you code might be eliminated at
10292 ^level^setting^ @option{-O1} or higher.
10294 The use of the @option{^-g^/DEBUG^} switch,
10295 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10296 which is needed for source-level debugging,
10297 affects the size of the program executable on disk,
10298 and indeed the debugging information can be quite large.
10299 However, it has no effect on the generated code (and thus does not
10300 degrade performance)
10302 Since the compiler generates debugging tables for a compilation unit before
10303 it performs optimizations, the optimizing transformations may invalidate some
10304 of the debugging data.  You therefore need to anticipate certain
10305 anomalous situations that may arise while debugging optimized code.
10306 These are the most common cases:
10308 @enumerate
10309 @item
10310 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10311 commands show
10312 the PC bouncing back and forth in the code.  This may result from any of
10313 the following optimizations:
10315 @itemize @bullet
10316 @item
10317 @i{Common subexpression elimination:} using a single instance of code for a
10318 quantity that the source computes several times.  As a result you
10319 may not be able to stop on what looks like a statement.
10321 @item
10322 @i{Invariant code motion:} moving an expression that does not change within a
10323 loop, to the beginning of the loop.
10325 @item
10326 @i{Instruction scheduling:} moving instructions so as to
10327 overlap loads and stores (typically) with other code, or in
10328 general to move computations of values closer to their uses. Often
10329 this causes you to pass an assignment statement without the assignment
10330 happening and then later bounce back to the statement when the
10331 value is actually needed.  Placing a breakpoint on a line of code
10332 and then stepping over it may, therefore, not always cause all the
10333 expected side-effects.
10334 @end itemize
10336 @item
10337 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10338 two identical pieces of code are merged and the program counter suddenly
10339 jumps to a statement that is not supposed to be executed, simply because
10340 it (and the code following) translates to the same thing as the code
10341 that @emph{was} supposed to be executed.  This effect is typically seen in
10342 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10343 a @code{break} in a C @code{^switch^switch^} statement.
10345 @item
10346 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10347 There are various reasons for this effect:
10349 @itemize @bullet
10350 @item
10351 In a subprogram prologue, a parameter may not yet have been moved to its
10352 ``home''.
10354 @item
10355 A variable may be dead, and its register re-used.  This is
10356 probably the most common cause.
10358 @item
10359 As mentioned above, the assignment of a value to a variable may
10360 have been moved.
10362 @item
10363 A variable may be eliminated entirely by value propagation or
10364 other means.  In this case, GCC may incorrectly generate debugging
10365 information for the variable
10366 @end itemize
10368 @noindent
10369 In general, when an unexpected value appears for a local variable or parameter
10370 you should first ascertain if that value was actually computed by
10371 your program, as opposed to being incorrectly reported by the debugger.
10372 Record fields or
10373 array elements in an object designated by an access value
10374 are generally less of a problem, once you have ascertained that the access
10375 value is sensible.
10376 Typically, this means checking variables in the preceding code and in the
10377 calling subprogram to verify that the value observed is explainable from other
10378 values (one must apply the procedure recursively to those
10379 other values); or re-running the code and stopping a little earlier
10380 (perhaps before the call) and stepping to better see how the variable obtained
10381 the value in question; or continuing to step @emph{from} the point of the
10382 strange value to see if code motion had simply moved the variable's
10383 assignments later.
10384 @end enumerate
10386 @noindent
10387 In light of such anomalies, a recommended technique is to use @option{-O0}
10388 early in the software development cycle, when extensive debugging capabilities
10389 are most needed, and then move to @option{-O1} and later @option{-O2} as
10390 the debugger becomes less critical.
10391 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10392 a release management issue.
10393 @ifclear vms
10394 Note that if you use @option{-g} you can then use the @command{strip} program
10395 on the resulting executable,
10396 which removes both debugging information and global symbols.
10397 @end ifclear
10399 @node Inlining of Subprograms
10400 @subsection Inlining of Subprograms
10402 @noindent
10403 A call to a subprogram in the current unit is inlined if all the
10404 following conditions are met:
10406 @itemize @bullet
10407 @item
10408 The optimization level is at least @option{-O1}.
10410 @item
10411 The called subprogram is suitable for inlining: It must be small enough
10412 and not contain something that @command{gcc} cannot support in inlined
10413 subprograms.
10415 @item
10416 @cindex pragma Inline
10417 @findex Inline
10418 Any one of the following applies: @code{pragma Inline} is applied to the
10419 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10420 subprogram is local to the unit and called once from within it; the
10421 subprogram is small and optimization level @option{-O2} is specified;
10422 optimization level @option{-O3}) is specified.
10423 @end itemize
10425 @noindent
10426 Calls to subprograms in @code{with}'ed units are normally not inlined.
10427 To achieve actual inlining (that is, replacement of the call by the code
10428 in the body of the subprogram), the following conditions must all be true.
10430 @itemize @bullet
10431 @item
10432 The optimization level is at least @option{-O1}.
10434 @item
10435 The called subprogram is suitable for inlining: It must be small enough
10436 and not contain something that @command{gcc} cannot support in inlined
10437 subprograms.
10439 @item
10440 The call appears in a body (not in a package spec).
10442 @item
10443 There is a @code{pragma Inline} for the subprogram.
10445 @item
10446 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10447 @end itemize
10449 Even if all these conditions are met, it may not be possible for
10450 the compiler to inline the call, due to the length of the body,
10451 or features in the body that make it impossible for the compiler
10452 to do the inlining.
10454 Note that specifying the @option{-gnatn} switch causes additional
10455 compilation dependencies. Consider the following:
10457 @smallexample @c ada
10458 @cartouche
10459 package R is
10460    procedure Q;
10461    pragma Inline (Q);
10462 end R;
10463 package body R is
10464    @dots{}
10465 end R;
10467 with R;
10468 procedure Main is
10469 begin
10470    @dots{}
10471    R.Q;
10472 end Main;
10473 @end cartouche
10474 @end smallexample
10476 @noindent
10477 With the default behavior (no @option{-gnatn} switch specified), the
10478 compilation of the @code{Main} procedure depends only on its own source,
10479 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10480 means that editing the body of @code{R} does not require recompiling
10481 @code{Main}.
10483 On the other hand, the call @code{R.Q} is not inlined under these
10484 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10485 is compiled, the call will be inlined if the body of @code{Q} is small
10486 enough, but now @code{Main} depends on the body of @code{R} in
10487 @file{r.adb} as well as on the spec. This means that if this body is edited,
10488 the main program must be recompiled. Note that this extra dependency
10489 occurs whether or not the call is in fact inlined by @command{gcc}.
10491 The use of front end inlining with @option{-gnatN} generates similar
10492 additional dependencies.
10494 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10495 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10496 can be used to prevent
10497 all inlining. This switch overrides all other conditions and ensures
10498 that no inlining occurs. The extra dependences resulting from
10499 @option{-gnatn} will still be active, even if
10500 this switch is used to suppress the resulting inlining actions.
10502 @cindex @option{-fno-inline-functions} (@command{gcc})
10503 Note: The @option{-fno-inline-functions} switch can be used to prevent
10504 automatic inlining of subprograms if @option{-O3} is used.
10506 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10507 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10508 automatic inlining of small subprograms if @option{-O2} is used.
10510 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10511 Note: The @option{-fno-inline-functions-called-once} switch
10512 can be used to prevent inlining of subprograms local to the unit
10513 and called once from within it if @option{-O1} is used.
10515 Note regarding the use of @option{-O3}: There is no difference in inlining
10516 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10517 pragma @code{Inline} assuming the use of @option{-gnatn}
10518 or @option{-gnatN} (the switches that activate inlining). If you have used
10519 pragma @code{Inline} in appropriate cases, then it is usually much better
10520 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10521 in this case only has the effect of inlining subprograms you did not
10522 think should be inlined. We often find that the use of @option{-O3} slows
10523 down code by performing excessive inlining, leading to increased instruction
10524 cache pressure from the increased code size. So the bottom line here is
10525 that you should not automatically assume that @option{-O3} is better than
10526 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10527 it actually improves performance.
10529 @node Other Optimization Switches
10530 @subsection Other Optimization Switches
10531 @cindex Optimization Switches
10533 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10534 @command{gcc} optimization switches are potentially usable. These switches
10535 have not been extensively tested with GNAT but can generally be expected
10536 to work. Examples of switches in this category are
10537 @option{-funroll-loops} and
10538 the various target-specific @option{-m} options (in particular, it has been
10539 observed that @option{-march=pentium4} can significantly improve performance
10540 on appropriate machines). For full details of these switches, see
10541 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10542 the GNU Compiler Collection (GCC)}.
10544 @node Optimization and Strict Aliasing
10545 @subsection Optimization and Strict Aliasing
10546 @cindex Aliasing
10547 @cindex Strict Aliasing
10548 @cindex No_Strict_Aliasing
10550 @noindent
10551 The strong typing capabilities of Ada allow an optimizer to generate
10552 efficient code in situations where other languages would be forced to
10553 make worst case assumptions preventing such optimizations. Consider
10554 the following example:
10556 @smallexample @c ada
10557 @cartouche
10558 procedure R is
10559    type Int1 is new Integer;
10560    type Int2 is new Integer;
10561    type Int1A is access Int1;
10562    type Int2A is access Int2;
10563    Int1V : Int1A;
10564    Int2V : Int2A;
10565    @dots{}
10567 begin
10568    @dots{}
10569    for J in Data'Range loop
10570       if Data (J) = Int1V.all then
10571          Int2V.all := Int2V.all + 1;
10572       end if;
10573    end loop;
10574    @dots{}
10575 end R;
10576 @end cartouche
10577 @end smallexample
10579 @noindent
10580 In this example, since the variable @code{Int1V} can only access objects
10581 of type @code{Int1}, and @code{Int2V} can only access objects of type
10582 @code{Int2}, there is no possibility that the assignment to
10583 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10584 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10585 for all iterations of the loop and avoid the extra memory reference
10586 required to dereference it each time through the loop.
10588 This kind of optimization, called strict aliasing analysis, is
10589 triggered by specifying an optimization level of @option{-O2} or
10590 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10591 when access values are involved.
10593 However, although this optimization is always correct in terms of
10594 the formal semantics of the Ada Reference Manual, difficulties can
10595 arise if features like @code{Unchecked_Conversion} are used to break
10596 the typing system. Consider the following complete program example:
10598 @smallexample @c ada
10599 @cartouche
10600 package p1 is
10601    type int1 is new integer;
10602    type int2 is new integer;
10603    type a1 is access int1;
10604    type a2 is access int2;
10605 end p1;
10607 with p1; use p1;
10608 package p2 is
10609    function to_a2 (Input : a1) return a2;
10610 end p2;
10612 with Unchecked_Conversion;
10613 package body p2 is
10614    function to_a2 (Input : a1) return a2 is
10615       function to_a2u is
10616         new Unchecked_Conversion (a1, a2);
10617    begin
10618       return to_a2u (Input);
10619    end to_a2;
10620 end p2;
10622 with p2; use p2;
10623 with p1; use p1;
10624 with Text_IO; use Text_IO;
10625 procedure m is
10626    v1 : a1 := new int1;
10627    v2 : a2 := to_a2 (v1);
10628 begin
10629    v1.all := 1;
10630    v2.all := 0;
10631    put_line (int1'image (v1.all));
10632 end;
10633 @end cartouche
10634 @end smallexample
10636 @noindent
10637 This program prints out 0 in @option{-O0} or @option{-O1}
10638 mode, but it prints out 1 in @option{-O2} mode. That's
10639 because in strict aliasing mode, the compiler can and
10640 does assume that the assignment to @code{v2.all} could not
10641 affect the value of @code{v1.all}, since different types
10642 are involved.
10644 This behavior is not a case of non-conformance with the standard, since
10645 the Ada RM specifies that an unchecked conversion where the resulting
10646 bit pattern is not a correct value of the target type can result in an
10647 abnormal value and attempting to reference an abnormal value makes the
10648 execution of a program erroneous.  That's the case here since the result
10649 does not point to an object of type @code{int2}.  This means that the
10650 effect is entirely unpredictable.
10652 However, although that explanation may satisfy a language
10653 lawyer, in practice an applications programmer expects an
10654 unchecked conversion involving pointers to create true
10655 aliases and the behavior of printing 1 seems plain wrong.
10656 In this case, the strict aliasing optimization is unwelcome.
10658 Indeed the compiler recognizes this possibility, and the
10659 unchecked conversion generates a warning:
10661 @smallexample
10662 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10663 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10664 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10665 @end smallexample
10667 @noindent
10668 Unfortunately the problem is recognized when compiling the body of
10669 package @code{p2}, but the actual "bad" code is generated while
10670 compiling the body of @code{m} and this latter compilation does not see
10671 the suspicious @code{Unchecked_Conversion}.
10673 As implied by the warning message, there are approaches you can use to
10674 avoid the unwanted strict aliasing optimization in a case like this.
10676 One possibility is to simply avoid the use of @option{-O2}, but
10677 that is a bit drastic, since it throws away a number of useful
10678 optimizations that do not involve strict aliasing assumptions.
10680 A less drastic approach is to compile the program using the
10681 option @option{-fno-strict-aliasing}. Actually it is only the
10682 unit containing the dereferencing of the suspicious pointer
10683 that needs to be compiled. So in this case, if we compile
10684 unit @code{m} with this switch, then we get the expected
10685 value of zero printed. Analyzing which units might need
10686 the switch can be painful, so a more reasonable approach
10687 is to compile the entire program with options @option{-O2}
10688 and @option{-fno-strict-aliasing}. If the performance is
10689 satisfactory with this combination of options, then the
10690 advantage is that the entire issue of possible "wrong"
10691 optimization due to strict aliasing is avoided.
10693 To avoid the use of compiler switches, the configuration
10694 pragma @code{No_Strict_Aliasing} with no parameters may be
10695 used to specify that for all access types, the strict
10696 aliasing optimization should be suppressed.
10698 However, these approaches are still overkill, in that they causes
10699 all manipulations of all access values to be deoptimized. A more
10700 refined approach is to concentrate attention on the specific
10701 access type identified as problematic.
10703 First, if a careful analysis of uses of the pointer shows
10704 that there are no possible problematic references, then
10705 the warning can be suppressed by bracketing the
10706 instantiation of @code{Unchecked_Conversion} to turn
10707 the warning off:
10709 @smallexample @c ada
10710    pragma Warnings (Off);
10711    function to_a2u is
10712      new Unchecked_Conversion (a1, a2);
10713    pragma Warnings (On);
10714 @end smallexample
10716 @noindent
10717 Of course that approach is not appropriate for this particular
10718 example, since indeed there is a problematic reference. In this
10719 case we can take one of two other approaches.
10721 The first possibility is to move the instantiation of unchecked
10722 conversion to the unit in which the type is declared. In
10723 this example, we would move the instantiation of
10724 @code{Unchecked_Conversion} from the body of package
10725 @code{p2} to the spec of package @code{p1}. Now the
10726 warning disappears. That's because any use of the
10727 access type knows there is a suspicious unchecked
10728 conversion, and the strict aliasing optimization
10729 is automatically suppressed for the type.
10731 If it is not practical to move the unchecked conversion to the same unit
10732 in which the destination access type is declared (perhaps because the
10733 source type is not visible in that unit), you may use pragma
10734 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10735 same declarative sequence as the declaration of the access type:
10737 @smallexample @c ada
10738    type a2 is access int2;
10739    pragma No_Strict_Aliasing (a2);
10740 @end smallexample
10742 @noindent
10743 Here again, the compiler now knows that the strict aliasing optimization
10744 should be suppressed for any reference to type @code{a2} and the
10745 expected behavior is obtained.
10747 Finally, note that although the compiler can generate warnings for
10748 simple cases of unchecked conversions, there are tricker and more
10749 indirect ways of creating type incorrect aliases which the compiler
10750 cannot detect. Examples are the use of address overlays and unchecked
10751 conversions involving composite types containing access types as
10752 components. In such cases, no warnings are generated, but there can
10753 still be aliasing problems. One safe coding practice is to forbid the
10754 use of address clauses for type overlaying, and to allow unchecked
10755 conversion only for primitive types. This is not really a significant
10756 restriction since any possible desired effect can be achieved by
10757 unchecked conversion of access values.
10759 The aliasing analysis done in strict aliasing mode can certainly
10760 have significant benefits. We have seen cases of large scale
10761 application code where the time is increased by up to 5% by turning
10762 this optimization off. If you have code that includes significant
10763 usage of unchecked conversion, you might want to just stick with
10764 @option{-O1} and avoid the entire issue. If you get adequate
10765 performance at this level of optimization level, that's probably
10766 the safest approach. If tests show that you really need higher
10767 levels of optimization, then you can experiment with @option{-O2}
10768 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10769 has on size and speed of the code. If you really need to use
10770 @option{-O2} with strict aliasing in effect, then you should
10771 review any uses of unchecked conversion of access types,
10772 particularly if you are getting the warnings described above.
10774 @ifset vms
10775 @node Coverage Analysis
10776 @subsection Coverage Analysis
10778 @noindent
10779 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10780 the user to determine the distribution of execution time across a program,
10781 @pxref{Profiling} for details of usage.
10782 @end ifset
10785 @node Text_IO Suggestions
10786 @section @code{Text_IO} Suggestions
10787 @cindex @code{Text_IO} and performance
10789 @noindent
10790 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10791 the requirement of maintaining page and line counts. If performance
10792 is critical, a recommendation is to use @code{Stream_IO} instead of
10793 @code{Text_IO} for volume output, since this package has less overhead.
10795 If @code{Text_IO} must be used, note that by default output to the standard
10796 output and standard error files is unbuffered (this provides better
10797 behavior when output statements are used for debugging, or if the
10798 progress of a program is observed by tracking the output, e.g. by
10799 using the Unix @command{tail -f} command to watch redirected output.
10801 If you are generating large volumes of output with @code{Text_IO} and
10802 performance is an important factor, use a designated file instead
10803 of the standard output file, or change the standard output file to
10804 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10808 @node Reducing Size of Ada Executables with gnatelim
10809 @section Reducing Size of Ada Executables with @code{gnatelim}
10810 @findex gnatelim
10812 @noindent
10813 This section describes @command{gnatelim}, a tool which detects unused
10814 subprograms and helps the compiler to create a smaller executable for your
10815 program.
10817 @menu
10818 * About gnatelim::
10819 * Running gnatelim::
10820 * Processing Precompiled Libraries::
10821 * Correcting the List of Eliminate Pragmas::
10822 * Making Your Executables Smaller::
10823 * Summary of the gnatelim Usage Cycle::
10824 @end menu
10826 @node About gnatelim
10827 @subsection About @code{gnatelim}
10829 @noindent
10830 When a program shares a set of Ada
10831 packages with other programs, it may happen that this program uses
10832 only a fraction of the subprograms defined in these packages. The code
10833 created for these unused subprograms increases the size of the executable.
10835 @code{gnatelim} tracks unused subprograms in an Ada program and
10836 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10837 subprograms that are declared but never called. By placing the list of
10838 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10839 recompiling your program, you may decrease the size of its executable,
10840 because the compiler will not generate the code for 'eliminated' subprograms.
10841 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10842 information about this pragma.
10844 @code{gnatelim} needs as its input data the name of the main subprogram.
10846 If a set of source files is specified as @code{gnatelim} arguments, it
10847 treats these files as a complete set of sources making up a program to
10848 analyse, and analyses only these sources.
10850 After a full successful build of the main subprogram @code{gnatelim} can be
10851 called without  specifying sources to analyse, in this case it computes
10852 the source closure of the main unit from the @file{ALI} files.
10854 The following command will create the set of @file{ALI} files needed for
10855 @code{gnatelim}:
10857 @smallexample
10858 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10859 @end smallexample
10861 Note that @code{gnatelim} does not need object files.
10863 @node Running gnatelim
10864 @subsection Running @code{gnatelim}
10866 @noindent
10867 @code{gnatelim} has the following command-line interface:
10869 @smallexample
10870 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10871 @end smallexample
10873 @noindent
10874 @var{main_unit_name} should be a name of a source file that contains the main
10875 subprogram of a program (partition).
10877 Each @var{filename} is the name (including the extension) of a source
10878 file to process. ``Wildcards'' are allowed, and
10879 the file name may contain path information.
10881 @samp{@var{gcc_switches}} is a list of switches for
10882 @command{gcc}. They will be passed on to all compiler invocations made by
10883 @command{gnatelim} to generate the ASIS trees. Here you can provide
10884 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10885 use the @option{-gnatec} switch to set the configuration file,
10886 use the @option{-gnat05} switch if sources should be compiled in
10887 Ada 2005 mode etc.
10889 @code{gnatelim} has the following switches:
10891 @table @option
10892 @c !sort!
10893 @item ^-files^/FILES^=@var{filename}
10894 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10895 Take the argument source files from the specified file. This file should be an
10896 ordinary text file containing file names separated by spaces or
10897 line breaks. You can use this switch more than once in the same call to
10898 @command{gnatelim}. You also can combine this switch with
10899 an explicit list of files.
10901 @item ^-log^/LOG^
10902 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10903 Duplicate all the output sent to @file{stderr} into a log file. The log file
10904 is named @file{gnatelim.log} and is located in the current directory.
10906 @item ^-log^/LOGFILE^=@var{filename}
10907 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10908 Duplicate all the output sent to @file{stderr} into a specified log file.
10910 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10911 @item ^--no-elim-dispatch^/NO_DISPATCH^
10912 Do not generate pragmas for dispatching operations.
10914 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10915 @item ^-o^/OUTPUT^=@var{report_file}
10916 Put @command{gnatelim} output into a specified file. If this file already exists,
10917 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10918 into @file{stderr}
10920 @item ^-q^/QUIET^
10921 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10922 Quiet mode: by default @code{gnatelim} outputs to the standard error
10923 stream the number of program units left to be processed. This option turns
10924 this trace off.
10926 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10927 @item ^-t^/TIME^
10928 Print out execution time.
10930 @item ^-v^/VERBOSE^
10931 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10932 Verbose mode: @code{gnatelim} version information is printed as Ada
10933 comments to the standard output stream. Also, in addition to the number of
10934 program units left @code{gnatelim} will output the name of the current unit
10935 being processed.
10937 @item ^-wq^/WARNINGS=QUIET^
10938 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10939 Quet warning mode - some warnings are suppressed. In particular warnings that
10940 indicate that the analysed set of sources is incomplete to make up a
10941 partition and that some subprogram bodies are missing are not generated.
10942 @end table
10944 @node Processing Precompiled Libraries
10945 @subsection Processing Precompiled Libraries
10947 @noindent
10948 If some program uses a precompiled Ada library, it can be processed by
10949 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10950 Eliminate pragma for a subprogram if the body of this subprogram has not
10951 been analysed, this is a typical case for subprograms from precompiled
10952 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10953 warnings about missing source files and non-analyzed subprogram bodies
10954 that can be generated when processing precompiled Ada libraries.
10956 @node Correcting the List of Eliminate Pragmas
10957 @subsection Correcting the List of Eliminate Pragmas
10959 @noindent
10960 In some rare cases @code{gnatelim} may try to eliminate
10961 subprograms that are actually called in the program. In this case, the
10962 compiler will generate an error message of the form:
10964 @smallexample
10965 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10966 @end smallexample
10968 @noindent
10969 You will need to manually remove the wrong @code{Eliminate} pragmas from
10970 the configuration file indicated in the error message. You should recompile
10971 your program from scratch after that, because you need a consistent
10972 configuration file(s) during the entire compilation.
10974 @node Making Your Executables Smaller
10975 @subsection Making Your Executables Smaller
10977 @noindent
10978 In order to get a smaller executable for your program you now have to
10979 recompile the program completely with the configuration file containing
10980 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10981 @file{gnat.adc} file located in your current directory, just do:
10983 @smallexample
10984 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10985 @end smallexample
10987 @noindent
10988 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10989 recompile everything
10990 with the set of pragmas @code{Eliminate} that you have obtained with
10991 @command{gnatelim}).
10993 Be aware that the set of @code{Eliminate} pragmas is specific to each
10994 program. It is not recommended to merge sets of @code{Eliminate}
10995 pragmas created for different programs in one configuration file.
10997 @node Summary of the gnatelim Usage Cycle
10998 @subsection Summary of the @code{gnatelim} Usage Cycle
11000 @noindent
11001 Here is a quick summary of the steps to be taken in order to reduce
11002 the size of your executables with @code{gnatelim}. You may use
11003 other GNAT options to control the optimization level,
11004 to produce the debugging information, to set search path, etc.
11006 @enumerate
11007 @item
11008 Create a complete set of @file{ALI} files (if the program has not been
11009 built already)
11011 @smallexample
11012 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11013 @end smallexample
11015 @item
11016 Generate a list of @code{Eliminate} pragmas in default configuration file
11017 @file{gnat.adc} in the current directory
11018 @smallexample
11019 @ifset vms
11020 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11021 @end ifset
11022 @ifclear vms
11023 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11024 @end ifclear
11025 @end smallexample
11027 @item
11028 Recompile the application
11030 @smallexample
11031 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11032 @end smallexample
11034 @end enumerate
11036 @node Reducing Size of Executables with unused subprogram/data elimination
11037 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11038 @findex unused subprogram/data elimination
11040 @noindent
11041 This section describes how you can eliminate unused subprograms and data from
11042 your executable just by setting options at compilation time.
11044 @menu
11045 * About unused subprogram/data elimination::
11046 * Compilation options::
11047 * Example of unused subprogram/data elimination::
11048 @end menu
11050 @node About unused subprogram/data elimination
11051 @subsection About unused subprogram/data elimination
11053 @noindent
11054 By default, an executable contains all code and data of its composing objects
11055 (directly linked or coming from statically linked libraries), even data or code
11056 never used by this executable.
11058 This feature will allow you to eliminate such unused code from your
11059 executable, making it smaller (in disk and in memory).
11061 This functionality is available on all Linux platforms except for the IA-64
11062 architecture and on all cross platforms using the ELF binary file format.
11063 In both cases GNU binutils version 2.16 or later are required to enable it.
11065 @node Compilation options
11066 @subsection Compilation options
11068 @noindent
11069 The operation of eliminating the unused code and data from the final executable
11070 is directly performed by the linker.
11072 In order to do this, it has to work with objects compiled with the
11073 following options:
11074 @option{-ffunction-sections} @option{-fdata-sections}.
11075 @cindex @option{-ffunction-sections} (@command{gcc})
11076 @cindex @option{-fdata-sections} (@command{gcc})
11077 These options are usable with C and Ada files.
11078 They will place respectively each
11079 function or data in a separate section in the resulting object file.
11081 Once the objects and static libraries are created with these options, the
11082 linker can perform the dead code elimination. You can do this by setting
11083 the @option{-Wl,--gc-sections} option to gcc command or in the
11084 @option{-largs} section of @command{gnatmake}. This will perform a
11085 garbage collection of code and data never referenced.
11087 If the linker performs a partial link (@option{-r} ld linker option), then you
11088 will need to provide one or several entry point using the
11089 @option{-e} / @option{--entry} ld option.
11091 Note that objects compiled without the @option{-ffunction-sections} and
11092 @option{-fdata-sections} options can still be linked with the executable.
11093 However, no dead code elimination will be performed on those objects (they will
11094 be linked as is).
11096 The GNAT static library is now compiled with -ffunction-sections and
11097 -fdata-sections on some platforms. This allows you to eliminate the unused code
11098 and data of the GNAT library from your executable.
11100 @node Example of unused subprogram/data elimination
11101 @subsection Example of unused subprogram/data elimination
11103 @noindent
11104 Here is a simple example:
11106 @smallexample @c ada
11107 with Aux;
11109 procedure Test is
11110 begin
11111    Aux.Used (10);
11112 end Test;
11114 package Aux is
11115    Used_Data   : Integer;
11116    Unused_Data : Integer;
11118    procedure Used   (Data : Integer);
11119    procedure Unused (Data : Integer);
11120 end Aux;
11122 package body Aux is
11123    procedure Used (Data : Integer) is
11124    begin
11125       Used_Data := Data;
11126    end Used;
11128    procedure Unused (Data : Integer) is
11129    begin
11130       Unused_Data := Data;
11131    end Unused;
11132 end Aux;
11133 @end smallexample
11135 @noindent
11136 @code{Unused} and @code{Unused_Data} are never referenced in this code
11137 excerpt, and hence they may be safely removed from the final executable.
11139 @smallexample
11140 $ gnatmake test
11142 $ nm test | grep used
11143 020015f0 T aux__unused
11144 02005d88 B aux__unused_data
11145 020015cc T aux__used
11146 02005d84 B aux__used_data
11148 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11149      -largs -Wl,--gc-sections
11151 $ nm test | grep used
11152 02005350 T aux__used
11153 0201ffe0 B aux__used_data
11154 @end smallexample
11156 @noindent
11157 It can be observed that the procedure @code{Unused} and the object
11158 @code{Unused_Data} are removed by the linker when using the
11159 appropriate options.
11161 @c ********************************
11162 @node Renaming Files Using gnatchop
11163 @chapter Renaming Files Using @code{gnatchop}
11164 @findex gnatchop
11166 @noindent
11167 This chapter discusses how to handle files with multiple units by using
11168 the @code{gnatchop} utility. This utility is also useful in renaming
11169 files to meet the standard GNAT default file naming conventions.
11171 @menu
11172 * Handling Files with Multiple Units::
11173 * Operating gnatchop in Compilation Mode::
11174 * Command Line for gnatchop::
11175 * Switches for gnatchop::
11176 * Examples of gnatchop Usage::
11177 @end menu
11179 @node Handling Files with Multiple Units
11180 @section Handling Files with Multiple Units
11182 @noindent
11183 The basic compilation model of GNAT requires that a file submitted to the
11184 compiler have only one unit and there be a strict correspondence
11185 between the file name and the unit name.
11187 The @code{gnatchop} utility allows both of these rules to be relaxed,
11188 allowing GNAT to process files which contain multiple compilation units
11189 and files with arbitrary file names. @code{gnatchop}
11190 reads the specified file and generates one or more output files,
11191 containing one unit per file. The unit and the file name correspond,
11192 as required by GNAT.
11194 If you want to permanently restructure a set of ``foreign'' files so that
11195 they match the GNAT rules, and do the remaining development using the
11196 GNAT structure, you can simply use @command{gnatchop} once, generate the
11197 new set of files and work with them from that point on.
11199 Alternatively, if you want to keep your files in the ``foreign'' format,
11200 perhaps to maintain compatibility with some other Ada compilation
11201 system, you can set up a procedure where you use @command{gnatchop} each
11202 time you compile, regarding the source files that it writes as temporary
11203 files that you throw away.
11205 Note that if your file containing multiple units starts with a byte order
11206 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11207 will each start with a copy of this BOM, meaning that they can be compiled
11208 automatically in UTF-8 mode without needing to specify an explicit encoding.
11210 @node Operating gnatchop in Compilation Mode
11211 @section Operating gnatchop in Compilation Mode
11213 @noindent
11214 The basic function of @code{gnatchop} is to take a file with multiple units
11215 and split it into separate files. The boundary between files is reasonably
11216 clear, except for the issue of comments and pragmas. In default mode, the
11217 rule is that any pragmas between units belong to the previous unit, except
11218 that configuration pragmas always belong to the following unit. Any comments
11219 belong to the following unit. These rules
11220 almost always result in the right choice of
11221 the split point without needing to mark it explicitly and most users will
11222 find this default to be what they want. In this default mode it is incorrect to
11223 submit a file containing only configuration pragmas, or one that ends in
11224 configuration pragmas, to @code{gnatchop}.
11226 However, using a special option to activate ``compilation mode'',
11227 @code{gnatchop}
11228 can perform another function, which is to provide exactly the semantics
11229 required by the RM for handling of configuration pragmas in a compilation.
11230 In the absence of configuration pragmas (at the main file level), this
11231 option has no effect, but it causes such configuration pragmas to be handled
11232 in a quite different manner.
11234 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11235 only configuration pragmas, then this file is appended to the
11236 @file{gnat.adc} file in the current directory. This behavior provides
11237 the required behavior described in the RM for the actions to be taken
11238 on submitting such a file to the compiler, namely that these pragmas
11239 should apply to all subsequent compilations in the same compilation
11240 environment. Using GNAT, the current directory, possibly containing a
11241 @file{gnat.adc} file is the representation
11242 of a compilation environment. For more information on the
11243 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11245 Second, in compilation mode, if @code{gnatchop}
11246 is given a file that starts with
11247 configuration pragmas, and contains one or more units, then these
11248 configuration pragmas are prepended to each of the chopped files. This
11249 behavior provides the required behavior described in the RM for the
11250 actions to be taken on compiling such a file, namely that the pragmas
11251 apply to all units in the compilation, but not to subsequently compiled
11252 units.
11254 Finally, if configuration pragmas appear between units, they are appended
11255 to the previous unit. This results in the previous unit being illegal,
11256 since the compiler does not accept configuration pragmas that follow
11257 a unit. This provides the required RM behavior that forbids configuration
11258 pragmas other than those preceding the first compilation unit of a
11259 compilation.
11261 For most purposes, @code{gnatchop} will be used in default mode. The
11262 compilation mode described above is used only if you need exactly
11263 accurate behavior with respect to compilations, and you have files
11264 that contain multiple units and configuration pragmas. In this
11265 circumstance the use of @code{gnatchop} with the compilation mode
11266 switch provides the required behavior, and is for example the mode
11267 in which GNAT processes the ACVC tests.
11269 @node Command Line for gnatchop
11270 @section Command Line for @code{gnatchop}
11272 @noindent
11273 The @code{gnatchop} command has the form:
11275 @smallexample
11276 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11277 @c      @ovar{directory}
11278 @c Expanding @ovar macro inline (explanation in macro def comments)
11279 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11280       @r{[}@var{directory}@r{]}
11281 @end smallexample
11283 @noindent
11284 The only required argument is the file name of the file to be chopped.
11285 There are no restrictions on the form of this file name. The file itself
11286 contains one or more Ada units, in normal GNAT format, concatenated
11287 together. As shown, more than one file may be presented to be chopped.
11289 When run in default mode, @code{gnatchop} generates one output file in
11290 the current directory for each unit in each of the files.
11292 @var{directory}, if specified, gives the name of the directory to which
11293 the output files will be written. If it is not specified, all files are
11294 written to the current directory.
11296 For example, given a
11297 file called @file{hellofiles} containing
11299 @smallexample @c ada
11300 @group
11301 @cartouche
11302 procedure hello;
11304 with Text_IO; use Text_IO;
11305 procedure hello is
11306 begin
11307    Put_Line ("Hello");
11308 end hello;
11309 @end cartouche
11310 @end group
11311 @end smallexample
11313 @noindent
11314 the command
11316 @smallexample
11317 $ gnatchop ^hellofiles^HELLOFILES.^
11318 @end smallexample
11320 @noindent
11321 generates two files in the current directory, one called
11322 @file{hello.ads} containing the single line that is the procedure spec,
11323 and the other called @file{hello.adb} containing the remaining text. The
11324 original file is not affected. The generated files can be compiled in
11325 the normal manner.
11327 @noindent
11328 When gnatchop is invoked on a file that is empty or that contains only empty
11329 lines and/or comments, gnatchop will not fail, but will not produce any
11330 new sources.
11332 For example, given a
11333 file called @file{toto.txt} containing
11335 @smallexample @c ada
11336 @group
11337 @cartouche
11338 --  Just a comment
11339 @end cartouche
11340 @end group
11341 @end smallexample
11343 @noindent
11344 the command
11346 @smallexample
11347 $ gnatchop ^toto.txt^TOT.TXT^
11348 @end smallexample
11350 @noindent
11351 will not produce any new file and will result in the following warnings:
11353 @smallexample
11354 toto.txt:1:01: warning: empty file, contains no compilation units
11355 no compilation units found
11356 no source files written
11357 @end smallexample
11359 @node Switches for gnatchop
11360 @section Switches for @code{gnatchop}
11362 @noindent
11363 @command{gnatchop} recognizes the following switches:
11365 @table @option
11366 @c !sort!
11368 @item --version
11369 @cindex @option{--version} @command{gnatchop}
11370 Display Copyright and version, then exit disregarding all other options.
11372 @item --help
11373 @cindex @option{--help} @command{gnatchop}
11374 If @option{--version} was not used, display usage, then exit disregarding
11375 all other options.
11377 @item ^-c^/COMPILATION^
11378 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11379 Causes @code{gnatchop} to operate in compilation mode, in which
11380 configuration pragmas are handled according to strict RM rules. See
11381 previous section for a full description of this mode.
11383 @ifclear vms
11384 @item -gnat@var{xxx}
11385 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11386 used to parse the given file. Not all @var{xxx} options make sense,
11387 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11388 process a source file that uses Latin-2 coding for identifiers.
11389 @end ifclear
11391 @item ^-h^/HELP^
11392 Causes @code{gnatchop} to generate a brief help summary to the standard
11393 output file showing usage information.
11395 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11396 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11397 Limit generated file names to the specified number @code{mm}
11398 of characters.
11399 This is useful if the
11400 resulting set of files is required to be interoperable with systems
11401 which limit the length of file names.
11402 @ifset vms
11403 If no value is given, or
11404 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11405 a default of 39, suitable for OpenVMS Alpha
11406 Systems, is assumed
11407 @end ifset
11408 @ifclear vms
11409 No space is allowed between the @option{-k} and the numeric value. The numeric
11410 value may be omitted in which case a default of @option{-k8},
11411 suitable for use
11412 with DOS-like file systems, is used. If no @option{-k} switch
11413 is present then
11414 there is no limit on the length of file names.
11415 @end ifclear
11417 @item ^-p^/PRESERVE^
11418 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11419 Causes the file ^modification^creation^ time stamp of the input file to be
11420 preserved and used for the time stamp of the output file(s). This may be
11421 useful for preserving coherency of time stamps in an environment where
11422 @code{gnatchop} is used as part of a standard build process.
11424 @item ^-q^/QUIET^
11425 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11426 Causes output of informational messages indicating the set of generated
11427 files to be suppressed. Warnings and error messages are unaffected.
11429 @item ^-r^/REFERENCE^
11430 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11431 @findex Source_Reference
11432 Generate @code{Source_Reference} pragmas. Use this switch if the output
11433 files are regarded as temporary and development is to be done in terms
11434 of the original unchopped file. This switch causes
11435 @code{Source_Reference} pragmas to be inserted into each of the
11436 generated files to refers back to the original file name and line number.
11437 The result is that all error messages refer back to the original
11438 unchopped file.
11439 In addition, the debugging information placed into the object file (when
11440 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11441 specified)
11442 also refers back to this original file so that tools like profilers and
11443 debuggers will give information in terms of the original unchopped file.
11445 If the original file to be chopped itself contains
11446 a @code{Source_Reference}
11447 pragma referencing a third file, then gnatchop respects
11448 this pragma, and the generated @code{Source_Reference} pragmas
11449 in the chopped file refer to the original file, with appropriate
11450 line numbers. This is particularly useful when @code{gnatchop}
11451 is used in conjunction with @code{gnatprep} to compile files that
11452 contain preprocessing statements and multiple units.
11454 @item ^-v^/VERBOSE^
11455 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11456 Causes @code{gnatchop} to operate in verbose mode. The version
11457 number and copyright notice are output, as well as exact copies of
11458 the gnat1 commands spawned to obtain the chop control information.
11460 @item ^-w^/OVERWRITE^
11461 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11462 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11463 fatal error if there is already a file with the same name as a
11464 file it would otherwise output, in other words if the files to be
11465 chopped contain duplicated units. This switch bypasses this
11466 check, and causes all but the last instance of such duplicated
11467 units to be skipped.
11469 @ifclear vms
11470 @item --GCC=@var{xxxx}
11471 @cindex @option{--GCC=} (@code{gnatchop})
11472 Specify the path of the GNAT parser to be used. When this switch is used,
11473 no attempt is made to add the prefix to the GNAT parser executable.
11474 @end ifclear
11475 @end table
11477 @node Examples of gnatchop Usage
11478 @section Examples of @code{gnatchop} Usage
11480 @table @code
11481 @ifset vms
11482 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11483 @end ifset
11484 @ifclear vms
11485 @item gnatchop -w hello_s.ada prerelease/files
11486 @end ifclear
11488 Chops the source file @file{hello_s.ada}. The output files will be
11489 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11490 overwriting any
11491 files with matching names in that directory (no files in the current
11492 directory are modified).
11494 @item gnatchop ^archive^ARCHIVE.^
11495 Chops the source file @file{^archive^ARCHIVE.^}
11496 into the current directory. One
11497 useful application of @code{gnatchop} is in sending sets of sources
11498 around, for example in email messages. The required sources are simply
11499 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11500 command), and then
11501 @command{gnatchop} is used at the other end to reconstitute the original
11502 file names.
11504 @item gnatchop file1 file2 file3 direc
11505 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11506 the resulting files in the directory @file{direc}. Note that if any units
11507 occur more than once anywhere within this set of files, an error message
11508 is generated, and no files are written. To override this check, use the
11509 @option{^-w^/OVERWRITE^} switch,
11510 in which case the last occurrence in the last file will
11511 be the one that is output, and earlier duplicate occurrences for a given
11512 unit will be skipped.
11513 @end table
11515 @node Configuration Pragmas
11516 @chapter Configuration Pragmas
11517 @cindex Configuration pragmas
11518 @cindex Pragmas, configuration
11520 @noindent
11521 Configuration pragmas include those pragmas described as
11522 such in the Ada Reference Manual, as well as
11523 implementation-dependent pragmas that are configuration pragmas.
11524 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11525 for details on these additional GNAT-specific configuration pragmas.
11526 Most notably, the pragma @code{Source_File_Name}, which allows
11527 specifying non-default names for source files, is a configuration
11528 pragma. The following is a complete list of configuration pragmas
11529 recognized by GNAT:
11531 @smallexample
11532    Ada_83
11533    Ada_95
11534    Ada_05
11535    Ada_2005
11536    Ada_12
11537    Ada_2012
11538    Assertion_Policy
11539    Assume_No_Invalid_Values
11540    C_Pass_By_Copy
11541    Check_Name
11542    Check_Policy
11543    Compile_Time_Error
11544    Compile_Time_Warning
11545    Compiler_Unit
11546    Component_Alignment
11547    Convention_Identifier
11548    Debug_Policy
11549    Detect_Blocking
11550    Default_Storage_Pool
11551    Discard_Names
11552    Elaboration_Checks
11553    Eliminate
11554    Extend_System
11555    Extensions_Allowed
11556    External_Name_Casing
11557    Fast_Math
11558    Favor_Top_Level
11559    Float_Representation
11560    Implicit_Packing
11561    Initialize_Scalars
11562    Interrupt_State
11563    License
11564    Locking_Policy
11565    Long_Float
11566    No_Run_Time
11567    No_Strict_Aliasing
11568    Normalize_Scalars
11569    Optimize_Alignment
11570    Persistent_BSS
11571    Polling
11572    Priority_Specific_Dispatching
11573    Profile
11574    Profile_Warnings
11575    Propagate_Exceptions
11576    Queuing_Policy
11577    Ravenscar
11578    Restricted_Run_Time
11579    Restrictions
11580    Restrictions_Warnings
11581    Reviewable
11582    Short_Circuit_And_Or
11583    Source_File_Name
11584    Source_File_Name_Project
11585    Style_Checks
11586    Suppress
11587    Suppress_Exception_Locations
11588    Task_Dispatching_Policy
11589    Universal_Data
11590    Unsuppress
11591    Use_VADS_Size
11592    Validity_Checks
11593    Warnings
11594    Wide_Character_Encoding
11596 @end smallexample
11598 @menu
11599 * Handling of Configuration Pragmas::
11600 * The Configuration Pragmas Files::
11601 @end menu
11603 @node Handling of Configuration Pragmas
11604 @section Handling of Configuration Pragmas
11606 Configuration pragmas may either appear at the start of a compilation
11607 unit, in which case they apply only to that unit, or they may apply to
11608 all compilations performed in a given compilation environment.
11610 GNAT also provides the @code{gnatchop} utility to provide an automatic
11611 way to handle configuration pragmas following the semantics for
11612 compilations (that is, files with multiple units), described in the RM.
11613 See @ref{Operating gnatchop in Compilation Mode} for details.
11614 However, for most purposes, it will be more convenient to edit the
11615 @file{gnat.adc} file that contains configuration pragmas directly,
11616 as described in the following section.
11618 @node The Configuration Pragmas Files
11619 @section The Configuration Pragmas Files
11620 @cindex @file{gnat.adc}
11622 @noindent
11623 In GNAT a compilation environment is defined by the current
11624 directory at the time that a compile command is given. This current
11625 directory is searched for a file whose name is @file{gnat.adc}. If
11626 this file is present, it is expected to contain one or more
11627 configuration pragmas that will be applied to the current compilation.
11628 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11629 considered.
11631 Configuration pragmas may be entered into the @file{gnat.adc} file
11632 either by running @code{gnatchop} on a source file that consists only of
11633 configuration pragmas, or more conveniently  by
11634 direct editing of the @file{gnat.adc} file, which is a standard format
11635 source file.
11637 In addition to @file{gnat.adc}, additional files containing configuration
11638 pragmas may be applied to the current compilation using the switch
11639 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11640 contains only configuration pragmas. These configuration pragmas are
11641 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11642 is present and switch @option{-gnatA} is not used).
11644 It is allowed to specify several switches @option{-gnatec}, all of which
11645 will be taken into account.
11647 If you are using project file, a separate mechanism is provided using
11648 project attributes, see @ref{Specifying Configuration Pragmas} for more
11649 details.
11651 @ifset vms
11652 Of special interest to GNAT OpenVMS Alpha is the following
11653 configuration pragma:
11655 @smallexample @c ada
11656 @cartouche
11657 pragma Extend_System (Aux_DEC);
11658 @end cartouche
11659 @end smallexample
11661 @noindent
11662 In the presence of this pragma, GNAT adds to the definition of the
11663 predefined package SYSTEM all the additional types and subprograms that are
11664 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11665 @end ifset
11667 @node Handling Arbitrary File Naming Conventions Using gnatname
11668 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11669 @cindex Arbitrary File Naming Conventions
11671 @menu
11672 * Arbitrary File Naming Conventions::
11673 * Running gnatname::
11674 * Switches for gnatname::
11675 * Examples of gnatname Usage::
11676 @end menu
11678 @node Arbitrary File Naming Conventions
11679 @section Arbitrary File Naming Conventions
11681 @noindent
11682 The GNAT compiler must be able to know the source file name of a compilation
11683 unit.  When using the standard GNAT default file naming conventions
11684 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11685 does not need additional information.
11687 @noindent
11688 When the source file names do not follow the standard GNAT default file naming
11689 conventions, the GNAT compiler must be given additional information through
11690 a configuration pragmas file (@pxref{Configuration Pragmas})
11691 or a project file.
11692 When the non-standard file naming conventions are well-defined,
11693 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11694 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11695 if the file naming conventions are irregular or arbitrary, a number
11696 of pragma @code{Source_File_Name} for individual compilation units
11697 must be defined.
11698 To help maintain the correspondence between compilation unit names and
11699 source file names within the compiler,
11700 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11701 set of files.
11703 @node Running gnatname
11704 @section Running @code{gnatname}
11706 @noindent
11707 The usual form of the @code{gnatname} command is
11709 @smallexample
11710 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11711 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11712 @c Expanding @ovar macro inline (explanation in macro def comments)
11713 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11714       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11715 @end smallexample
11717 @noindent
11718 All of the arguments are optional. If invoked without any argument,
11719 @code{gnatname} will display its usage.
11721 @noindent
11722 When used with at least one naming pattern, @code{gnatname} will attempt to
11723 find all the compilation units in files that follow at least one of the
11724 naming patterns. To find these compilation units,
11725 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11726 regular files.
11728 @noindent
11729 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11730 Each Naming Pattern is enclosed between double quotes (or single
11731 quotes on Windows).
11732 A Naming Pattern is a regular expression similar to the wildcard patterns
11733 used in file names by the Unix shells or the DOS prompt.
11735 @noindent
11736 @code{gnatname} may be called with several sections of directories/patterns.
11737 Sections are separated by switch @code{--and}. In each section, there must be
11738 at least one pattern. If no directory is specified in a section, the current
11739 directory (or the project directory is @code{-P} is used) is implied.
11740 The options other that the directory switches and the patterns apply globally
11741 even if they are in different sections.
11743 @noindent
11744 Examples of Naming Patterns are
11746 @smallexample
11747    "*.[12].ada"
11748    "*.ad[sb]*"
11749    "body_*"    "spec_*"
11750 @end smallexample
11752 @noindent
11753 For a more complete description of the syntax of Naming Patterns,
11754 see the second kind of regular expressions described in @file{g-regexp.ads}
11755 (the ``Glob'' regular expressions).
11757 @noindent
11758 When invoked with no switch @code{-P}, @code{gnatname} will create a
11759 configuration pragmas file @file{gnat.adc} in the current working directory,
11760 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11761 unit.
11763 @node Switches for gnatname
11764 @section Switches for @code{gnatname}
11766 @noindent
11767 Switches for @code{gnatname} must precede any specified Naming Pattern.
11769 @noindent
11770 You may specify any of the following switches to @code{gnatname}:
11772 @table @option
11773 @c !sort!
11775 @item --version
11776 @cindex @option{--version} @command{gnatname}
11777 Display Copyright and version, then exit disregarding all other options.
11779 @item --help
11780 @cindex @option{--help} @command{gnatname}
11781 If @option{--version} was not used, display usage, then exit disregarding
11782 all other options.
11784 @item --and
11785 Start another section of directories/patterns.
11787 @item ^-c^/CONFIG_FILE=^@file{file}
11788 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11789 Create a configuration pragmas file @file{file} (instead of the default
11790 @file{gnat.adc}).
11791 @ifclear vms
11792 There may be zero, one or more space between @option{-c} and
11793 @file{file}.
11794 @end ifclear
11795 @file{file} may include directory information. @file{file} must be
11796 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11797 When a switch @option{^-c^/CONFIG_FILE^} is
11798 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11800 @item ^-d^/SOURCE_DIRS=^@file{dir}
11801 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11802 Look for source files in directory @file{dir}. There may be zero, one or more
11803 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11804 When a switch @option{^-d^/SOURCE_DIRS^}
11805 is specified, the current working directory will not be searched for source
11806 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11807 or @option{^-D^/DIR_FILES^} switch.
11808 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11809 If @file{dir} is a relative path, it is relative to the directory of
11810 the configuration pragmas file specified with switch
11811 @option{^-c^/CONFIG_FILE^},
11812 or to the directory of the project file specified with switch
11813 @option{^-P^/PROJECT_FILE^} or,
11814 if neither switch @option{^-c^/CONFIG_FILE^}
11815 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11816 current working directory. The directory
11817 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11819 @item ^-D^/DIRS_FILE=^@file{file}
11820 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11821 Look for source files in all directories listed in text file @file{file}.
11822 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11823 and @file{file}.
11824 @file{file} must be an existing, readable text file.
11825 Each nonempty line in @file{file} must be a directory.
11826 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11827 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11828 @file{file}.
11830 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11831 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11832 Foreign patterns. Using this switch, it is possible to add sources of languages
11833 other than Ada to the list of sources of a project file.
11834 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11835 For example,
11836 @smallexample
11837 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11838 @end smallexample
11839 @noindent
11840 will look for Ada units in all files with the @file{.ada} extension,
11841 and will add to the list of file for project @file{prj.gpr} the C files
11842 with extension @file{.^c^C^}.
11844 @item ^-h^/HELP^
11845 @cindex @option{^-h^/HELP^} (@code{gnatname})
11846 Output usage (help) information. The output is written to @file{stdout}.
11848 @item ^-P^/PROJECT_FILE=^@file{proj}
11849 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11850 Create or update project file @file{proj}. There may be zero, one or more space
11851 between @option{-P} and @file{proj}. @file{proj} may include directory
11852 information. @file{proj} must be writable.
11853 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11854 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11855 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11857 @item ^-v^/VERBOSE^
11858 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11859 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11860 This includes name of the file written, the name of the directories to search
11861 and, for each file in those directories whose name matches at least one of
11862 the Naming Patterns, an indication of whether the file contains a unit,
11863 and if so the name of the unit.
11865 @item ^-v -v^/VERBOSE /VERBOSE^
11866 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11867 Very Verbose mode. In addition to the output produced in verbose mode,
11868 for each file in the searched directories whose name matches none of
11869 the Naming Patterns, an indication is given that there is no match.
11871 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11872 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11873 Excluded patterns. Using this switch, it is possible to exclude some files
11874 that would match the name patterns. For example,
11875 @smallexample
11876 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11877 @end smallexample
11878 @noindent
11879 will look for Ada units in all files with the @file{.ada} extension,
11880 except those whose names end with @file{_nt.ada}.
11882 @end table
11884 @node Examples of gnatname Usage
11885 @section Examples of @code{gnatname} Usage
11887 @ifset vms
11888 @smallexample
11889 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11890 @end smallexample
11891 @end ifset
11893 @ifclear vms
11894 @smallexample
11895 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11896 @end smallexample
11897 @end ifclear
11899 @noindent
11900 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11901 and be writable. In addition, the directory
11902 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11903 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11905 @ifclear vms
11906 Note the optional spaces after @option{-c} and @option{-d}.
11907 @end ifclear
11909 @smallexample
11910 @ifclear vms
11911 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11912   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11913 @end ifclear
11914 @ifset vms
11915 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11916   /EXCLUDED_PATTERN=*_nt_body.ada
11917   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11918   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11919 @end ifset
11920 @end smallexample
11922 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11923 even in conjunction with one or several switches
11924 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11925 are used in this example.
11927 @c *****************************************
11928 @c * G N A T  P r o j e c t  M a n a g e r *
11929 @c *****************************************
11931 @c ------ macros for projects.texi
11932 @c These macros are needed when building the gprbuild documentation, but
11933 @c should have no effect in the gnat user's guide
11935 @macro CODESAMPLE{TXT}
11936 @smallexample
11937 @group
11938 \TXT\
11939 @end group
11940 @end smallexample
11941 @end macro
11943 @macro PROJECTFILE{TXT}
11944 @CODESAMPLE{\TXT\}
11945 @end macro
11947 @c simulates a newline when in a @CODESAMPLE
11948 @macro NL{}
11949 @end macro
11951 @macro TIP{TXT}
11952 @quotation
11953 @noindent
11954 \TXT\
11955 @end quotation
11956 @end macro
11958 @macro TIPHTML{TXT}
11959 \TXT\
11960 @end macro
11962 @macro IMPORTANT{TXT}
11963 @quotation
11964 @noindent
11965 \TXT\
11966 @end quotation
11968 @end macro
11970 @macro NOTE{TXT}
11971 @quotation
11972 @noindent
11973 \TXT\
11974 @end quotation
11975 @end macro
11977 @include projects.texi
11979 @c *****************************************
11980 @c * Cross-referencing tools
11981 @c *****************************************
11983 @node The Cross-Referencing Tools gnatxref and gnatfind
11984 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
11985 @findex gnatxref
11986 @findex gnatfind
11988 @noindent
11989 The compiler generates cross-referencing information (unless
11990 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
11991 This information indicates where in the source each entity is declared and
11992 referenced. Note that entities in package Standard are not included, but
11993 entities in all other predefined units are included in the output.
11995 Before using any of these two tools, you need to compile successfully your
11996 application, so that GNAT gets a chance to generate the cross-referencing
11997 information.
11999 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12000 information to provide the user with the capability to easily locate the
12001 declaration and references to an entity. These tools are quite similar,
12002 the difference being that @code{gnatfind} is intended for locating
12003 definitions and/or references to a specified entity or entities, whereas
12004 @code{gnatxref} is oriented to generating a full report of all
12005 cross-references.
12007 To use these tools, you must not compile your application using the
12008 @option{-gnatx} switch on the @command{gnatmake} command line
12009 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12010 information will not be generated.
12012 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12013 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12015 @menu
12016 * Switches for gnatxref::
12017 * Switches for gnatfind::
12018 * Project Files for gnatxref and gnatfind::
12019 * Regular Expressions in gnatfind and gnatxref::
12020 * Examples of gnatxref Usage::
12021 * Examples of gnatfind Usage::
12022 @end menu
12024 @node Switches for gnatxref
12025 @section @code{gnatxref} Switches
12027 @noindent
12028 The command invocation for @code{gnatxref} is:
12029 @smallexample
12030 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12031 @c Expanding @ovar macro inline (explanation in macro def comments)
12032 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12033 @end smallexample
12035 @noindent
12036 where
12038 @table @var
12039 @item sourcefile1
12040 @itemx sourcefile2
12041 identifies the source files for which a report is to be generated. The
12042 ``with''ed units will be processed too. You must provide at least one file.
12044 These file names are considered to be regular expressions, so for instance
12045 specifying @file{source*.adb} is the same as giving every file in the current
12046 directory whose name starts with @file{source} and whose extension is
12047 @file{adb}.
12049 You shouldn't specify any directory name, just base names. @command{gnatxref}
12050 and @command{gnatfind} will be able to locate these files by themselves using
12051 the source path. If you specify directories, no result is produced.
12053 @end table
12055 @noindent
12056 The switches can be:
12057 @table @option
12058 @c !sort!
12059 @item --version
12060 @cindex @option{--version} @command{gnatxref}
12061 Display Copyright and version, then exit disregarding all other options.
12063 @item --help
12064 @cindex @option{--help} @command{gnatxref}
12065 If @option{--version} was not used, display usage, then exit disregarding
12066 all other options.
12068 @item ^-a^/ALL_FILES^
12069 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12070 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12071 the read-only files found in the library search path. Otherwise, these files
12072 will be ignored. This option can be used to protect Gnat sources or your own
12073 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12074 much faster, and their output much smaller. Read-only here refers to access
12075 or permissions status in the file system for the current user.
12077 @item -aIDIR
12078 @cindex @option{-aIDIR} (@command{gnatxref})
12079 When looking for source files also look in directory DIR. The order in which
12080 source file search is undertaken is the same as for @command{gnatmake}.
12082 @item -aODIR
12083 @cindex @option{-aODIR} (@command{gnatxref})
12084 When searching for library and object files, look in directory
12085 DIR. The order in which library files are searched is the same as for
12086 @command{gnatmake}.
12088 @item -nostdinc
12089 @cindex @option{-nostdinc} (@command{gnatxref})
12090 Do not look for sources in the system default directory.
12092 @item -nostdlib
12093 @cindex @option{-nostdlib} (@command{gnatxref})
12094 Do not look for library files in the system default directory.
12096 @item --ext=@var{extension}
12097 @cindex @option{--ext} (@command{gnatxref})
12098 Specify an alternate ali file extension. The default is @code{ali} and other
12099 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12100 switch. Note that if this switch overrides the default, which means that only
12101 the new extension will be considered.
12103 @item --RTS=@var{rts-path}
12104 @cindex @option{--RTS} (@command{gnatxref})
12105 Specifies the default location of the runtime library. Same meaning as the
12106 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12108 @item ^-d^/DERIVED_TYPES^
12109 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12110 If this switch is set @code{gnatxref} will output the parent type
12111 reference for each matching derived types.
12113 @item ^-f^/FULL_PATHNAME^
12114 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12115 If this switch is set, the output file names will be preceded by their
12116 directory (if the file was found in the search path). If this switch is
12117 not set, the directory will not be printed.
12119 @item ^-g^/IGNORE_LOCALS^
12120 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12121 If this switch is set, information is output only for library-level
12122 entities, ignoring local entities. The use of this switch may accelerate
12123 @code{gnatfind} and @code{gnatxref}.
12125 @item -IDIR
12126 @cindex @option{-IDIR} (@command{gnatxref})
12127 Equivalent to @samp{-aODIR -aIDIR}.
12129 @item -pFILE
12130 @cindex @option{-pFILE} (@command{gnatxref})
12131 Specify a project file to use @xref{GNAT Project Manager}.
12132 If you need to use the @file{.gpr}
12133 project files, you should use gnatxref through the GNAT driver
12134 (@command{gnat xref -Pproject}).
12136 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12137 project file in the current directory.
12139 If a project file is either specified or found by the tools, then the content
12140 of the source directory and object directory lines are added as if they
12141 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12142 and @samp{^-aO^OBJECT_SEARCH^}.
12143 @item ^-u^/UNUSED^
12144 Output only unused symbols. This may be really useful if you give your
12145 main compilation unit on the command line, as @code{gnatxref} will then
12146 display every unused entity and 'with'ed package.
12148 @ifclear vms
12149 @item -v
12150 Instead of producing the default output, @code{gnatxref} will generate a
12151 @file{tags} file that can be used by vi. For examples how to use this
12152 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12153 to the standard output, thus you will have to redirect it to a file.
12154 @end ifclear
12156 @end table
12158 @noindent
12159 All these switches may be in any order on the command line, and may even
12160 appear after the file names. They need not be separated by spaces, thus
12161 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12162 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12164 @node Switches for gnatfind
12165 @section @code{gnatfind} Switches
12167 @noindent
12168 The command line for @code{gnatfind} is:
12170 @smallexample
12171 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12172 @c       @r{[}@var{file1} @var{file2} @dots{}]
12173 @c Expanding @ovar macro inline (explanation in macro def comments)
12174 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12175       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12176 @end smallexample
12178 @noindent
12179 where
12181 @table @var
12182 @item pattern
12183 An entity will be output only if it matches the regular expression found
12184 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12186 Omitting the pattern is equivalent to specifying @samp{*}, which
12187 will match any entity. Note that if you do not provide a pattern, you
12188 have to provide both a sourcefile and a line.
12190 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12191 for matching purposes. At the current time there is no support for
12192 8-bit codes other than Latin-1, or for wide characters in identifiers.
12194 @item sourcefile
12195 @code{gnatfind} will look for references, bodies or declarations
12196 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12197 and column @var{column}. See @ref{Examples of gnatfind Usage}
12198 for syntax examples.
12200 @item line
12201 is a decimal integer identifying the line number containing
12202 the reference to the entity (or entities) to be located.
12204 @item column
12205 is a decimal integer identifying the exact location on the
12206 line of the first character of the identifier for the
12207 entity reference. Columns are numbered from 1.
12209 @item file1 file2 @dots{}
12210 The search will be restricted to these source files. If none are given, then
12211 the search will be done for every library file in the search path.
12212 These file must appear only after the pattern or sourcefile.
12214 These file names are considered to be regular expressions, so for instance
12215 specifying @file{source*.adb} is the same as giving every file in the current
12216 directory whose name starts with @file{source} and whose extension is
12217 @file{adb}.
12219 The location of the spec of the entity will always be displayed, even if it
12220 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12221 occurrences of the entity in the separate units of the ones given on the
12222 command line will also be displayed.
12224 Note that if you specify at least one file in this part, @code{gnatfind} may
12225 sometimes not be able to find the body of the subprograms.
12227 @end table
12229 @noindent
12230 At least one of 'sourcefile' or 'pattern' has to be present on
12231 the command line.
12233 The following switches are available:
12234 @table @option
12235 @c !sort!
12237 @cindex @option{--version} @command{gnatfind}
12238 Display Copyright and version, then exit disregarding all other options.
12240 @item --help
12241 @cindex @option{--help} @command{gnatfind}
12242 If @option{--version} was not used, display usage, then exit disregarding
12243 all other options.
12245 @item ^-a^/ALL_FILES^
12246 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12247 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12248 the read-only files found in the library search path. Otherwise, these files
12249 will be ignored. This option can be used to protect Gnat sources or your own
12250 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12251 much faster, and their output much smaller. Read-only here refers to access
12252 or permission status in the file system for the current user.
12254 @item -aIDIR
12255 @cindex @option{-aIDIR} (@command{gnatfind})
12256 When looking for source files also look in directory DIR. The order in which
12257 source file search is undertaken is the same as for @command{gnatmake}.
12259 @item -aODIR
12260 @cindex @option{-aODIR} (@command{gnatfind})
12261 When searching for library and object files, look in directory
12262 DIR. The order in which library files are searched is the same as for
12263 @command{gnatmake}.
12265 @item -nostdinc
12266 @cindex @option{-nostdinc} (@command{gnatfind})
12267 Do not look for sources in the system default directory.
12269 @item -nostdlib
12270 @cindex @option{-nostdlib} (@command{gnatfind})
12271 Do not look for library files in the system default directory.
12273 @item --ext=@var{extension}
12274 @cindex @option{--ext} (@command{gnatfind})
12275 Specify an alternate ali file extension. The default is @code{ali} and other
12276 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12277 switch. Note that if this switch overrides the default, which means that only
12278 the new extension will be considered.
12280 @item --RTS=@var{rts-path}
12281 @cindex @option{--RTS} (@command{gnatfind})
12282 Specifies the default location of the runtime library. Same meaning as the
12283 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12285 @item ^-d^/DERIVED_TYPE_INFORMATION^
12286 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12287 If this switch is set, then @code{gnatfind} will output the parent type
12288 reference for each matching derived types.
12290 @item ^-e^/EXPRESSIONS^
12291 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12292 By default, @code{gnatfind} accept the simple regular expression set for
12293 @samp{pattern}. If this switch is set, then the pattern will be
12294 considered as full Unix-style regular expression.
12296 @item ^-f^/FULL_PATHNAME^
12297 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12298 If this switch is set, the output file names will be preceded by their
12299 directory (if the file was found in the search path). If this switch is
12300 not set, the directory will not be printed.
12302 @item ^-g^/IGNORE_LOCALS^
12303 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12304 If this switch is set, information is output only for library-level
12305 entities, ignoring local entities. The use of this switch may accelerate
12306 @code{gnatfind} and @code{gnatxref}.
12308 @item -IDIR
12309 @cindex @option{-IDIR} (@command{gnatfind})
12310 Equivalent to @samp{-aODIR -aIDIR}.
12312 @item -pFILE
12313 @cindex @option{-pFILE} (@command{gnatfind})
12314 Specify a project file (@pxref{GNAT Project Manager}) to use.
12315 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12316 project file in the current directory.
12318 If a project file is either specified or found by the tools, then the content
12319 of the source directory and object directory lines are added as if they
12320 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12321 @samp{^-aO^/OBJECT_SEARCH^}.
12323 @item ^-r^/REFERENCES^
12324 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12325 By default, @code{gnatfind} will output only the information about the
12326 declaration, body or type completion of the entities. If this switch is
12327 set, the @code{gnatfind} will locate every reference to the entities in
12328 the files specified on the command line (or in every file in the search
12329 path if no file is given on the command line).
12331 @item ^-s^/PRINT_LINES^
12332 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12333 If this switch is set, then @code{gnatfind} will output the content
12334 of the Ada source file lines were the entity was found.
12336 @item ^-t^/TYPE_HIERARCHY^
12337 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12338 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12339 the specified type. It act like -d option but recursively from parent
12340 type to parent type. When this switch is set it is not possible to
12341 specify more than one file.
12343 @end table
12345 @noindent
12346 All these switches may be in any order on the command line, and may even
12347 appear after the file names. They need not be separated by spaces, thus
12348 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12349 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12351 As stated previously, gnatfind will search in every directory in the
12352 search path. You can force it to look only in the current directory if
12353 you specify @code{*} at the end of the command line.
12355 @node Project Files for gnatxref and gnatfind
12356 @section Project Files for @command{gnatxref} and @command{gnatfind}
12358 @noindent
12359 Project files allow a programmer to specify how to compile its
12360 application, where to find sources, etc.  These files are used
12361 @ifclear vms
12362 primarily by GPS, but they can also be used
12363 @end ifclear
12364 by the two tools
12365 @code{gnatxref} and @code{gnatfind}.
12367 A project file name must end with @file{.gpr}. If a single one is
12368 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12369 extract the information from it. If multiple project files are found, none of
12370 them is read, and you have to use the @samp{-p} switch to specify the one
12371 you want to use.
12373 The following lines can be included, even though most of them have default
12374 values which can be used in most cases.
12375 The lines can be entered in any order in the file.
12376 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12377 each line. If you have multiple instances, only the last one is taken into
12378 account.
12380 @table @code
12381 @item src_dir=DIR
12382 [default: @code{"^./^[]^"}]
12383 specifies a directory where to look for source files. Multiple @code{src_dir}
12384 lines can be specified and they will be searched in the order they
12385 are specified.
12387 @item obj_dir=DIR
12388 [default: @code{"^./^[]^"}]
12389 specifies a directory where to look for object and library files. Multiple
12390 @code{obj_dir} lines can be specified, and they will be searched in the order
12391 they are specified
12393 @item comp_opt=SWITCHES
12394 [default: @code{""}]
12395 creates a variable which can be referred to subsequently by using
12396 the @code{$@{comp_opt@}} notation. This is intended to store the default
12397 switches given to @command{gnatmake} and @command{gcc}.
12399 @item bind_opt=SWITCHES
12400 [default: @code{""}]
12401 creates a variable which can be referred to subsequently by using
12402 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12403 switches given to @command{gnatbind}.
12405 @item link_opt=SWITCHES
12406 [default: @code{""}]
12407 creates a variable which can be referred to subsequently by using
12408 the @samp{$@{link_opt@}} notation. This is intended to store the default
12409 switches given to @command{gnatlink}.
12411 @item main=EXECUTABLE
12412 [default: @code{""}]
12413 specifies the name of the executable for the application. This variable can
12414 be referred to in the following lines by using the @samp{$@{main@}} notation.
12416 @ifset vms
12417 @item comp_cmd=COMMAND
12418 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12419 @end ifset
12420 @ifclear vms
12421 @item comp_cmd=COMMAND
12422 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12423 @end ifclear
12424 specifies the command used to compile a single file in the application.
12426 @ifset vms
12427 @item make_cmd=COMMAND
12428 [default: @code{"GNAT MAKE $@{main@}
12429 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12430 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12431 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12432 @end ifset
12433 @ifclear vms
12434 @item make_cmd=COMMAND
12435 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12436 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12437 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12438 @end ifclear
12439 specifies the command used to recompile the whole application.
12441 @item run_cmd=COMMAND
12442 [default: @code{"$@{main@}"}]
12443 specifies the command used to run the application.
12445 @item debug_cmd=COMMAND
12446 [default: @code{"gdb $@{main@}"}]
12447 specifies the command used to debug the application
12449 @end table
12451 @noindent
12452 @command{gnatxref} and @command{gnatfind} only take into account the
12453 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12455 @node Regular Expressions in gnatfind and gnatxref
12456 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12458 @noindent
12459 As specified in the section about @command{gnatfind}, the pattern can be a
12460 regular expression. Actually, there are to set of regular expressions
12461 which are recognized by the program:
12463 @table @code
12464 @item globbing patterns
12465 These are the most usual regular expression. They are the same that you
12466 generally used in a Unix shell command line, or in a DOS session.
12468 Here is a more formal grammar:
12469 @smallexample
12470 @group
12471 @iftex
12472 @leftskip=.5cm
12473 @end iftex
12474 regexp ::= term
12475 term   ::= elmt            -- matches elmt
12476 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12477 term   ::= *               -- any string of 0 or more characters
12478 term   ::= ?               -- matches any character
12479 term   ::= [char @{char@}]   -- matches any character listed
12480 term   ::= [char - char]   -- matches any character in range
12481 @end group
12482 @end smallexample
12484 @item full regular expression
12485 The second set of regular expressions is much more powerful. This is the
12486 type of regular expressions recognized by utilities such a @file{grep}.
12488 The following is the form of a regular expression, expressed in Ada
12489 reference manual style BNF is as follows
12491 @smallexample
12492 @iftex
12493 @leftskip=.5cm
12494 @end iftex
12495 @group
12496 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12498 term ::= item @{item@}       -- concatenation (item then item)
12500 item ::= elmt              -- match elmt
12501 item ::= elmt *            -- zero or more elmt's
12502 item ::= elmt +            -- one or more elmt's
12503 item ::= elmt ?            -- matches elmt or nothing
12504 @end group
12505 @group
12506 elmt ::= nschar            -- matches given character
12507 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12508 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12509 elmt ::= [char - char]     -- matches chars in given range
12510 elmt ::= \ char            -- matches given character
12511 elmt ::= .                 -- matches any single character
12512 elmt ::= ( regexp )        -- parens used for grouping
12514 char ::= any character, including special characters
12515 nschar ::= any character except ()[].*+?^^^
12516 @end group
12517 @end smallexample
12519 Following are a few examples:
12521 @table @samp
12522 @item abcde|fghi
12523 will match any of the two strings @samp{abcde} and @samp{fghi},
12525 @item abc*d
12526 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12527 @samp{abcccd}, and so on,
12529 @item [a-z]+
12530 will match any string which has only lowercase characters in it (and at
12531 least one character.
12533 @end table
12534 @end table
12536 @node Examples of gnatxref Usage
12537 @section Examples of @code{gnatxref} Usage
12539 @subsection General Usage
12541 @noindent
12542 For the following examples, we will consider the following units:
12544 @smallexample @c ada
12545 @group
12546 @cartouche
12547 main.ads:
12548 1: with Bar;
12549 2: package Main is
12550 3:     procedure Foo (B : in Integer);
12551 4:     C : Integer;
12552 5: private
12553 6:     D : Integer;
12554 7: end Main;
12556 main.adb:
12557 1: package body Main is
12558 2:     procedure Foo (B : in Integer) is
12559 3:     begin
12560 4:        C := B;
12561 5:        D := B;
12562 6:        Bar.Print (B);
12563 7:        Bar.Print (C);
12564 8:     end Foo;
12565 9: end Main;
12567 bar.ads:
12568 1: package Bar is
12569 2:     procedure Print (B : Integer);
12570 3: end bar;
12571 @end cartouche
12572 @end group
12573 @end smallexample
12575 @table @code
12577 @noindent
12578 The first thing to do is to recompile your application (for instance, in
12579 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12580 the cross-referencing information.
12581 You can then issue any of the following commands:
12583 @item gnatxref main.adb
12584 @code{gnatxref} generates cross-reference information for main.adb
12585 and every unit 'with'ed by main.adb.
12587 The output would be:
12588 @smallexample
12589 @iftex
12590 @leftskip=0cm
12591 @end iftex
12592 B                                                      Type: Integer
12593   Decl: bar.ads           2:22
12594 B                                                      Type: Integer
12595   Decl: main.ads          3:20
12596   Body: main.adb          2:20
12597   Ref:  main.adb          4:13     5:13     6:19
12598 Bar                                                    Type: Unit
12599   Decl: bar.ads           1:9
12600   Ref:  main.adb          6:8      7:8
12601        main.ads           1:6
12602 C                                                      Type: Integer
12603   Decl: main.ads          4:5
12604   Modi: main.adb          4:8
12605   Ref:  main.adb          7:19
12606 D                                                      Type: Integer
12607   Decl: main.ads          6:5
12608   Modi: main.adb          5:8
12609 Foo                                                    Type: Unit
12610   Decl: main.ads          3:15
12611   Body: main.adb          2:15
12612 Main                                                    Type: Unit
12613   Decl: main.ads          2:9
12614   Body: main.adb          1:14
12615 Print                                                   Type: Unit
12616   Decl: bar.ads           2:15
12617   Ref:  main.adb          6:12     7:12
12618 @end smallexample
12620 @noindent
12621 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12622 its body is in main.adb, line 1, column 14 and is not referenced any where.
12624 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12625 it referenced in main.adb, line 6 column 12 and line 7 column 12.
12627 @item gnatxref package1.adb package2.ads
12628 @code{gnatxref} will generates cross-reference information for
12629 package1.adb, package2.ads and any other package 'with'ed by any
12630 of these.
12632 @end table
12634 @ifclear vms
12635 @subsection Using gnatxref with vi
12637 @code{gnatxref} can generate a tags file output, which can be used
12638 directly from @command{vi}. Note that the standard version of @command{vi}
12639 will not work properly with overloaded symbols. Consider using another
12640 free implementation of @command{vi}, such as @command{vim}.
12642 @smallexample
12643 $ gnatxref -v gnatfind.adb > tags
12644 @end smallexample
12646 @noindent
12647 will generate the tags file for @code{gnatfind} itself (if the sources
12648 are in the search path!).
12650 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12651 (replacing @var{entity} by whatever you are looking for), and vi will
12652 display a new file with the corresponding declaration of entity.
12653 @end ifclear
12655 @node Examples of gnatfind Usage
12656 @section Examples of @code{gnatfind} Usage
12658 @table @code
12660 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12661 Find declarations for all entities xyz referenced at least once in
12662 main.adb. The references are search in every library file in the search
12663 path.
12665 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12666 switch is set)
12668 The output will look like:
12669 @smallexample
12670 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12671 ^directory/^[directory]^main.adb:24:10: xyz <= body
12672 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12673 @end smallexample
12675 @noindent
12676 that is to say, one of the entities xyz found in main.adb is declared at
12677 line 12 of main.ads (and its body is in main.adb), and another one is
12678 declared at line 45 of foo.ads
12680 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12681 This is the same command as the previous one, instead @code{gnatfind} will
12682 display the content of the Ada source file lines.
12684 The output will look like:
12686 @smallexample
12687 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12688    procedure xyz;
12689 ^directory/^[directory]^main.adb:24:10: xyz <= body
12690    procedure xyz is
12691 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12692    xyz : Integer;
12693 @end smallexample
12695 @noindent
12696 This can make it easier to find exactly the location your are looking
12697 for.
12699 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12700 Find references to all entities containing an x that are
12701 referenced on line 123 of main.ads.
12702 The references will be searched only in main.ads and foo.adb.
12704 @item gnatfind main.ads:123
12705 Find declarations and bodies for all entities that are referenced on
12706 line 123 of main.ads.
12708 This is the same as @code{gnatfind "*":main.adb:123}.
12710 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12711 Find the declaration for the entity referenced at column 45 in
12712 line 123 of file main.adb in directory mydir. Note that it
12713 is usual to omit the identifier name when the column is given,
12714 since the column position identifies a unique reference.
12716 The column has to be the beginning of the identifier, and should not
12717 point to any character in the middle of the identifier.
12719 @end table
12721 @c *********************************
12722 @node The GNAT Pretty-Printer gnatpp
12723 @chapter The GNAT Pretty-Printer @command{gnatpp}
12724 @findex gnatpp
12725 @cindex Pretty-Printer
12727 @noindent
12728 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12729 for source reformatting / pretty-printing.
12730 It takes an Ada source file as input and generates a reformatted
12731 version as output.
12732 You can specify various style directives via switches; e.g.,
12733 identifier case conventions, rules of indentation, and comment layout.
12735 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12736 tree for the input source and thus requires the input to be syntactically and
12737 semantically legal.
12738 If this condition is not met, @command{gnatpp} will terminate with an
12739 error message; no output file will be generated.
12741 If the source files presented to @command{gnatpp} contain
12742 preprocessing directives, then the output file will
12743 correspond to the generated source after all
12744 preprocessing is carried out. There is no way
12745 using @command{gnatpp} to obtain pretty printed files that
12746 include the preprocessing directives.
12748 If the compilation unit
12749 contained in the input source depends semantically upon units located
12750 outside the current directory, you have to provide the source search path
12751 when invoking @command{gnatpp}, if these units are contained in files with
12752 names that do not follow the GNAT file naming rules, you have to provide
12753 the configuration file describing the corresponding naming scheme;
12754 see the description of the @command{gnatpp}
12755 switches below. Another possibility is to use a project file and to
12756 call @command{gnatpp} through the @command{gnat} driver
12758 The @command{gnatpp} command has the form
12760 @smallexample
12761 @c $ gnatpp @ovar{switches} @var{filename}
12762 @c Expanding @ovar macro inline (explanation in macro def comments)
12763 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12764 @end smallexample
12766 @noindent
12767 where
12768 @itemize @bullet
12769 @item
12770 @var{switches} is an optional sequence of switches defining such properties as
12771 the formatting rules, the source search path, and the destination for the
12772 output source file
12774 @item
12775 @var{filename} is the name (including the extension) of the source file to
12776 reformat; ``wildcards'' or several file names on the same gnatpp command are
12777 allowed.  The file name may contain path information; it does not have to
12778 follow the GNAT file naming rules
12780 @item
12781 @samp{@var{gcc_switches}} is a list of switches for
12782 @command{gcc}. They will be passed on to all compiler invocations made by
12783 @command{gnatelim} to generate the ASIS trees. Here you can provide
12784 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12785 use the @option{-gnatec} switch to set the configuration file,
12786 use the @option{-gnat05} switch if sources should be compiled in
12787 Ada 2005 mode  etc.
12788 @end itemize
12790 @menu
12791 * Switches for gnatpp::
12792 * Formatting Rules::
12793 @end menu
12795 @node Switches for gnatpp
12796 @section Switches for @command{gnatpp}
12798 @noindent
12799 The following subsections describe the various switches accepted by
12800 @command{gnatpp}, organized by category.
12802 @ifclear vms
12803 You specify a switch by supplying a name and generally also a value.
12804 In many cases the values for a switch with a given name are incompatible with
12805 each other
12806 (for example the switch that controls the casing of a reserved word may have
12807 exactly one value: upper case, lower case, or
12808 mixed case) and thus exactly one such switch can be in effect for an
12809 invocation of @command{gnatpp}.
12810 If more than one is supplied, the last one is used.
12811 However, some values for the same switch are mutually compatible.
12812 You may supply several such switches to @command{gnatpp}, but then
12813 each must be specified in full, with both the name and the value.
12814 Abbreviated forms (the name appearing once, followed by each value) are
12815 not permitted.
12816 For example, to set
12817 the alignment of the assignment delimiter both in declarations and in
12818 assignment statements, you must write @option{-A2A3}
12819 (or @option{-A2 -A3}), but not @option{-A23}.
12820 @end ifclear
12822 @ifset vms
12823 In many cases the set of options for a given qualifier are incompatible with
12824 each other (for example the qualifier that controls the casing of a reserved
12825 word may have exactly one option, which specifies either upper case, lower
12826 case, or mixed case), and thus exactly one such option can be in effect for
12827 an invocation of @command{gnatpp}.
12828 If more than one is supplied, the last one is used.
12829 However, some qualifiers have options that are mutually compatible,
12830 and then you may then supply several such options when invoking
12831 @command{gnatpp}.
12832 @end ifset
12834 In most cases, it is obvious whether or not the
12835 ^values for a switch with a given name^options for a given qualifier^
12836 are compatible with each other.
12837 When the semantics might not be evident, the summaries below explicitly
12838 indicate the effect.
12840 @menu
12841 * Alignment Control::
12842 * Casing Control::
12843 * Construct Layout Control::
12844 * General Text Layout Control::
12845 * Other Formatting Options::
12846 * Setting the Source Search Path::
12847 * Output File Control::
12848 * Other gnatpp Switches::
12849 @end menu
12851 @node Alignment Control
12852 @subsection Alignment Control
12853 @cindex Alignment control in @command{gnatpp}
12855 @noindent
12856 Programs can be easier to read if certain constructs are vertically aligned.
12857 By default all alignments are set ON.
12858 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12859 OFF, and then use one or more of the other
12860 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12861 to activate alignment for specific constructs.
12863 @table @option
12864 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12866 @ifset vms
12867 @item /ALIGN=ON
12868 Set all alignments to ON
12869 @end ifset
12871 @item ^-A0^/ALIGN=OFF^
12872 Set all alignments to OFF
12874 @item ^-A1^/ALIGN=COLONS^
12875 Align @code{:} in declarations
12877 @item ^-A2^/ALIGN=DECLARATIONS^
12878 Align @code{:=} in initializations in declarations
12880 @item ^-A3^/ALIGN=STATEMENTS^
12881 Align @code{:=} in assignment statements
12883 @item ^-A4^/ALIGN=ARROWS^
12884 Align @code{=>} in associations
12886 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12887 Align @code{at} keywords in the component clauses in record
12888 representation clauses
12889 @end table
12891 @noindent
12892 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12893 is allowed.
12895 @node Casing Control
12896 @subsection Casing Control
12897 @cindex Casing control in @command{gnatpp}
12899 @noindent
12900 @command{gnatpp} allows you to specify the casing for reserved words,
12901 pragma names, attribute designators and identifiers.
12902 For identifiers you may define a
12903 general rule for name casing but also override this rule
12904 via a set of dictionary files.
12906 Three types of casing are supported: lower case, upper case, and mixed case.
12907 Lower and upper case are self-explanatory (but since some letters in
12908 Latin1 and other GNAT-supported character sets
12909 exist only in lower-case form, an upper case conversion will have no
12910 effect on them.)
12911 ``Mixed case'' means that the first letter, and also each letter immediately
12912 following an underscore, are converted to their uppercase forms;
12913 all the other letters are converted to their lowercase forms.
12915 @table @option
12916 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12917 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12918 Attribute designators are lower case
12920 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12921 Attribute designators are upper case
12923 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12924 Attribute designators are mixed case (this is the default)
12926 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12927 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12928 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12929 lower case (this is the default)
12931 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12932 Keywords are upper case
12934 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12935 @item ^-nD^/NAME_CASING=AS_DECLARED^
12936 Name casing for defining occurrences are as they appear in the source file
12937 (this is the default)
12939 @item ^-nU^/NAME_CASING=UPPER_CASE^
12940 Names are in upper case
12942 @item ^-nL^/NAME_CASING=LOWER_CASE^
12943 Names are in lower case
12945 @item ^-nM^/NAME_CASING=MIXED_CASE^
12946 Names are in mixed case
12948 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12949 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12950 Pragma names are lower case
12952 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12953 Pragma names are upper case
12955 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12956 Pragma names are mixed case (this is the default)
12958 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12959 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12960 Use @var{file} as a @emph{dictionary file} that defines
12961 the casing for a set of specified names,
12962 thereby overriding the effect on these names by
12963 any explicit or implicit
12964 ^-n^/NAME_CASING^ switch.
12965 To supply more than one dictionary file,
12966 use ^several @option{-D} switches^a list of files as options^.
12968 @noindent
12969 @option{gnatpp} implicitly uses a @emph{default dictionary file}
12970 to define the casing for the Ada predefined names and
12971 the names declared in the GNAT libraries.
12973 @item ^-D-^/SPECIFIC_CASING^
12974 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
12975 Do not use the default dictionary file;
12976 instead, use the casing
12977 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
12978 dictionary file(s)
12979 @end table
12981 @noindent
12982 The structure of a dictionary file, and details on the conventions
12983 used in the default dictionary file, are defined in @ref{Name Casing}.
12985 The @option{^-D-^/SPECIFIC_CASING^} and
12986 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
12987 compatible.
12989 @node Construct Layout Control
12990 @subsection Construct Layout Control
12991 @cindex Layout control in @command{gnatpp}
12993 @noindent
12994 This group of @command{gnatpp} switches controls the layout of comments and
12995 complex syntactic constructs.  See @ref{Formatting Comments} for details
12996 on their effect.
12998 @table @option
12999 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13000 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13001 All the comments remain unchanged
13003 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13004 GNAT-style comment line indentation (this is the default).
13006 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13007 Reference-manual comment line indentation.
13009 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13010 GNAT-style comment beginning
13012 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13013 Reformat comment blocks
13015 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13016 Keep unchanged special form comments
13018 Reformat comment blocks
13020 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13021 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13022 GNAT-style layout (this is the default)
13024 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13025 Compact layout
13027 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13028 Uncompact layout
13030 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13031 @item ^-N^/NOTABS^
13032 All the VT characters are removed from the comment text. All the HT characters
13033 are expanded with the sequences of space characters to get to the next tab
13034 stops.
13036 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13037 @item ^--no-separate-is^/NO_SEPARATE_IS^
13038 Do not place the keyword @code{is} on a separate line in a subprogram body in
13039 case if the spec occupies more then one line.
13041 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13042 @item ^--separate-label^/SEPARATE_LABEL^
13043 Place statement label(s) on a separate line, with the following statement
13044 on the next line.
13046 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13047 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13048 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13049 keyword @code{then} in IF statements on a separate line.
13051 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13052 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13053 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13054 keyword @code{then} in IF statements on a separate line. This option is
13055 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13057 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13058 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13059 Start each USE clause in a context clause from a separate line.
13061 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13062 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13063 Use a separate line for a loop or block statement name, but do not use an extra
13064 indentation level for the statement itself.
13066 @end table
13068 @ifclear vms
13069 @noindent
13070 The @option{-c1} and @option{-c2} switches are incompatible.
13071 The @option{-c3} and @option{-c4} switches are compatible with each other and
13072 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13073 the other comment formatting switches.
13075 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13076 @end ifclear
13078 @ifset vms
13079 @noindent
13080 For the @option{/COMMENTS_LAYOUT} qualifier:
13081 @itemize @bullet
13082 @item
13083 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13084 @item
13085 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13086 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13087 @end itemize
13089 @noindent
13090 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13091 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13092 @end ifset
13094 @node General Text Layout Control
13095 @subsection General Text Layout Control
13097 @noindent
13098 These switches allow control over line length and indentation.
13100 @table @option
13101 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13102 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13103 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13105 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13106 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13107 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13109 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13110 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13111 Indentation level for continuation lines (relative to the line being
13112 continued), @var{nnn} from 1@dots{}9.
13113 The default
13114 value is one less then the (normal) indentation level, unless the
13115 indentation is set to 1 (in which case the default value for continuation
13116 line indentation is also 1)
13117 @end table
13119 @node Other Formatting Options
13120 @subsection Other Formatting Options
13122 @noindent
13123 These switches control the inclusion of missing end/exit labels, and
13124 the indentation level in @b{case} statements.
13126 @table @option
13127 @item ^-e^/NO_MISSED_LABELS^
13128 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13129 Do not insert missing end/exit labels. An end label is the name of
13130 a construct that may optionally be repeated at the end of the
13131 construct's declaration;
13132 e.g., the names of packages, subprograms, and tasks.
13133 An exit label is the name of a loop that may appear as target
13134 of an exit statement within the loop.
13135 By default, @command{gnatpp} inserts these end/exit labels when
13136 they are absent from the original source. This option suppresses such
13137 insertion, so that the formatted source reflects the original.
13139 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13140 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13141 Insert a Form Feed character after a pragma Page.
13143 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13144 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13145 Do not use an additional indentation level for @b{case} alternatives
13146 and variants if there are @var{nnn} or more (the default
13147 value is 10).
13148 If @var{nnn} is 0, an additional indentation level is
13149 used for @b{case} alternatives and variants regardless of their number.
13150 @end table
13152 @node Setting the Source Search Path
13153 @subsection Setting the Source Search Path
13155 @noindent
13156 To define the search path for the input source file, @command{gnatpp}
13157 uses the same switches as the GNAT compiler, with the same effects.
13159 @table @option
13160 @item ^-I^/SEARCH=^@var{dir}
13161 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13162 The same as the corresponding gcc switch
13164 @item ^-I-^/NOCURRENT_DIRECTORY^
13165 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13166 The same as the corresponding gcc switch
13168 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13169 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13170 The same as the corresponding gcc switch
13172 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13173 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13174 The same as the corresponding gcc switch
13176 @end table
13178 @node Output File Control
13179 @subsection Output File Control
13181 @noindent
13182 By default the output is sent to the file whose name is obtained by appending
13183 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13184 (if the file with this name already exists, it is unconditionally overwritten).
13185 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13186 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13187 as output file.
13188 The output may be redirected by the following switches:
13190 @table @option
13191 @item ^-pipe^/STANDARD_OUTPUT^
13192 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13193 Send the output to @code{Standard_Output}
13195 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13196 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13197 Write the output into @var{output_file}.
13198 If @var{output_file} already exists, @command{gnatpp} terminates without
13199 reading or processing the input file.
13201 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13202 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13203 Write the output into @var{output_file}, overwriting the existing file
13204 (if one is present).
13206 @item ^-r^/REPLACE^
13207 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13208 Replace the input source file with the reformatted output, and copy the
13209 original input source into the file whose name is obtained by appending the
13210 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13211 If a file with this name already exists, @command{gnatpp} terminates without
13212 reading or processing the input file.
13214 @item ^-rf^/OVERRIDING_REPLACE^
13215 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13216 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13217 already exists, it is overwritten.
13219 @item ^-rnb^/REPLACE_NO_BACKUP^
13220 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13221 Replace the input source file with the reformatted output without
13222 creating any backup copy of the input source.
13224 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13225 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13226 Specifies the format of the reformatted output file. The @var{xxx}
13227 ^string specified with the switch^option^ may be either
13228 @itemize @bullet
13229 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13230 @item ``@option{^crlf^CRLF^}''
13231 the same as @option{^crlf^CRLF^}
13232 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13233 @item ``@option{^lf^LF^}''
13234 the same as @option{^unix^UNIX^}
13235 @end itemize
13237 @item ^-W^/RESULT_ENCODING=^@var{e}
13238 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13239 Specify the wide character encoding method used to write the code in the
13240 result file
13241 @var{e} is one of the following:
13243 @itemize @bullet
13245 @item ^h^HEX^
13246 Hex encoding
13248 @item ^u^UPPER^
13249 Upper half encoding
13251 @item ^s^SHIFT_JIS^
13252 Shift/JIS encoding
13254 @item ^e^EUC^
13255 EUC encoding
13257 @item ^8^UTF8^
13258 UTF-8 encoding
13260 @item ^b^BRACKETS^
13261 Brackets encoding (default value)
13262 @end itemize
13264 @end table
13266 @noindent
13267 Options @option{^-pipe^/STANDARD_OUTPUT^},
13268 @option{^-o^/OUTPUT^} and
13269 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13270 contains only one file to reformat.
13271 Option
13272 @option{^--eol^/END_OF_LINE^}
13274 @option{^-W^/RESULT_ENCODING^}
13275 cannot be used together
13276 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13278 @node Other gnatpp Switches
13279 @subsection Other @code{gnatpp} Switches
13281 @noindent
13282 The additional @command{gnatpp} switches are defined in this subsection.
13284 @table @option
13285 @item ^-files @var{filename}^/FILES=@var{filename}^
13286 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13287 Take the argument source files from the specified file. This file should be an
13288 ordinary text file containing file names separated by spaces or
13289 line breaks. You can use this switch more than once in the same call to
13290 @command{gnatpp}. You also can combine this switch with an explicit list of
13291 files.
13293 @item ^-v^/VERBOSE^
13294 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13295 Verbose mode;
13296 @command{gnatpp} generates version information and then
13297 a trace of the actions it takes to produce or obtain the ASIS tree.
13299 @item ^-w^/WARNINGS^
13300 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13301 Warning mode;
13302 @command{gnatpp} generates a warning whenever it cannot provide
13303 a required layout in the result source.
13304 @end table
13306 @node Formatting Rules
13307 @section Formatting Rules
13309 @noindent
13310 The following subsections show how @command{gnatpp} treats ``white space'',
13311 comments, program layout, and name casing.
13312 They provide the detailed descriptions of the switches shown above.
13314 @menu
13315 * White Space and Empty Lines::
13316 * Formatting Comments::
13317 * Construct Layout::
13318 * Name Casing::
13319 @end menu
13321 @node White Space and Empty Lines
13322 @subsection White Space and Empty Lines
13324 @noindent
13325 @command{gnatpp} does not have an option to control space characters.
13326 It will add or remove spaces according to the style illustrated by the
13327 examples in the @cite{Ada Reference Manual}.
13329 The only format effectors
13330 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13331 that will appear in the output file are platform-specific line breaks,
13332 and also format effectors within (but not at the end of) comments.
13333 In particular, each horizontal tab character that is not inside
13334 a comment will be treated as a space and thus will appear in the
13335 output file as zero or more spaces depending on
13336 the reformatting of the line in which it appears.
13337 The only exception is a Form Feed character, which is inserted after a
13338 pragma @code{Page} when @option{-ff} is set.
13340 The output file will contain no lines with trailing ``white space'' (spaces,
13341 format effectors).
13343 Empty lines in the original source are preserved
13344 only if they separate declarations or statements.
13345 In such contexts, a
13346 sequence of two or more empty lines is replaced by exactly one empty line.
13347 Note that a blank line will be removed if it separates two ``comment blocks''
13348 (a comment block is a sequence of whole-line comments).
13349 In order to preserve a visual separation between comment blocks, use an
13350 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13351 Likewise, if for some reason you wish to have a sequence of empty lines,
13352 use a sequence of empty comments instead.
13354 @node Formatting Comments
13355 @subsection Formatting Comments
13357 @noindent
13358 Comments in Ada code are of two kinds:
13359 @itemize @bullet
13360 @item
13361 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13362 ``white space'') on a line
13364 @item
13365 an @emph{end-of-line comment}, which follows some other Ada lexical element
13366 on the same line.
13367 @end itemize
13369 @noindent
13370 The indentation of a whole-line comment is that of either
13371 the preceding or following line in
13372 the formatted source, depending on switch settings as will be described below.
13374 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13375 between the end of the preceding Ada lexical element and the beginning
13376 of the comment as appear in the original source,
13377 unless either the comment has to be split to
13378 satisfy the line length limitation, or else the next line contains a
13379 whole line comment that is considered a continuation of this end-of-line
13380 comment (because it starts at the same position).
13381 In the latter two
13382 cases, the start of the end-of-line comment is moved right to the nearest
13383 multiple of the indentation level.
13384 This may result in a ``line overflow'' (the right-shifted comment extending
13385 beyond the maximum line length), in which case the comment is split as
13386 described below.
13388 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13389 (GNAT-style comment line indentation)
13390 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13391 (reference-manual comment line indentation).
13392 With reference-manual style, a whole-line comment is indented as if it
13393 were a declaration or statement at the same place
13394 (i.e., according to the indentation of the preceding line(s)).
13395 With GNAT style, a whole-line comment that is immediately followed by an
13396 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13397 word @b{begin}, is indented based on the construct that follows it.
13399 For example:
13400 @smallexample @c ada
13401 @cartouche
13402 if A then
13403     null;
13404        -- some comment
13405 else
13406    null;
13407 end if;
13408 @end cartouche
13409 @end smallexample
13411 @noindent
13412 Reference-manual indentation produces:
13414 @smallexample @c ada
13415 @cartouche
13416 if A then
13417    null;
13418    --  some comment
13419 else
13420    null;
13421 end if;
13422 @end cartouche
13423 @end smallexample
13425 @noindent
13426 while GNAT-style indentation produces:
13428 @smallexample @c ada
13429 @cartouche
13430 if A then
13431    null;
13432 --  some comment
13433 else
13434    null;
13435 end if;
13436 @end cartouche
13437 @end smallexample
13439 @noindent
13440 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13441 (GNAT style comment beginning) has the following
13442 effect:
13444 @itemize @bullet
13445 @item
13446 For each whole-line comment that does not end with two hyphens,
13447 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13448 to ensure that there are at least two spaces between these hyphens and the
13449 first non-blank character of the comment.
13450 @end itemize
13452 @noindent
13453 For an end-of-line comment, if in the original source the next line is a
13454 whole-line comment that starts at the same position
13455 as the end-of-line comment,
13456 then the whole-line comment (and all whole-line comments
13457 that follow it and that start at the same position)
13458 will start at this position in the output file.
13460 @noindent
13461 That is, if in the original source we have:
13463 @smallexample @c ada
13464 @cartouche
13465 begin
13466 A := B + C;            --  B must be in the range Low1..High1
13467                        --  C must be in the range Low2..High2
13468              --B+C will be in the range Low1+Low2..High1+High2
13469 X := X + 1;
13470 @end cartouche
13471 @end smallexample
13473 @noindent
13474 Then in the formatted source we get
13476 @smallexample @c ada
13477 @cartouche
13478 begin
13479    A := B + C;            --  B must be in the range Low1..High1
13480                           --  C must be in the range Low2..High2
13481    --  B+C will be in the range Low1+Low2..High1+High2
13482    X := X + 1;
13483 @end cartouche
13484 @end smallexample
13486 @noindent
13487 A comment that exceeds the line length limit will be split.
13488 Unless switch
13489 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13490 the line belongs to a reformattable block, splitting the line generates a
13491 @command{gnatpp} warning.
13492 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13493 comments may be reformatted in typical
13494 word processor style (that is, moving words between lines and putting as
13495 many words in a line as possible).
13497 @noindent
13498 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13499 that has a special format (that is, a character that is neither a letter nor digit
13500 not white space nor line break immediately following the leading @code{--} of
13501 the comment) should be without any change moved from the argument source
13502 into reformatted source. This switch allows to preserve comments that are used
13503 as a special marks in the code (e.g.@: SPARK annotation).
13505 @node Construct Layout
13506 @subsection Construct Layout
13508 @noindent
13509 In several cases the suggested layout in the Ada Reference Manual includes
13510 an extra level of indentation that many programmers prefer to avoid. The
13511 affected cases include:
13513 @itemize @bullet
13515 @item Record type declaration (RM 3.8)
13517 @item Record representation clause (RM 13.5.1)
13519 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13521 @item Block statement in case if a block has a statement identifier (RM 5.6)
13522 @end itemize
13524 @noindent
13525 In compact mode (when GNAT style layout or compact layout is set),
13526 the pretty printer uses one level of indentation instead
13527 of two. This is achieved in the record definition and record representation
13528 clause cases by putting the @code{record} keyword on the same line as the
13529 start of the declaration or representation clause, and in the block and loop
13530 case by putting the block or loop header on the same line as the statement
13531 identifier.
13533 @noindent
13534 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13535 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13536 layout on the one hand, and uncompact layout
13537 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13538 can be illustrated by the following examples:
13540 @iftex
13541 @cartouche
13542 @multitable @columnfractions .5 .5
13543 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13545 @item
13546 @smallexample @c ada
13547 type q is record
13548    a : integer;
13549    b : integer;
13550 end record;
13551 @end smallexample
13552 @tab
13553 @smallexample @c ada
13554 type q is
13555    record
13556       a : integer;
13557       b : integer;
13558    end record;
13559 @end smallexample
13561 @item
13562 @smallexample @c ada
13563 for q use record
13564    a at 0 range  0 .. 31;
13565    b at 4 range  0 .. 31;
13566 end record;
13567 @end smallexample
13568 @tab
13569 @smallexample @c ada
13570 for q use
13571    record
13572       a at 0 range  0 .. 31;
13573       b at 4 range  0 .. 31;
13574    end record;
13575 @end smallexample
13577 @item
13578 @smallexample @c ada
13579 Block : declare
13580    A : Integer := 3;
13581 begin
13582    Proc (A, A);
13583 end Block;
13584 @end smallexample
13585 @tab
13586 @smallexample @c ada
13587 Block :
13588    declare
13589       A : Integer := 3;
13590    begin
13591       Proc (A, A);
13592    end Block;
13593 @end smallexample
13595 @item
13596 @smallexample @c ada
13597 Clear : for J in 1 .. 10 loop
13598    A (J) := 0;
13599 end loop Clear;
13600 @end smallexample
13601 @tab
13602 @smallexample @c ada
13603 Clear :
13604    for J in 1 .. 10 loop
13605       A (J) := 0;
13606    end loop Clear;
13607 @end smallexample
13608 @end multitable
13609 @end cartouche
13610 @end iftex
13612 @ifnottex
13613 @smallexample
13614 @cartouche
13615 GNAT style, compact layout              Uncompact layout
13617 type q is record                        type q is
13618    a : integer;                            record
13619    b : integer;                               a : integer;
13620 end record;                                   b : integer;
13621                                            end record;
13623 for q use record                        for q use
13624    a at 0 range  0 .. 31;                  record
13625    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13626 end record;                                   b at 4 range  0 .. 31;
13627                                            end record;
13629 Block : declare                         Block :
13630    A : Integer := 3;                       declare
13631 begin                                         A : Integer := 3;
13632    Proc (A, A);                            begin
13633 end Block;                                    Proc (A, A);
13634                                            end Block;
13636 Clear : for J in 1 .. 10 loop           Clear :
13637    A (J) := 0;                             for J in 1 .. 10 loop
13638 end loop Clear;                               A (J) := 0;
13639                                            end loop Clear;
13640 @end cartouche
13641 @end smallexample
13642 @end ifnottex
13644 @noindent
13645 A further difference between GNAT style layout and compact layout is that
13646 GNAT style layout inserts empty lines as separation for
13647 compound statements, return statements and bodies.
13649 Note that the layout specified by
13650 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13651 for named block and loop statements overrides the layout defined by these
13652 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13653 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13654 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13656 @node Name Casing
13657 @subsection Name Casing
13659 @noindent
13660 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13661 the same casing as the corresponding defining identifier.
13663 You control the casing for defining occurrences via the
13664 @option{^-n^/NAME_CASING^} switch.
13665 @ifclear vms
13666 With @option{-nD} (``as declared'', which is the default),
13667 @end ifclear
13668 @ifset vms
13669 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13670 @end ifset
13671 defining occurrences appear exactly as in the source file
13672 where they are declared.
13673 The other ^values for this switch^options for this qualifier^ ---
13674 @option{^-nU^UPPER_CASE^},
13675 @option{^-nL^LOWER_CASE^},
13676 @option{^-nM^MIXED_CASE^} ---
13677 result in
13678 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13679 If @command{gnatpp} changes the casing of a defining
13680 occurrence, it analogously changes the casing of all the
13681 usage occurrences of this name.
13683 If the defining occurrence of a name is not in the source compilation unit
13684 currently being processed by @command{gnatpp}, the casing of each reference to
13685 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13686 switch (subject to the dictionary file mechanism described below).
13687 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13688 had affected the
13689 casing for the defining occurrence of the name.
13691 Some names may need to be spelled with casing conventions that are not
13692 covered by the upper-, lower-, and mixed-case transformations.
13693 You can arrange correct casing by placing such names in a
13694 @emph{dictionary file},
13695 and then supplying a @option{^-D^/DICTIONARY^} switch.
13696 The casing of names from dictionary files overrides
13697 any @option{^-n^/NAME_CASING^} switch.
13699 To handle the casing of Ada predefined names and the names from GNAT libraries,
13700 @command{gnatpp} assumes a default dictionary file.
13701 The name of each predefined entity is spelled with the same casing as is used
13702 for the entity in the @cite{Ada Reference Manual}.
13703 The name of each entity in the GNAT libraries is spelled with the same casing
13704 as is used in the declaration of that entity.
13706 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13707 default dictionary file.
13708 Instead, the casing for predefined and GNAT-defined names will be established
13709 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13710 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13711 will appear as just shown,
13712 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13713 To ensure that even such names are rendered in uppercase,
13714 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13715 (or else, less conveniently, place these names in upper case in a dictionary
13716 file).
13718 A dictionary file is
13719 a plain text file; each line in this file can be either a blank line
13720 (containing only space characters and ASCII.HT characters), an Ada comment
13721 line, or the specification of exactly one @emph{casing schema}.
13723 A casing schema is a string that has the following syntax:
13725 @smallexample
13726 @cartouche
13727   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13729   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13730 @end cartouche
13731 @end smallexample
13733 @noindent
13734 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13735 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13737 The casing schema string can be followed by white space and/or an Ada-style
13738 comment; any amount of white space is allowed before the string.
13740 If a dictionary file is passed as
13741 @ifclear vms
13742 the value of a @option{-D@var{file}} switch
13743 @end ifclear
13744 @ifset vms
13745 an option to the @option{/DICTIONARY} qualifier
13746 @end ifset
13747 then for every
13748 simple name and every identifier, @command{gnatpp} checks if the dictionary
13749 defines the casing for the name or for some of its parts (the term ``subword''
13750 is used below to denote the part of a name which is delimited by ``_'' or by
13751 the beginning or end of the word and which does not contain any ``_'' inside):
13753 @itemize @bullet
13754 @item
13755 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13756 the casing defined by the dictionary; no subwords are checked for this word
13758 @item
13759 for every subword @command{gnatpp} checks if the dictionary contains the
13760 corresponding string of the form @code{*@var{simple_identifier}*},
13761 and if it does, the casing of this @var{simple_identifier} is used
13762 for this subword
13764 @item
13765 if the whole name does not contain any ``_'' inside, and if for this name
13766 the dictionary contains two entries - one of the form @var{identifier},
13767 and another - of the form *@var{simple_identifier}*, then the first one
13768 is applied to define the casing of this name
13770 @item
13771 if more than one dictionary file is passed as @command{gnatpp} switches, each
13772 dictionary adds new casing exceptions and overrides all the existing casing
13773 exceptions set by the previous dictionaries
13775 @item
13776 when @command{gnatpp} checks if the word or subword is in the dictionary,
13777 this check is not case sensitive
13778 @end itemize
13780 @noindent
13781 For example, suppose we have the following source to reformat:
13783 @smallexample @c ada
13784 @cartouche
13785 procedure test is
13786    name1 : integer := 1;
13787    name4_name3_name2 : integer := 2;
13788    name2_name3_name4 : Boolean;
13789    name1_var : Float;
13790 begin
13791    name2_name3_name4 := name4_name3_name2 > name1;
13792 end;
13793 @end cartouche
13794 @end smallexample
13796 @noindent
13797 And suppose we have two dictionaries:
13799 @smallexample
13800 @cartouche
13801 @i{dict1:}
13802    NAME1
13803    *NaMe3*
13804    *Name1*
13805 @end cartouche
13807 @cartouche
13808 @i{dict2:}
13809   *NAME3*
13810 @end cartouche
13811 @end smallexample
13813 @noindent
13814 If @command{gnatpp} is called with the following switches:
13816 @smallexample
13817 @ifclear vms
13818 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13819 @end ifclear
13820 @ifset vms
13821 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13822 @end ifset
13823 @end smallexample
13825 @noindent
13826 then we will get the following name casing in the @command{gnatpp} output:
13828 @smallexample @c ada
13829 @cartouche
13830 procedure Test is
13831    NAME1             : Integer := 1;
13832    Name4_NAME3_Name2 : Integer := 2;
13833    Name2_NAME3_Name4 : Boolean;
13834    Name1_Var         : Float;
13835 begin
13836    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13837 end Test;
13838 @end cartouche
13839 @end smallexample
13841 @c *********************************
13842 @node The GNAT Metric Tool gnatmetric
13843 @chapter The GNAT Metric Tool @command{gnatmetric}
13844 @findex gnatmetric
13845 @cindex Metric tool
13847 @noindent
13848 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13849 for computing various program metrics.
13850 It takes an Ada source file as input and generates a file containing the
13851 metrics data as output. Various switches control which
13852 metrics are computed and output.
13854 @command{gnatmetric} generates and uses the ASIS
13855 tree for the input source and thus requires the input to be syntactically and
13856 semantically legal.
13857 If this condition is not met, @command{gnatmetric} will generate
13858 an error message; no metric information for this file will be
13859 computed and reported.
13861 If the compilation unit contained in the input source depends semantically
13862 upon units in files located outside the current directory, you have to provide
13863 the source search path when invoking @command{gnatmetric}.
13864 If it depends semantically upon units that are contained
13865 in files with names that do not follow the GNAT file naming rules, you have to
13866 provide the configuration file describing the corresponding naming scheme (see
13867 the description of the @command{gnatmetric} switches below.)
13868 Alternatively, you may use a project file and invoke @command{gnatmetric}
13869 through the @command{gnat} driver.
13871 The @command{gnatmetric} command has the form
13873 @smallexample
13874 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13875 @c Expanding @ovar macro inline (explanation in macro def comments)
13876 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13877 @end smallexample
13879 @noindent
13880 where
13881 @itemize @bullet
13882 @item
13883 @var{switches} specify the metrics to compute and define the destination for
13884 the output
13886 @item
13887 Each @var{filename} is the name (including the extension) of a source
13888 file to process. ``Wildcards'' are allowed, and
13889 the file name may contain path information.
13890 If no @var{filename} is supplied, then the @var{switches} list must contain
13891 at least one
13892 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13893 Including both a @option{-files} switch and one or more
13894 @var{filename} arguments is permitted.
13896 @item
13897 @samp{@var{gcc_switches}} is a list of switches for
13898 @command{gcc}. They will be passed on to all compiler invocations made by
13899 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13900 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13901 and use the @option{-gnatec} switch to set the configuration file,
13902 use the @option{-gnat05} switch if sources should be compiled in
13903 Ada 2005 mode etc.
13904 @end itemize
13906 @menu
13907 * Switches for gnatmetric::
13908 @end menu
13910 @node Switches for gnatmetric
13911 @section Switches for @command{gnatmetric}
13913 @noindent
13914 The following subsections describe the various switches accepted by
13915 @command{gnatmetric}, organized by category.
13917 @menu
13918 * Output Files Control::
13919 * Disable Metrics For Local Units::
13920 * Specifying a set of metrics to compute::
13921 * Other gnatmetric Switches::
13922 * Generate project-wide metrics::
13923 @end menu
13925 @node Output Files Control
13926 @subsection Output File Control
13927 @cindex Output file control in @command{gnatmetric}
13929 @noindent
13930 @command{gnatmetric} has two output formats. It can generate a
13931 textual (human-readable) form, and also XML. By default only textual
13932 output is generated.
13934 When generating the output in textual form, @command{gnatmetric} creates
13935 for each Ada source file a corresponding text file
13936 containing the computed metrics, except for the case when the set of metrics
13937 specified by gnatmetric parameters consists only of metrics that are computed
13938 for the whole set of analyzed sources, but not for each Ada source.
13939 By default, this file is placed in the same directory as where the source
13940 file is located, and its name is obtained
13941 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13942 input file.
13944 All the output information generated in XML format is placed in a single
13945 file. By default this file is placed in the current directory and has the
13946 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13948 Some of the computed metrics are summed over the units passed to
13949 @command{gnatmetric}; for example, the total number of lines of code.
13950 By default this information is sent to @file{stdout}, but a file
13951 can be specified with the @option{-og} switch.
13953 The following switches control the @command{gnatmetric} output:
13955 @table @option
13956 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13957 @item ^-x^/XML^
13958 Generate the XML output
13960 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13961 @item ^-xs^/XSD^
13962 Generate the XML output and the XML schema file that describes the structure
13963 of the XML metric report, this schema is assigned to the XML file. The schema
13964 file has the same name as the XML output file with @file{.xml} suffix replaced
13965 with @file{.xsd}
13967 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
13968 @item ^-nt^/NO_TEXT^
13969 Do not generate the output in text form (implies @option{^-x^/XML^})
13971 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
13972 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
13973 Put text files with detailed metrics into @var{output_dir}
13975 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
13976 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
13977 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
13978 in the name of the output file.
13980 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
13981 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
13982 Put global metrics into @var{file_name}
13984 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
13985 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
13986 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
13988 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
13989 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
13990 Use ``short'' source file names in the output.  (The @command{gnatmetric}
13991 output includes the name(s) of the Ada source file(s) from which the metrics
13992 are computed.  By default each name includes the absolute path. The
13993 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
13994 to exclude all directory information from the file names that are output.)
13996 @end table
13998 @node Disable Metrics For Local Units
13999 @subsection Disable Metrics For Local Units
14000 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14002 @noindent
14003 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14004 one compilation
14005 unit per one source file. It computes line metrics for the whole source
14006 file, and it also computes syntax
14007 and complexity metrics for the file's outermost unit.
14009 By default, @command{gnatmetric} will also compute all metrics for certain
14010 kinds of locally declared program units:
14012 @itemize @bullet
14013 @item
14014 subprogram (and generic subprogram) bodies;
14016 @item
14017 package (and generic package) specs and bodies;
14019 @item
14020 task object and type specifications and bodies;
14022 @item
14023 protected object and type specifications and bodies.
14024 @end itemize
14026 @noindent
14027 These kinds of entities will be referred to as
14028 @emph{eligible local program units}, or simply @emph{eligible local units},
14029 @cindex Eligible local unit (for @command{gnatmetric})
14030 in the discussion below.
14032 Note that a subprogram declaration, generic instantiation,
14033 or renaming declaration only receives metrics
14034 computation when it appear as the outermost entity
14035 in a source file.
14037 Suppression of metrics computation for eligible local units can be
14038 obtained via the following switch:
14040 @table @option
14041 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14042 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14043 Do not compute detailed metrics for eligible local program units
14045 @end table
14047 @node Specifying a set of metrics to compute
14048 @subsection Specifying a set of metrics to compute
14050 @noindent
14051 By default all the metrics are computed and reported. The switches
14052 described in this subsection allow you to control, on an individual
14053 basis, whether metrics are computed and
14054 reported. If at least one positive metric
14055 switch is specified (that is, a switch that defines that a given
14056 metric or set of metrics is to be computed), then only
14057 explicitly specified metrics are reported.
14059 @menu
14060 * Line Metrics Control::
14061 * Syntax Metrics Control::
14062 * Complexity Metrics Control::
14063 * Object-Oriented Metrics Control::
14064 @end menu
14066 @node Line Metrics Control
14067 @subsubsection Line Metrics Control
14068 @cindex Line metrics control in @command{gnatmetric}
14070 @noindent
14071 For any (legal) source file, and for each of its
14072 eligible local program units, @command{gnatmetric} computes the following
14073 metrics:
14075 @itemize @bullet
14076 @item
14077 the total number of lines;
14079 @item
14080 the total number of code lines (i.e., non-blank lines that are not comments)
14082 @item
14083 the number of comment lines
14085 @item
14086 the number of code lines containing end-of-line comments;
14088 @item
14089 the comment percentage: the ratio between the number of lines that contain
14090 comments and the number of all non-blank lines, expressed as a percentage;
14092 @item
14093 the number of empty lines and lines containing only space characters and/or
14094 format effectors (blank lines)
14096 @item
14097 the average number of code lines in subprogram bodies, task bodies, entry
14098 bodies and statement sequences in package bodies (this metric is only computed
14099 across the whole set of the analyzed units)
14101 @end itemize
14103 @noindent
14104 @command{gnatmetric} sums the values of the line metrics for all the
14105 files being processed and then generates the cumulative results. The tool
14106 also computes for all the files being processed the average number of code
14107 lines in bodies.
14109 You can use the following switches to select the specific line metrics
14110 to be computed and reported.
14112 @table @option
14113 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14115 @ifclear vms
14116 @cindex @option{--no-lines@var{x}}
14117 @end ifclear
14119 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14120 Report all the line metrics
14122 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14123 Do not report any of line metrics
14125 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14126 Report the number of all lines
14128 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14129 Do not report the number of all lines
14131 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14132 Report the number of code lines
14134 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14135 Do not report the number of code lines
14137 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14138 Report the number of comment lines
14140 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14141 Do not report the number of comment lines
14143 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14144 Report the number of code lines containing
14145 end-of-line comments
14147 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14148 Do not report the number of code lines containing
14149 end-of-line comments
14151 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14152 Report the comment percentage in the program text
14154 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14155 Do not report the comment percentage in the program text
14157 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14158 Report the number of blank lines
14160 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14161 Do not report the number of blank lines
14163 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14164 Report the average number of code lines in subprogram bodies, task bodies,
14165 entry bodies and statement sequences in package bodies. The metric is computed
14166 and reported for the whole set of processed Ada sources only.
14168 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14169 Do not report the average number of code lines in subprogram bodies,
14170 task bodies, entry bodies and statement sequences in package bodies.
14172 @end table
14174 @node Syntax Metrics Control
14175 @subsubsection Syntax Metrics Control
14176 @cindex Syntax metrics control in @command{gnatmetric}
14178 @noindent
14179 @command{gnatmetric} computes various syntactic metrics for the
14180 outermost unit and for each eligible local unit:
14182 @table @emph
14183 @item LSLOC (``Logical Source Lines Of Code'')
14184 The total number of declarations and the total number of statements
14186 @item Maximal static nesting level of inner program units
14187 According to
14188 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14189 package, a task unit, a protected unit, a
14190 protected entry, a generic unit, or an explicitly declared subprogram other
14191 than an enumeration literal.''
14193 @item Maximal nesting level of composite syntactic constructs
14194 This corresponds to the notion of the
14195 maximum nesting level in the GNAT built-in style checks
14196 (@pxref{Style Checking})
14197 @end table
14199 @noindent
14200 For the outermost unit in the file, @command{gnatmetric} additionally computes
14201 the following metrics:
14203 @table @emph
14204 @item Public subprograms
14205 This metric is computed for package specs. It is the
14206 number of subprograms and generic subprograms declared in the visible
14207 part (including the visible part of nested packages, protected objects, and
14208 protected types).
14210 @item All subprograms
14211 This metric is computed for bodies and subunits. The
14212 metric is equal to a total number of subprogram bodies in the compilation
14213 unit.
14214 Neither generic instantiations nor renamings-as-a-body nor body stubs
14215 are counted. Any subprogram body is counted, independently of its nesting
14216 level and enclosing constructs. Generic bodies and bodies of protected
14217 subprograms are counted in the same way as ``usual'' subprogram bodies.
14219 @item Public types
14220 This metric is computed for package specs and
14221 generic package declarations. It is the total number of types
14222 that can be referenced from outside this compilation unit, plus the
14223 number of types from all the visible parts of all the visible generic
14224 packages. Generic formal types are not counted.  Only types, not subtypes,
14225 are included.
14227 @noindent
14228 Along with the total number of public types, the following
14229 types are counted and reported separately:
14231 @itemize @bullet
14232 @item
14233 Abstract types
14235 @item
14236 Root tagged types (abstract, non-abstract, private, non-private). Type
14237 extensions are @emph{not} counted
14239 @item
14240 Private types (including private extensions)
14242 @item
14243 Task types
14245 @item
14246 Protected types
14248 @end itemize
14250 @item All types
14251 This metric is computed for any compilation unit. It is equal to the total
14252 number of the declarations of different types given in the compilation unit.
14253 The private and the corresponding full type declaration are counted as one
14254 type declaration. Incomplete type declarations and generic formal types
14255 are not counted.
14256 No distinction is made among different kinds of types (abstract,
14257 private etc.); the total number of types is computed and reported.
14259 @end table
14261 @noindent
14262 By default, all the syntax metrics are computed and reported. You can use the
14263 following switches to select specific syntax metrics.
14265 @table @option
14267 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14269 @ifclear vms
14270 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14271 @end ifclear
14273 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14274 Report all the syntax metrics
14276 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14277 Do not report any of syntax metrics
14279 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14280 Report the total number of declarations
14282 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14283 Do not report the total number of declarations
14285 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14286 Report the total number of statements
14288 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14289 Do not report the total number of statements
14291 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14292 Report the number of public subprograms in a compilation unit
14294 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14295 Do not report the number of public subprograms in a compilation unit
14297 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14298 Report the number of all the subprograms in a compilation unit
14300 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14301 Do not report the number of all the subprograms in a compilation unit
14303 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14304 Report the number of public types in a compilation unit
14306 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14307 Do not report the number of public types in a compilation unit
14309 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14310 Report the number of all the types in a compilation unit
14312 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14313 Do not report the number of all the types in a compilation unit
14315 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14316 Report the maximal program unit nesting level
14318 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14319 Do not report the maximal program unit nesting level
14321 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14322 Report the maximal construct nesting level
14324 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14325 Do not report the maximal construct nesting level
14327 @end table
14329 @node Complexity Metrics Control
14330 @subsubsection Complexity Metrics Control
14331 @cindex Complexity metrics control in @command{gnatmetric}
14333 @noindent
14334 For a program unit that is an executable body (a subprogram body (including
14335 generic bodies), task body, entry body or a package body containing
14336 its own statement sequence) @command{gnatmetric} computes the following
14337 complexity metrics:
14339 @itemize @bullet
14340 @item
14341 McCabe cyclomatic complexity;
14343 @item
14344 McCabe essential complexity;
14346 @item
14347 maximal loop nesting level
14349 @end itemize
14351 @noindent
14352 The McCabe complexity metrics are defined
14353 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
14355 According to McCabe, both control statements and short-circuit control forms
14356 should be taken into account when computing cyclomatic complexity. For each
14357 body, we compute three metric values:
14359 @itemize @bullet
14360 @item
14361 the complexity introduced by control
14362 statements only, without taking into account short-circuit forms,
14364 @item
14365 the complexity introduced by short-circuit control forms only, and
14367 @item
14368 the total
14369 cyclomatic complexity, which is the sum of these two values.
14370 @end itemize
14372 @noindent
14373 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14374 the code in the exception handlers and in all the nested program units.
14376 By default, all the complexity metrics are computed and reported.
14377 For more fine-grained control you can use
14378 the following switches:
14380 @table @option
14381 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14383 @ifclear vms
14384 @cindex @option{--no-complexity@var{x}}
14385 @end ifclear
14387 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14388 Report all the complexity metrics
14390 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14391 Do not report any of complexity metrics
14393 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14394 Report the McCabe Cyclomatic Complexity
14396 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14397 Do not report the McCabe Cyclomatic Complexity
14399 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14400 Report the Essential Complexity
14402 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14403 Do not report the Essential Complexity
14405 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14406 Report maximal loop nesting level
14408 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14409 Do not report maximal loop nesting level
14411 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14412 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14413 task bodies, entry bodies and statement sequences in package bodies.
14414 The metric is computed and reported for whole set of processed Ada sources
14415 only.
14417 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14418 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14419 bodies, task bodies, entry bodies and statement sequences in package bodies
14421 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14422 @item ^-ne^/NO_EXITS_AS_GOTOS^
14423 Do not consider @code{exit} statements as @code{goto}s when
14424 computing Essential Complexity
14426 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14427 Report the extra exit points for subprogram bodies. As an exit point, this
14428 metric counts @code{return} statements and raise statements in case when the
14429 raised exception is not handled in the same body. In case of a function this
14430 metric subtracts 1 from the number of exit points, because a function body
14431 must contain at least one @code{return} statement.
14433 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14434 Do not report the extra exit points for subprogram bodies
14435 @end table
14438 @node Object-Oriented Metrics Control
14439 @subsubsection Object-Oriented Metrics Control
14440 @cindex Object-Oriented metrics control in @command{gnatmetric}
14442 @noindent
14443 @cindex Coupling metrics (in in @command{gnatmetric})
14444 Coupling metrics are object-oriented metrics that measure the
14445 dependencies between a given class (or a group of classes) and the
14446 ``external world'' (that is, the other classes in the program). In this
14447 subsection the term ``class'' is used in its
14448 traditional object-oriented programming sense
14449 (an instantiable module that contains data and/or method members).
14450 A @emph{category} (of classes)
14451 is a group of closely related classes that are reused and/or
14452 modified together.
14454 A class @code{K}'s @emph{efferent coupling} is the number of classes
14455 that @code{K} depends upon.
14456 A category's efferent coupling is the number of classes outside the
14457 category that the classes inside the category depend upon.
14459 A class @code{K}'s @emph{afferent coupling} is the number of classes
14460 that depend upon @code{K}.
14461 A category's afferent coupling is the number of classes outside the
14462 category that depend on classes belonging to the category.
14464 Ada's implementation of the object-oriented paradigm does not use the
14465 traditional class notion, so the definition of the coupling
14466 metrics for Ada maps the class and class category notions
14467 onto Ada constructs.
14469 For the coupling metrics, several kinds of modules -- a library package,
14470 a library generic package, and a library generic package instantiation --
14471 that define a tagged type or an interface type are
14472 considered to be a class. A category consists of a library package (or
14473 a library generic package) that defines a tagged or an interface type,
14474 together with all its descendant (generic) packages that define tagged
14475 or interface types. For any package counted as a class,
14476 its body and subunits (if any) are considered
14477 together with its spec when counting the dependencies, and coupling
14478 metrics are reported for spec units only. For dependencies
14479 between classes, the Ada semantic dependencies are considered.
14480 For coupling metrics, only dependencies on units that are considered as
14481 classes, are considered.
14483 When computing coupling metrics, @command{gnatmetric} counts only
14484 dependencies between units that are arguments of the gnatmetric call.
14485 Coupling metrics are program-wide (or project-wide) metrics, so to
14486 get a valid result, you should call @command{gnatmetric} for
14487 the whole set of sources that make up your program. It can be done
14488 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14489 option (see See @ref{The GNAT Driver and Project Files} for details.
14491 By default, all the coupling metrics are disabled. You can use the following
14492 switches to specify the coupling metrics to be computed and reported:
14494 @table @option
14496 @ifclear vms
14497 @cindex @option{--package@var{x}} (@command{gnatmetric})
14498 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14499 @cindex @option{--category@var{x}} (@command{gnatmetric})
14500 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14501 @end ifclear
14503 @ifset vms
14504 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14505 @end ifset
14507 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14508 Report all the coupling metrics
14510 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14511 Do not report any of  metrics
14513 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14514 Report package efferent coupling
14516 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14517 Do not report package efferent coupling
14519 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14520 Report package afferent coupling
14522 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14523 Do not report package afferent coupling
14525 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14526 Report category efferent coupling
14528 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14529 Do not report category efferent coupling
14531 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14532 Report category afferent coupling
14534 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14535 Do not report category afferent coupling
14537 @end table
14539 @node Other gnatmetric Switches
14540 @subsection Other @code{gnatmetric} Switches
14542 @noindent
14543 Additional @command{gnatmetric} switches are as follows:
14545 @table @option
14546 @item ^-files @var{filename}^/FILES=@var{filename}^
14547 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14548 Take the argument source files from the specified file. This file should be an
14549 ordinary text file containing file names separated by spaces or
14550 line breaks. You can use this switch more than once in the same call to
14551 @command{gnatmetric}. You also can combine this switch with
14552 an explicit list of files.
14554 @item ^-v^/VERBOSE^
14555 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14556 Verbose mode;
14557 @command{gnatmetric} generates version information and then
14558 a trace of sources being processed.
14560 @item ^-dv^/DEBUG_OUTPUT^
14561 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
14562 Debug mode;
14563 @command{gnatmetric} generates various messages useful to understand what
14564 happens during the metrics computation
14566 @item ^-q^/QUIET^
14567 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14568 Quiet mode.
14569 @end table
14571 @node Generate project-wide metrics
14572 @subsection Generate project-wide metrics
14574 In order to compute metrics on all units of a given project, you can use
14575 the @command{gnat} driver along with the @option{-P} option:
14576 @smallexample
14577    gnat metric -Pproj
14578 @end smallexample
14580 @noindent
14581 If the project @code{proj} depends upon other projects, you can compute
14582 the metrics on the project closure using the @option{-U} option:
14583 @smallexample
14584    gnat metric -Pproj -U
14585 @end smallexample
14587 @noindent
14588 Finally, if not all the units are relevant to a particular main
14589 program in the project closure, you can generate metrics for the set
14590 of units needed to create a given main program (unit closure) using
14591 the @option{-U} option followed by the name of the main unit:
14592 @smallexample
14593    gnat metric -Pproj -U main
14594 @end smallexample
14597 @c ***********************************
14598 @node File Name Krunching Using gnatkr
14599 @chapter File Name Krunching Using @code{gnatkr}
14600 @findex gnatkr
14602 @noindent
14603 This chapter discusses the method used by the compiler to shorten
14604 the default file names chosen for Ada units so that they do not
14605 exceed the maximum length permitted. It also describes the
14606 @code{gnatkr} utility that can be used to determine the result of
14607 applying this shortening.
14608 @menu
14609 * About gnatkr::
14610 * Using gnatkr::
14611 * Krunching Method::
14612 * Examples of gnatkr Usage::
14613 @end menu
14615 @node About gnatkr
14616 @section About @code{gnatkr}
14618 @noindent
14619 The default file naming rule in GNAT
14620 is that the file name must be derived from
14621 the unit name. The exact default rule is as follows:
14622 @itemize @bullet
14623 @item
14624 Take the unit name and replace all dots by hyphens.
14625 @item
14626 If such a replacement occurs in the
14627 second character position of a name, and the first character is
14628 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14629 then replace the dot by the character
14630 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14631 instead of a minus.
14632 @end itemize
14633 The reason for this exception is to avoid clashes
14634 with the standard names for children of System, Ada, Interfaces,
14635 and GNAT, which use the prefixes
14636 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14637 respectively.
14639 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14640 switch of the compiler activates a ``krunching''
14641 circuit that limits file names to nn characters (where nn is a decimal
14642 integer). For example, using OpenVMS,
14643 where the maximum file name length is
14644 39, the value of nn is usually set to 39, but if you want to generate
14645 a set of files that would be usable if ported to a system with some
14646 different maximum file length, then a different value can be specified.
14647 The default value of 39 for OpenVMS need not be specified.
14649 The @code{gnatkr} utility can be used to determine the krunched name for
14650 a given file, when krunched to a specified maximum length.
14652 @node Using gnatkr
14653 @section Using @code{gnatkr}
14655 @noindent
14656 The @code{gnatkr} command has the form
14658 @ifclear vms
14659 @smallexample
14660 @c $ gnatkr @var{name} @ovar{length}
14661 @c Expanding @ovar macro inline (explanation in macro def comments)
14662 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14663 @end smallexample
14664 @end ifclear
14666 @ifset vms
14667 @smallexample
14668 $ gnatkr @var{name} /COUNT=nn
14669 @end smallexample
14670 @end ifset
14672 @noindent
14673 @var{name} is the uncrunched file name, derived from the name of the unit
14674 in the standard manner described in the previous section (i.e., in particular
14675 all dots are replaced by hyphens). The file name may or may not have an
14676 extension (defined as a suffix of the form period followed by arbitrary
14677 characters other than period). If an extension is present then it will
14678 be preserved in the output. For example, when krunching @file{hellofile.ads}
14679 to eight characters, the result will be hellofil.ads.
14681 Note: for compatibility with previous versions of @code{gnatkr} dots may
14682 appear in the name instead of hyphens, but the last dot will always be
14683 taken as the start of an extension. So if @code{gnatkr} is given an argument
14684 such as @file{Hello.World.adb} it will be treated exactly as if the first
14685 period had been a hyphen, and for example krunching to eight characters
14686 gives the result @file{hellworl.adb}.
14688 Note that the result is always all lower case (except on OpenVMS where it is
14689 all upper case). Characters of the other case are folded as required.
14691 @var{length} represents the length of the krunched name. The default
14692 when no argument is given is ^8^39^ characters. A length of zero stands for
14693 unlimited, in other words do not chop except for system files where the
14694 implied crunching length is always eight characters.
14696 @noindent
14697 The output is the krunched name. The output has an extension only if the
14698 original argument was a file name with an extension.
14700 @node Krunching Method
14701 @section Krunching Method
14703 @noindent
14704 The initial file name is determined by the name of the unit that the file
14705 contains. The name is formed by taking the full expanded name of the
14706 unit and replacing the separating dots with hyphens and
14707 using ^lowercase^uppercase^
14708 for all letters, except that a hyphen in the second character position is
14709 replaced by a ^tilde^dollar sign^ if the first character is
14710 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14711 The extension is @code{.ads} for a
14712 spec and @code{.adb} for a body.
14713 Krunching does not affect the extension, but the file name is shortened to
14714 the specified length by following these rules:
14716 @itemize @bullet
14717 @item
14718 The name is divided into segments separated by hyphens, tildes or
14719 underscores and all hyphens, tildes, and underscores are
14720 eliminated. If this leaves the name short enough, we are done.
14722 @item
14723 If the name is too long, the longest segment is located (left-most
14724 if there are two of equal length), and shortened by dropping
14725 its last character. This is repeated until the name is short enough.
14727 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14728 to fit the name into 8 characters as required by some operating systems.
14730 @smallexample
14731 our-strings-wide_fixed 22
14732 our strings wide fixed 19
14733 our string  wide fixed 18
14734 our strin   wide fixed 17
14735 our stri    wide fixed 16
14736 our stri    wide fixe  15
14737 our str     wide fixe  14
14738 our str     wid  fixe  13
14739 our str     wid  fix   12
14740 ou  str     wid  fix   11
14741 ou  st      wid  fix   10
14742 ou  st      wi   fix   9
14743 ou  st      wi   fi    8
14744 Final file name: oustwifi.adb
14745 @end smallexample
14747 @item
14748 The file names for all predefined units are always krunched to eight
14749 characters. The krunching of these predefined units uses the following
14750 special prefix replacements:
14752 @table @file
14753 @item ada-
14754 replaced by @file{^a^A^-}
14756 @item gnat-
14757 replaced by @file{^g^G^-}
14759 @item interfaces-
14760 replaced by @file{^i^I^-}
14762 @item system-
14763 replaced by @file{^s^S^-}
14764 @end table
14766 These system files have a hyphen in the second character position. That
14767 is why normal user files replace such a character with a
14768 ^tilde^dollar sign^, to
14769 avoid confusion with system file names.
14771 As an example of this special rule, consider
14772 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14774 @smallexample
14775 ada-strings-wide_fixed 22
14776 a-  strings wide fixed 18
14777 a-  string  wide fixed 17
14778 a-  strin   wide fixed 16
14779 a-  stri    wide fixed 15
14780 a-  stri    wide fixe  14
14781 a-  str     wide fixe  13
14782 a-  str     wid  fixe  12
14783 a-  str     wid  fix   11
14784 a-  st      wid  fix   10
14785 a-  st      wi   fix   9
14786 a-  st      wi   fi    8
14787 Final file name: a-stwifi.adb
14788 @end smallexample
14789 @end itemize
14791 Of course no file shortening algorithm can guarantee uniqueness over all
14792 possible unit names, and if file name krunching is used then it is your
14793 responsibility to ensure that no name clashes occur. The utility
14794 program @code{gnatkr} is supplied for conveniently determining the
14795 krunched name of a file.
14797 @node Examples of gnatkr Usage
14798 @section Examples of @code{gnatkr} Usage
14800 @smallexample
14801 @iftex
14802 @leftskip=0cm
14803 @end iftex
14804 @ifclear vms
14805 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14806 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14807 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14808 $ gnatkr grandparent-parent-child     --> grparchi
14809 @end ifclear
14810 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14811 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14812 @end smallexample
14814 @node Preprocessing Using gnatprep
14815 @chapter Preprocessing Using @code{gnatprep}
14816 @findex gnatprep
14818 @noindent
14819 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14820 preprocessing.
14821 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14822 special GNAT features.
14823 For further discussion of conditional compilation in general, see
14824 @ref{Conditional Compilation}.
14826 @menu
14827 * Preprocessing Symbols::
14828 * Using gnatprep::
14829 * Switches for gnatprep::
14830 * Form of Definitions File::
14831 * Form of Input Text for gnatprep::
14832 @end menu
14834 @node Preprocessing Symbols
14835 @section Preprocessing Symbols
14837 @noindent
14838 Preprocessing symbols are defined in definition files and referred to in
14839 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14840 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14841 all characters need to be in the ASCII set (no accented letters).
14843 @node Using gnatprep
14844 @section Using @code{gnatprep}
14846 @noindent
14847 To call @code{gnatprep} use
14849 @smallexample
14850 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14851 @c Expanding @ovar macro inline (explanation in macro def comments)
14852 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14853 @end smallexample
14855 @noindent
14856 where
14857 @table @var
14858 @item switches
14859 is an optional sequence of switches as described in the next section.
14861 @item infile
14862 is the full name of the input file, which is an Ada source
14863 file containing preprocessor directives.
14865 @item outfile
14866 is the full name of the output file, which is an Ada source
14867 in standard Ada form. When used with GNAT, this file name will
14868 normally have an ads or adb suffix.
14870 @item deffile
14871 is the full name of a text file containing definitions of
14872 preprocessing symbols to be referenced by the preprocessor. This argument is
14873 optional, and can be replaced by the use of the @option{-D} switch.
14875 @end table
14877 @node Switches for gnatprep
14878 @section Switches for @code{gnatprep}
14880 @table @option
14881 @c !sort!
14883 @item ^-b^/BLANK_LINES^
14884 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14885 Causes both preprocessor lines and the lines deleted by
14886 preprocessing to be replaced by blank lines in the output source file,
14887 preserving line numbers in the output file.
14889 @item ^-c^/COMMENTS^
14890 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14891 Causes both preprocessor lines and the lines deleted
14892 by preprocessing to be retained in the output source as comments marked
14893 with the special string @code{"--! "}. This option will result in line numbers
14894 being preserved in the output file.
14896 @item ^-C^/REPLACE_IN_COMMENTS^
14897 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14898 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14899 If this option is specified, then comments are scanned and any $symbol
14900 substitutions performed as in program text. This is particularly useful
14901 when structured comments are used (e.g., when writing programs in the
14902 SPARK dialect of Ada). Note that this switch is not available when
14903 doing integrated preprocessing (it would be useless in this context
14904 since comments are ignored by the compiler in any case).
14906 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14907 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14908 Defines a new preprocessing symbol, associated with value. If no value is given
14909 on the command line, then symbol is considered to be @code{True}. This switch
14910 can be used in place of a definition file.
14912 @ifset vms
14913 @item /REMOVE
14914 @cindex @option{/REMOVE} (@command{gnatprep})
14915 This is the default setting which causes lines deleted by preprocessing
14916 to be entirely removed from the output file.
14917 @end ifset
14919 @item ^-r^/REFERENCE^
14920 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14921 Causes a @code{Source_Reference} pragma to be generated that
14922 references the original input file, so that error messages will use
14923 the file name of this original file. The use of this switch implies
14924 that preprocessor lines are not to be removed from the file, so its
14925 use will force @option{^-b^/BLANK_LINES^} mode if
14926 @option{^-c^/COMMENTS^}
14927 has not been specified explicitly.
14929 Note that if the file to be preprocessed contains multiple units, then
14930 it will be necessary to @code{gnatchop} the output file from
14931 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14932 in the preprocessed file, it will be respected by
14933 @code{gnatchop ^-r^/REFERENCE^}
14934 so that the final chopped files will correctly refer to the original
14935 input source file for @code{gnatprep}.
14937 @item ^-s^/SYMBOLS^
14938 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
14939 Causes a sorted list of symbol names and values to be
14940 listed on the standard output file.
14942 @item ^-u^/UNDEFINED^
14943 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
14944 Causes undefined symbols to be treated as having the value FALSE in the context
14945 of a preprocessor test. In the absence of this option, an undefined symbol in
14946 a @code{#if} or @code{#elsif} test will be treated as an error.
14948 @end table
14950 @ifclear vms
14951 @noindent
14952 Note: if neither @option{-b} nor @option{-c} is present,
14953 then preprocessor lines and
14954 deleted lines are completely removed from the output, unless -r is
14955 specified, in which case -b is assumed.
14956 @end ifclear
14958 @node Form of Definitions File
14959 @section Form of Definitions File
14961 @noindent
14962 The definitions file contains lines of the form
14964 @smallexample
14965 symbol := value
14966 @end smallexample
14968 @noindent
14969 where symbol is a preprocessing symbol, and value is one of the following:
14971 @itemize @bullet
14972 @item
14973 Empty, corresponding to a null substitution
14974 @item
14975 A string literal using normal Ada syntax
14976 @item
14977 Any sequence of characters from the set
14978 (letters, digits, period, underline).
14979 @end itemize
14981 @noindent
14982 Comment lines may also appear in the definitions file, starting with
14983 the usual @code{--},
14984 and comments may be added to the definitions lines.
14986 @node Form of Input Text for gnatprep
14987 @section Form of Input Text for @code{gnatprep}
14989 @noindent
14990 The input text may contain preprocessor conditional inclusion lines,
14991 as well as general symbol substitution sequences.
14993 The preprocessor conditional inclusion commands have the form
14995 @smallexample
14996 @group
14997 @cartouche
14998 #if @i{expression} @r{[}then@r{]}
14999    lines
15000 #elsif @i{expression} @r{[}then@r{]}
15001    lines
15002 #elsif @i{expression} @r{[}then@r{]}
15003    lines
15004 @dots{}
15005 #else
15006    lines
15007 #end if;
15008 @end cartouche
15009 @end group
15010 @end smallexample
15012 @noindent
15013 In this example, @i{expression} is defined by the following grammar:
15014 @smallexample
15015 @i{expression} ::=  <symbol>
15016 @i{expression} ::=  <symbol> = "<value>"
15017 @i{expression} ::=  <symbol> = <symbol>
15018 @i{expression} ::=  <symbol> 'Defined
15019 @i{expression} ::=  not @i{expression}
15020 @i{expression} ::=  @i{expression} and @i{expression}
15021 @i{expression} ::=  @i{expression} or @i{expression}
15022 @i{expression} ::=  @i{expression} and then @i{expression}
15023 @i{expression} ::=  @i{expression} or else @i{expression}
15024 @i{expression} ::=  ( @i{expression} )
15025 @end smallexample
15027 The following restriction exists: it is not allowed to have "and" or "or"
15028 following "not" in the same expression without parentheses. For example, this
15029 is not allowed:
15031 @smallexample
15032    not X or Y
15033 @end smallexample
15035 This should be one of the following:
15037 @smallexample
15038    (not X) or Y
15039    not (X or Y)
15040 @end smallexample
15042 @noindent
15043 For the first test (@i{expression} ::= <symbol>) the symbol must have
15044 either the value true or false, that is to say the right-hand of the
15045 symbol definition must be one of the (case-insensitive) literals
15046 @code{True} or @code{False}. If the value is true, then the
15047 corresponding lines are included, and if the value is false, they are
15048 excluded.
15050 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15051 the symbol has been defined in the definition file or by a @option{-D}
15052 switch on the command line. Otherwise, the test is false.
15054 The equality tests are case insensitive, as are all the preprocessor lines.
15056 If the symbol referenced is not defined in the symbol definitions file,
15057 then the effect depends on whether or not switch @option{-u}
15058 is specified. If so, then the symbol is treated as if it had the value
15059 false and the test fails. If this switch is not specified, then
15060 it is an error to reference an undefined symbol. It is also an error to
15061 reference a symbol that is defined with a value other than @code{True}
15062 or @code{False}.
15064 The use of the @code{not} operator inverts the sense of this logical test.
15065 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15066 operators, without parentheses. For example, "if not X or Y then" is not
15067 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15069 The @code{then} keyword is optional as shown
15071 The @code{#} must be the first non-blank character on a line, but
15072 otherwise the format is free form. Spaces or tabs may appear between
15073 the @code{#} and the keyword. The keywords and the symbols are case
15074 insensitive as in normal Ada code. Comments may be used on a
15075 preprocessor line, but other than that, no other tokens may appear on a
15076 preprocessor line. Any number of @code{elsif} clauses can be present,
15077 including none at all. The @code{else} is optional, as in Ada.
15079 The @code{#} marking the start of a preprocessor line must be the first
15080 non-blank character on the line, i.e., it must be preceded only by
15081 spaces or horizontal tabs.
15083 Symbol substitution outside of preprocessor lines is obtained by using
15084 the sequence
15086 @smallexample
15087 $symbol
15088 @end smallexample
15090 @noindent
15091 anywhere within a source line, except in a comment or within a
15092 string literal. The identifier
15093 following the @code{$} must match one of the symbols defined in the symbol
15094 definition file, and the result is to substitute the value of the
15095 symbol in place of @code{$symbol} in the output file.
15097 Note that although the substitution of strings within a string literal
15098 is not possible, it is possible to have a symbol whose defined value is
15099 a string literal. So instead of setting XYZ to @code{hello} and writing:
15101 @smallexample
15102 Header : String := "$XYZ";
15103 @end smallexample
15105 @noindent
15106 you should set XYZ to @code{"hello"} and write:
15108 @smallexample
15109 Header : String := $XYZ;
15110 @end smallexample
15112 @noindent
15113 and then the substitution will occur as desired.
15115 @node The GNAT Library Browser gnatls
15116 @chapter The GNAT Library Browser @code{gnatls}
15117 @findex gnatls
15118 @cindex Library browser
15120 @noindent
15121 @code{gnatls} is a tool that outputs information about compiled
15122 units. It gives the relationship between objects, unit names and source
15123 files. It can also be used to check the source dependencies of a unit
15124 as well as various characteristics.
15126 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15127 driver (see @ref{The GNAT Driver and Project Files}).
15129 @menu
15130 * Running gnatls::
15131 * Switches for gnatls::
15132 * Examples of gnatls Usage::
15133 @end menu
15135 @node Running gnatls
15136 @section Running @code{gnatls}
15138 @noindent
15139 The @code{gnatls} command has the form
15141 @smallexample
15142 $ gnatls switches @var{object_or_ali_file}
15143 @end smallexample
15145 @noindent
15146 The main argument is the list of object or @file{ali} files
15147 (@pxref{The Ada Library Information Files})
15148 for which information is requested.
15150 In normal mode, without additional option, @code{gnatls} produces a
15151 four-column listing. Each line represents information for a specific
15152 object. The first column gives the full path of the object, the second
15153 column gives the name of the principal unit in this object, the third
15154 column gives the status of the source and the fourth column gives the
15155 full path of the source representing this unit.
15156 Here is a simple example of use:
15158 @smallexample
15159 $ gnatls *.o
15160 ^./^[]^demo1.o            demo1            DIF demo1.adb
15161 ^./^[]^demo2.o            demo2             OK demo2.adb
15162 ^./^[]^hello.o            h1                OK hello.adb
15163 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15164 ^./^[]^instr.o            instr             OK instr.adb
15165 ^./^[]^tef.o              tef              DIF tef.adb
15166 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15167 ^./^[]^tgef.o             tgef             DIF tgef.adb
15168 @end smallexample
15170 @noindent
15171 The first line can be interpreted as follows: the main unit which is
15172 contained in
15173 object file @file{demo1.o} is demo1, whose main source is in
15174 @file{demo1.adb}. Furthermore, the version of the source used for the
15175 compilation of demo1 has been modified (DIF). Each source file has a status
15176 qualifier which can be:
15178 @table @code
15179 @item OK (unchanged)
15180 The version of the source file used for the compilation of the
15181 specified unit corresponds exactly to the actual source file.
15183 @item MOK (slightly modified)
15184 The version of the source file used for the compilation of the
15185 specified unit differs from the actual source file but not enough to
15186 require recompilation. If you use gnatmake with the qualifier
15187 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15188 MOK will not be recompiled.
15190 @item DIF (modified)
15191 No version of the source found on the path corresponds to the source
15192 used to build this object.
15194 @item ??? (file not found)
15195 No source file was found for this unit.
15197 @item HID (hidden,  unchanged version not first on PATH)
15198 The version of the source that corresponds exactly to the source used
15199 for compilation has been found on the path but it is hidden by another
15200 version of the same source that has been modified.
15202 @end table
15204 @node Switches for gnatls
15205 @section Switches for @code{gnatls}
15207 @noindent
15208 @code{gnatls} recognizes the following switches:
15210 @table @option
15211 @c !sort!
15212 @cindex @option{--version} @command{gnatls}
15213 Display Copyright and version, then exit disregarding all other options.
15215 @item --help
15216 @cindex @option{--help} @command{gnatls}
15217 If @option{--version} was not used, display usage, then exit disregarding
15218 all other options.
15220 @item ^-a^/ALL_UNITS^
15221 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15222 Consider all units, including those of the predefined Ada library.
15223 Especially useful with @option{^-d^/DEPENDENCIES^}.
15225 @item ^-d^/DEPENDENCIES^
15226 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15227 List sources from which specified units depend on.
15229 @item ^-h^/OUTPUT=OPTIONS^
15230 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15231 Output the list of options.
15233 @item ^-o^/OUTPUT=OBJECTS^
15234 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15235 Only output information about object files.
15237 @item ^-s^/OUTPUT=SOURCES^
15238 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15239 Only output information about source files.
15241 @item ^-u^/OUTPUT=UNITS^
15242 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15243 Only output information about compilation units.
15245 @item ^-files^/FILES^=@var{file}
15246 @cindex @option{^-files^/FILES^} (@code{gnatls})
15247 Take as arguments the files listed in text file @var{file}.
15248 Text file @var{file} may contain empty lines that are ignored.
15249 Each nonempty line should contain the name of an existing file.
15250 Several such switches may be specified simultaneously.
15252 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15253 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15254 @itemx ^-I^/SEARCH=^@var{dir}
15255 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15256 @itemx -nostdinc
15257 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15258 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15259 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15260 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15261 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15262 flags (@pxref{Switches for gnatmake}).
15264 @item --RTS=@var{rts-path}
15265 @cindex @option{--RTS} (@code{gnatls})
15266 Specifies the default location of the runtime library. Same meaning as the
15267 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15269 @item ^-v^/OUTPUT=VERBOSE^
15270 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15271 Verbose mode. Output the complete source, object and project paths. Do not use
15272 the default column layout but instead use long format giving as much as
15273 information possible on each requested units, including special
15274 characteristics such as:
15276 @table @code
15277 @item  Preelaborable
15278 The unit is preelaborable in the Ada sense.
15280 @item No_Elab_Code
15281 No elaboration code has been produced by the compiler for this unit.
15283 @item Pure
15284 The unit is pure in the Ada sense.
15286 @item Elaborate_Body
15287 The unit contains a pragma Elaborate_Body.
15289 @item Remote_Types
15290 The unit contains a pragma Remote_Types.
15292 @item Shared_Passive
15293 The unit contains a pragma Shared_Passive.
15295 @item Predefined
15296 This unit is part of the predefined environment and cannot be modified
15297 by the user.
15299 @item Remote_Call_Interface
15300 The unit contains a pragma Remote_Call_Interface.
15302 @end table
15304 @end table
15306 @node Examples of gnatls Usage
15307 @section Example of @code{gnatls} Usage
15308 @ifclear vms
15310 @noindent
15311 Example of using the verbose switch. Note how the source and
15312 object paths are affected by the -I switch.
15314 @smallexample
15315 $ gnatls -v -I.. demo1.o
15317 GNATLS 5.03w (20041123-34)
15318 Copyright 1997-2004 Free Software Foundation, Inc.
15320 Source Search Path:
15321    <Current_Directory>
15322    ../
15323    /home/comar/local/adainclude/
15325 Object Search Path:
15326    <Current_Directory>
15327    ../
15328    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15330 Project Search Path:
15331    <Current_Directory>
15332    /home/comar/local/lib/gnat/
15334 ./demo1.o
15335    Unit =>
15336      Name   => demo1
15337      Kind   => subprogram body
15338      Flags  => No_Elab_Code
15339      Source => demo1.adb    modified
15340 @end smallexample
15342 @noindent
15343 The following is an example of use of the dependency list.
15344 Note the use of the -s switch
15345 which gives a straight list of source files. This can be useful for
15346 building specialized scripts.
15348 @smallexample
15349 $ gnatls -d demo2.o
15350 ./demo2.o   demo2        OK demo2.adb
15351                          OK gen_list.ads
15352                          OK gen_list.adb
15353                          OK instr.ads
15354                          OK instr-child.ads
15356 $ gnatls -d -s -a demo1.o
15357 demo1.adb
15358 /home/comar/local/adainclude/ada.ads
15359 /home/comar/local/adainclude/a-finali.ads
15360 /home/comar/local/adainclude/a-filico.ads
15361 /home/comar/local/adainclude/a-stream.ads
15362 /home/comar/local/adainclude/a-tags.ads
15363 gen_list.ads
15364 gen_list.adb
15365 /home/comar/local/adainclude/gnat.ads
15366 /home/comar/local/adainclude/g-io.ads
15367 instr.ads
15368 /home/comar/local/adainclude/system.ads
15369 /home/comar/local/adainclude/s-exctab.ads
15370 /home/comar/local/adainclude/s-finimp.ads
15371 /home/comar/local/adainclude/s-finroo.ads
15372 /home/comar/local/adainclude/s-secsta.ads
15373 /home/comar/local/adainclude/s-stalib.ads
15374 /home/comar/local/adainclude/s-stoele.ads
15375 /home/comar/local/adainclude/s-stratt.ads
15376 /home/comar/local/adainclude/s-tasoli.ads
15377 /home/comar/local/adainclude/s-unstyp.ads
15378 /home/comar/local/adainclude/unchconv.ads
15379 @end smallexample
15380 @end ifclear
15382 @ifset vms
15383 @smallexample
15384 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15386 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15387 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15388 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15389 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15390 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15391 demo1.adb
15392 gen_list.ads
15393 gen_list.adb
15394 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15395 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15396 instr.ads
15397 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15398 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15399 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15400 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15401 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15402 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15403 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15404 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15405 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15406 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15407 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15408 @end smallexample
15409 @end ifset
15411 @node Cleaning Up Using gnatclean
15412 @chapter Cleaning Up Using @code{gnatclean}
15413 @findex gnatclean
15414 @cindex Cleaning tool
15416 @noindent
15417 @code{gnatclean} is a tool that allows the deletion of files produced by the
15418 compiler, binder and linker, including ALI files, object files, tree files,
15419 expanded source files, library files, interface copy source files, binder
15420 generated files and executable files.
15422 @menu
15423 * Running gnatclean::
15424 * Switches for gnatclean::
15425 @c * Examples of gnatclean Usage::
15426 @end menu
15428 @node Running gnatclean
15429 @section Running @code{gnatclean}
15431 @noindent
15432 The @code{gnatclean} command has the form:
15434 @smallexample
15435 $ gnatclean switches @var{names}
15436 @end smallexample
15438 @noindent
15439 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15440 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15441 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15443 @noindent
15444 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15445 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15446 the linker. In informative-only mode, specified by switch
15447 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15448 normal mode is listed, but no file is actually deleted.
15450 @node Switches for gnatclean
15451 @section Switches for @code{gnatclean}
15453 @noindent
15454 @code{gnatclean} recognizes the following switches:
15456 @table @option
15457 @c !sort!
15458 @cindex @option{--version} @command{gnatclean}
15459 Display Copyright and version, then exit disregarding all other options.
15461 @item --help
15462 @cindex @option{--help} @command{gnatclean}
15463 If @option{--version} was not used, display usage, then exit disregarding
15464 all other options.
15466 @item ^--subdirs^/SUBDIRS^=subdir
15467 Actual object directory of each project file is the subdirectory subdir of the
15468 object directory specified or defauted in the project file.
15470 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15471 By default, shared library projects are not allowed to import static library
15472 projects. When this switch is used on the command line, this restriction is
15473 relaxed.
15475 @item ^-c^/COMPILER_FILES_ONLY^
15476 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15477 Only attempt to delete the files produced by the compiler, not those produced
15478 by the binder or the linker. The files that are not to be deleted are library
15479 files, interface copy files, binder generated files and executable files.
15481 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15482 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15483 Indicate that ALI and object files should normally be found in directory
15484 @var{dir}.
15486 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15487 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15488 When using project files, if some errors or warnings are detected during
15489 parsing and verbose mode is not in effect (no use of switch
15490 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15491 file, rather than its simple file name.
15493 @item ^-h^/HELP^
15494 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15495 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15497 @item ^-n^/NODELETE^
15498 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15499 Informative-only mode. Do not delete any files. Output the list of the files
15500 that would have been deleted if this switch was not specified.
15502 @item ^-P^/PROJECT_FILE=^@var{project}
15503 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15504 Use project file @var{project}. Only one such switch can be used.
15505 When cleaning a project file, the files produced by the compilation of the
15506 immediate sources or inherited sources of the project files are to be
15507 deleted. This is not depending on the presence or not of executable names
15508 on the command line.
15510 @item ^-q^/QUIET^
15511 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15512 Quiet output. If there are no errors, do not output anything, except in
15513 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15514 (switch ^-n^/NODELETE^).
15516 @item ^-r^/RECURSIVE^
15517 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15518 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15519 clean all imported and extended project files, recursively. If this switch
15520 is not specified, only the files related to the main project file are to be
15521 deleted. This switch has no effect if no project file is specified.
15523 @item ^-v^/VERBOSE^
15524 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15525 Verbose mode.
15527 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15528 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15529 Indicates the verbosity of the parsing of GNAT project files.
15530 @xref{Switches Related to Project Files}.
15532 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15533 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15534 Indicates that external variable @var{name} has the value @var{value}.
15535 The Project Manager will use this value for occurrences of
15536 @code{external(name)} when parsing the project file.
15537 @xref{Switches Related to Project Files}.
15539 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15540 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15541 When searching for ALI and object files, look in directory
15542 @var{dir}.
15544 @item ^-I^/SEARCH=^@var{dir}
15545 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15546 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15548 @item ^-I-^/NOCURRENT_DIRECTORY^
15549 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15550 @cindex Source files, suppressing search
15551 Do not look for ALI or object files in the directory
15552 where @code{gnatclean} was invoked.
15554 @end table
15556 @c @node Examples of gnatclean Usage
15557 @c @section Examples of @code{gnatclean} Usage
15559 @ifclear vms
15560 @node GNAT and Libraries
15561 @chapter GNAT and Libraries
15562 @cindex Library, building, installing, using
15564 @noindent
15565 This chapter describes how to build and use libraries with GNAT, and also shows
15566 how to recompile the GNAT run-time library. You should be familiar with the
15567 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15568 chapter.
15570 @menu
15571 * Introduction to Libraries in GNAT::
15572 * General Ada Libraries::
15573 * Stand-alone Ada Libraries::
15574 * Rebuilding the GNAT Run-Time Library::
15575 @end menu
15577 @node Introduction to Libraries in GNAT
15578 @section Introduction to Libraries in GNAT
15580 @noindent
15581 A library is, conceptually, a collection of objects which does not have its
15582 own main thread of execution, but rather provides certain services to the
15583 applications that use it. A library can be either statically linked with the
15584 application, in which case its code is directly included in the application,
15585 or, on platforms that support it, be dynamically linked, in which case
15586 its code is shared by all applications making use of this library.
15588 GNAT supports both types of libraries.
15589 In the static case, the compiled code can be provided in different ways. The
15590 simplest approach is to provide directly the set of objects resulting from
15591 compilation of the library source files. Alternatively, you can group the
15592 objects into an archive using whatever commands are provided by the operating
15593 system. For the latter case, the objects are grouped into a shared library.
15595 In the GNAT environment, a library has three types of components:
15596 @itemize @bullet
15597 @item
15598 Source files.
15599 @item
15600 @file{ALI} files.
15601 @xref{The Ada Library Information Files}.
15602 @item
15603 Object files, an archive or a shared library.
15604 @end itemize
15606 @noindent
15607 A GNAT library may expose all its source files, which is useful for
15608 documentation purposes. Alternatively, it may expose only the units needed by
15609 an external user to make use of the library. That is to say, the specs
15610 reflecting the library services along with all the units needed to compile
15611 those specs, which can include generic bodies or any body implementing an
15612 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15613 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15615 All compilation units comprising an application, including those in a library,
15616 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15617 computes the elaboration order from the @file{ALI} files and this is why they
15618 constitute a mandatory part of GNAT libraries.
15619 @emph{Stand-alone libraries} are the exception to this rule because a specific
15620 library elaboration routine is produced independently of the application(s)
15621 using the library.
15623 @node General Ada Libraries
15624 @section General Ada Libraries
15626 @menu
15627 * Building a library::
15628 * Installing a library::
15629 * Using a library::
15630 @end menu
15632 @node Building a library
15633 @subsection Building a library
15635 @noindent
15636 The easiest way to build a library is to use the Project Manager,
15637 which supports a special type of project called a @emph{Library Project}
15638 (@pxref{Library Projects}).
15640 A project is considered a library project, when two project-level attributes
15641 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15642 control different aspects of library configuration, additional optional
15643 project-level attributes can be specified:
15644 @table @code
15645 @item Library_Kind
15646 This attribute controls whether the library is to be static or dynamic
15648 @item Library_Version
15649 This attribute specifies the library version; this value is used
15650 during dynamic linking of shared libraries to determine if the currently
15651 installed versions of the binaries are compatible.
15653 @item Library_Options
15654 @item Library_GCC
15655 These attributes specify additional low-level options to be used during
15656 library generation, and redefine the actual application used to generate
15657 library.
15658 @end table
15660 @noindent
15661 The GNAT Project Manager takes full care of the library maintenance task,
15662 including recompilation of the source files for which objects do not exist
15663 or are not up to date, assembly of the library archive, and installation of
15664 the library (i.e., copying associated source, object and @file{ALI} files
15665 to the specified location).
15667 Here is a simple library project file:
15668 @smallexample @c ada
15669 project My_Lib is
15670    for Source_Dirs use ("src1", "src2");
15671    for Object_Dir use "obj";
15672    for Library_Name use "mylib";
15673    for Library_Dir use "lib";
15674    for Library_Kind use "dynamic";
15675 end My_lib;
15676 @end smallexample
15678 @noindent
15679 and the compilation command to build and install the library:
15681 @smallexample @c ada
15682   $ gnatmake -Pmy_lib
15683 @end smallexample
15685 @noindent
15686 It is not entirely trivial to perform manually all the steps required to
15687 produce a library. We recommend that you use the GNAT Project Manager
15688 for this task. In special cases where this is not desired, the necessary
15689 steps are discussed below.
15691 There are various possibilities for compiling the units that make up the
15692 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15693 with a conventional script. For simple libraries, it is also possible to create
15694 a dummy main program which depends upon all the packages that comprise the
15695 interface of the library. This dummy main program can then be given to
15696 @command{gnatmake}, which will ensure that all necessary objects are built.
15698 After this task is accomplished, you should follow the standard procedure
15699 of the underlying operating system to produce the static or shared library.
15701 Here is an example of such a dummy program:
15702 @smallexample @c ada
15703 @group
15704 with My_Lib.Service1;
15705 with My_Lib.Service2;
15706 with My_Lib.Service3;
15707 procedure My_Lib_Dummy is
15708 begin
15709    null;
15710 end;
15711 @end group
15712 @end smallexample
15714 @noindent
15715 Here are the generic commands that will build an archive or a shared library.
15717 @smallexample
15718 # compiling the library
15719 $ gnatmake -c my_lib_dummy.adb
15721 # we don't need the dummy object itself
15722 $ rm my_lib_dummy.o my_lib_dummy.ali
15724 # create an archive with the remaining objects
15725 $ ar rc libmy_lib.a *.o
15726 # some systems may require "ranlib" to be run as well
15728 # or create a shared library
15729 $ gcc -shared -o libmy_lib.so *.o
15730 # some systems may require the code to have been compiled with -fPIC
15732 # remove the object files that are now in the library
15733 $ rm *.o
15735 # Make the ALI files read-only so that gnatmake will not try to
15736 # regenerate the objects that are in the library
15737 $ chmod -w *.ali
15738 @end smallexample
15740 @noindent
15741 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15742 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15743 be accessed by the directive @option{-l@var{xxx}} at link time.
15745 @node Installing a library
15746 @subsection Installing a library
15747 @cindex @code{ADA_PROJECT_PATH}
15748 @cindex @code{GPR_PROJECT_PATH}
15750 @noindent
15751 If you use project files, library installation is part of the library build
15752 process (@pxref{Installing a library with project files}).
15754 When project files are not an option, it is also possible, but not recommended,
15755 to install the library so that the sources needed to use the library are on the
15756 Ada source path and the ALI files & libraries be on the Ada Object path (see
15757 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15758 administrator can place general-purpose libraries in the default compiler
15759 paths, by specifying the libraries' location in the configuration files
15760 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15761 must be located in the GNAT installation tree at the same place as the gcc spec
15762 file. The location of the gcc spec file can be determined as follows:
15763 @smallexample
15764 $ gcc -v
15765 @end smallexample
15767 @noindent
15768 The configuration files mentioned above have a simple format: each line
15769 must contain one unique directory name.
15770 Those names are added to the corresponding path
15771 in their order of appearance in the file. The names can be either absolute
15772 or relative; in the latter case, they are relative to where theses files
15773 are located.
15775 The files @file{ada_source_path} and @file{ada_object_path} might not be
15776 present in a
15777 GNAT installation, in which case, GNAT will look for its run-time library in
15778 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15779 objects and @file{ALI} files). When the files exist, the compiler does not
15780 look in @file{adainclude} and @file{adalib}, and thus the
15781 @file{ada_source_path} file
15782 must contain the location for the GNAT run-time sources (which can simply
15783 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15784 contain the location for the GNAT run-time objects (which can simply
15785 be @file{adalib}).
15787 You can also specify a new default path to the run-time library at compilation
15788 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15789 the run-time library you want your program to be compiled with. This switch is
15790 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15791 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15793 It is possible to install a library before or after the standard GNAT
15794 library, by reordering the lines in the configuration files. In general, a
15795 library must be installed before the GNAT library if it redefines
15796 any part of it.
15798 @node Using a library
15799 @subsection Using a library
15801 @noindent Once again, the project facility greatly simplifies the use of
15802 libraries. In this context, using a library is just a matter of adding a
15803 @code{with} clause in the user project. For instance, to make use of the
15804 library @code{My_Lib} shown in examples in earlier sections, you can
15805 write:
15807 @smallexample @c projectfile
15808 with "my_lib";
15809 project My_Proj is
15810   @dots{}
15811 end My_Proj;
15812 @end smallexample
15814 Even if you have a third-party, non-Ada library, you can still use GNAT's
15815 Project Manager facility to provide a wrapper for it. For example, the
15816 following project, when @code{with}ed by your main project, will link with the
15817 third-party library @file{liba.a}:
15819 @smallexample @c projectfile
15820 @group
15821 project Liba is
15822    for Externally_Built use "true";
15823    for Source_Files use ();
15824    for Library_Dir use "lib";
15825    for Library_Name use "a";
15826    for Library_Kind use "static";
15827 end Liba;
15828 @end group
15829 @end smallexample
15830 This is an alternative to the use of @code{pragma Linker_Options}. It is
15831 especially interesting in the context of systems with several interdependent
15832 static libraries where finding a proper linker order is not easy and best be
15833 left to the tools having visibility over project dependence information.
15835 @noindent
15836 In order to use an Ada library manually, you need to make sure that this
15837 library is on both your source and object path
15838 (see @ref{Search Paths and the Run-Time Library (RTL)}
15839 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15840 in an archive or a shared library, you need to specify the desired
15841 library at link time.
15843 For example, you can use the library @file{mylib} installed in
15844 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15846 @smallexample
15847 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15848   -largs -lmy_lib
15849 @end smallexample
15851 @noindent
15852 This can be expressed more simply:
15853 @smallexample
15854 $ gnatmake my_appl
15855 @end smallexample
15856 @noindent
15857 when the following conditions are met:
15858 @itemize @bullet
15859 @item
15860 @file{/dir/my_lib_src} has been added by the user to the environment
15861 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15862 @file{ada_source_path}
15863 @item
15864 @file{/dir/my_lib_obj} has been added by the user to the environment
15865 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15866 @file{ada_object_path}
15867 @item
15868 a pragma @code{Linker_Options} has been added to one of the sources.
15869 For example:
15871 @smallexample @c ada
15872 pragma Linker_Options ("-lmy_lib");
15873 @end smallexample
15874 @end itemize
15876 @node Stand-alone Ada Libraries
15877 @section Stand-alone Ada Libraries
15878 @cindex Stand-alone library, building, using
15880 @menu
15881 * Introduction to Stand-alone Libraries::
15882 * Building a Stand-alone Library::
15883 * Creating a Stand-alone Library to be used in a non-Ada context::
15884 * Restrictions in Stand-alone Libraries::
15885 @end menu
15887 @node Introduction to Stand-alone Libraries
15888 @subsection Introduction to Stand-alone Libraries
15890 @noindent
15891 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15892 necessary code to
15893 elaborate the Ada units that are included in the library. In contrast with
15894 an ordinary library, which consists of all sources, objects and @file{ALI}
15895 files of the
15896 library, a SAL may specify a restricted subset of compilation units
15897 to serve as a library interface. In this case, the fully
15898 self-sufficient set of files will normally consist of an objects
15899 archive, the sources of interface units' specs, and the @file{ALI}
15900 files of interface units.
15901 If an interface spec contains a generic unit or an inlined subprogram,
15902 the body's
15903 source must also be provided; if the units that must be provided in the source
15904 form depend on other units, the source and @file{ALI} files of those must
15905 also be provided.
15907 The main purpose of a SAL is to minimize the recompilation overhead of client
15908 applications when a new version of the library is installed. Specifically,
15909 if the interface sources have not changed, client applications do not need to
15910 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15911 version, controlled by @code{Library_Version} attribute, is not changed,
15912 then the clients do not need to be relinked.
15914 SALs also allow the library providers to minimize the amount of library source
15915 text exposed to the clients.  Such ``information hiding'' might be useful or
15916 necessary for various reasons.
15918 Stand-alone libraries are also well suited to be used in an executable whose
15919 main routine is not written in Ada.
15921 @node Building a Stand-alone Library
15922 @subsection Building a Stand-alone Library
15924 @noindent
15925 GNAT's Project facility provides a simple way of building and installing
15926 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15927 To be a Stand-alone Library Project, in addition to the two attributes
15928 that make a project a Library Project (@code{Library_Name} and
15929 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15930 @code{Library_Interface} must be defined.  For example:
15932 @smallexample @c projectfile
15933 @group
15934    for Library_Dir use "lib_dir";
15935    for Library_Name use "dummy";
15936    for Library_Interface use ("int1", "int1.child");
15937 @end group
15938 @end smallexample
15940 @noindent
15941 Attribute @code{Library_Interface} has a non-empty string list value,
15942 each string in the list designating a unit contained in an immediate source
15943 of the project file.
15945 When a Stand-alone Library is built, first the binder is invoked to build
15946 a package whose name depends on the library name
15947 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
15948 This binder-generated package includes initialization and
15949 finalization procedures whose
15950 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
15951 in the example
15952 above). The object corresponding to this package is included in the library.
15954 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
15955 calling of these procedures if a static SAL is built, or if a shared SAL
15956 is built
15957 with the project-level attribute @code{Library_Auto_Init} set to
15958 @code{"false"}.
15960 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
15961 (those that are listed in attribute @code{Library_Interface}) are copied to
15962 the Library Directory. As a consequence, only the Interface Units may be
15963 imported from Ada units outside of the library. If other units are imported,
15964 the binding phase will fail.
15966 The attribute @code{Library_Src_Dir} may be specified for a
15967 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
15968 single string value. Its value must be the path (absolute or relative to the
15969 project directory) of an existing directory. This directory cannot be the
15970 object directory or one of the source directories, but it can be the same as
15971 the library directory. The sources of the Interface
15972 Units of the library that are needed by an Ada client of the library will be
15973 copied to the designated directory, called the Interface Copy directory.
15974 These sources include the specs of the Interface Units, but they may also
15975 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
15976 are used, or when there is a generic unit in the spec. Before the sources
15977 are copied to the Interface Copy directory, an attempt is made to delete all
15978 files in the Interface Copy directory.
15980 Building stand-alone libraries by hand is somewhat tedious, but for those
15981 occasions when it is necessary here are the steps that you need to perform:
15982 @itemize @bullet
15983 @item
15984 Compile all library sources.
15986 @item
15987 Invoke the binder with the switch @option{-n} (No Ada main program),
15988 with all the @file{ALI} files of the interfaces, and
15989 with the switch @option{-L} to give specific names to the @code{init}
15990 and @code{final} procedures.  For example:
15991 @smallexample
15992   gnatbind -n int1.ali int2.ali -Lsal1
15993 @end smallexample
15995 @item
15996 Compile the binder generated file:
15997 @smallexample
15998   gcc -c b~int2.adb
15999 @end smallexample
16001 @item
16002 Link the dynamic library with all the necessary object files,
16003 indicating to the linker the names of the @code{init} (and possibly
16004 @code{final}) procedures for automatic initialization (and finalization).
16005 The built library should be placed in a directory different from
16006 the object directory.
16008 @item
16009 Copy the @code{ALI} files of the interface to the library directory,
16010 add in this copy an indication that it is an interface to a SAL
16011 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16012 with letter ``P'') and make the modified copy of the @file{ALI} file
16013 read-only.
16014 @end itemize
16016 @noindent
16017 Using SALs is not different from using other libraries
16018 (see @ref{Using a library}).
16020 @node Creating a Stand-alone Library to be used in a non-Ada context
16021 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16023 @noindent
16024 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16025 a non-Ada context.
16027 The only extra step required is to ensure that library interface subprograms
16028 are compatible with the main program, by means of @code{pragma Export}
16029 or @code{pragma Convention}.
16031 Here is an example of simple library interface for use with C main program:
16033 @smallexample @c ada
16034 package My_Package is
16036    procedure Do_Something;
16037    pragma Export (C, Do_Something, "do_something");
16039    procedure Do_Something_Else;
16040    pragma Export (C, Do_Something_Else, "do_something_else");
16042 end My_Package;
16043 @end smallexample
16045 @noindent
16046 On the foreign language side, you must provide a ``foreign'' view of the
16047 library interface; remember that it should contain elaboration routines in
16048 addition to interface subprograms.
16050 The example below shows the content of @code{mylib_interface.h} (note
16051 that there is no rule for the naming of this file, any name can be used)
16052 @smallexample
16053 /* the library elaboration procedure */
16054 extern void mylibinit (void);
16056 /* the library finalization procedure */
16057 extern void mylibfinal (void);
16059 /* the interface exported by the library */
16060 extern void do_something (void);
16061 extern void do_something_else (void);
16062 @end smallexample
16064 @noindent
16065 Libraries built as explained above can be used from any program, provided
16066 that the elaboration procedures (named @code{mylibinit} in the previous
16067 example) are called before the library services are used. Any number of
16068 libraries can be used simultaneously, as long as the elaboration
16069 procedure of each library is called.
16071 Below is an example of a C program that uses the @code{mylib} library.
16073 @smallexample
16074 #include "mylib_interface.h"
16077 main (void)
16079    /* First, elaborate the library before using it */
16080    mylibinit ();
16082    /* Main program, using the library exported entities */
16083    do_something ();
16084    do_something_else ();
16086    /* Library finalization at the end of the program */
16087    mylibfinal ();
16088    return 0;
16090 @end smallexample
16092 @noindent
16093 Note that invoking any library finalization procedure generated by
16094 @code{gnatbind} shuts down the Ada run-time environment.
16095 Consequently, the
16096 finalization of all Ada libraries must be performed at the end of the program.
16097 No call to these libraries or to the Ada run-time library should be made
16098 after the finalization phase.
16100 @node Restrictions in Stand-alone Libraries
16101 @subsection Restrictions in Stand-alone Libraries
16103 @noindent
16104 The pragmas listed below should be used with caution inside libraries,
16105 as they can create incompatibilities with other Ada libraries:
16106 @itemize @bullet
16107 @item pragma @code{Locking_Policy}
16108 @item pragma @code{Queuing_Policy}
16109 @item pragma @code{Task_Dispatching_Policy}
16110 @item pragma @code{Unreserve_All_Interrupts}
16111 @end itemize
16113 @noindent
16114 When using a library that contains such pragmas, the user must make sure
16115 that all libraries use the same pragmas with the same values. Otherwise,
16116 @code{Program_Error} will
16117 be raised during the elaboration of the conflicting
16118 libraries. The usage of these pragmas and its consequences for the user
16119 should therefore be well documented.
16121 Similarly, the traceback in the exception occurrence mechanism should be
16122 enabled or disabled in a consistent manner across all libraries.
16123 Otherwise, Program_Error will be raised during the elaboration of the
16124 conflicting libraries.
16126 If the @code{Version} or @code{Body_Version}
16127 attributes are used inside a library, then you need to
16128 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16129 libraries, so that version identifiers can be properly computed.
16130 In practice these attributes are rarely used, so this is unlikely
16131 to be a consideration.
16133 @node  Rebuilding the GNAT Run-Time Library
16134 @section Rebuilding the GNAT Run-Time Library
16135 @cindex GNAT Run-Time Library, rebuilding
16136 @cindex Building the GNAT Run-Time Library
16137 @cindex Rebuilding the GNAT Run-Time Library
16138 @cindex Run-Time Library, rebuilding
16140 @noindent
16141 It may be useful to recompile the GNAT library in various contexts, the
16142 most important one being the use of partition-wide configuration pragmas
16143 such as @code{Normalize_Scalars}. A special Makefile called
16144 @code{Makefile.adalib} is provided to that effect and can be found in
16145 the directory containing the GNAT library. The location of this
16146 directory depends on the way the GNAT environment has been installed and can
16147 be determined by means of the command:
16149 @smallexample
16150 $ gnatls -v
16151 @end smallexample
16153 @noindent
16154 The last entry in the object search path usually contains the
16155 gnat library. This Makefile contains its own documentation and in
16156 particular the set of instructions needed to rebuild a new library and
16157 to use it.
16159 @node Using the GNU make Utility
16160 @chapter Using the GNU @code{make} Utility
16161 @findex make
16163 @noindent
16164 This chapter offers some examples of makefiles that solve specific
16165 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16166 make, make, GNU @code{make}}), nor does it try to replace the
16167 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16169 All the examples in this section are specific to the GNU version of
16170 make. Although @command{make} is a standard utility, and the basic language
16171 is the same, these examples use some advanced features found only in
16172 @code{GNU make}.
16174 @menu
16175 * Using gnatmake in a Makefile::
16176 * Automatically Creating a List of Directories::
16177 * Generating the Command Line Switches::
16178 * Overcoming Command Line Length Limits::
16179 @end menu
16181 @node Using gnatmake in a Makefile
16182 @section Using gnatmake in a Makefile
16183 @findex makefile
16184 @cindex GNU make
16186 @noindent
16187 Complex project organizations can be handled in a very powerful way by
16188 using GNU make combined with gnatmake. For instance, here is a Makefile
16189 which allows you to build each subsystem of a big project into a separate
16190 shared library. Such a makefile allows you to significantly reduce the link
16191 time of very big applications while maintaining full coherence at
16192 each step of the build process.
16194 The list of dependencies are handled automatically by
16195 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16196 the appropriate directories.
16198 Note that you should also read the example on how to automatically
16199 create the list of directories
16200 (@pxref{Automatically Creating a List of Directories})
16201 which might help you in case your project has a lot of subdirectories.
16203 @smallexample
16204 @iftex
16205 @leftskip=0cm
16206 @font@heightrm=cmr8
16207 @heightrm
16208 @end iftex
16209 ## This Makefile is intended to be used with the following directory
16210 ## configuration:
16211 ##  - The sources are split into a series of csc (computer software components)
16212 ##    Each of these csc is put in its own directory.
16213 ##    Their name are referenced by the directory names.
16214 ##    They will be compiled into shared library (although this would also work
16215 ##    with static libraries
16216 ##  - The main program (and possibly other packages that do not belong to any
16217 ##    csc is put in the top level directory (where the Makefile is).
16218 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16219 ##                    \_ second_csc (sources) __ lib (will contain the library)
16220 ##                    \_ @dots{}
16221 ## Although this Makefile is build for shared library, it is easy to modify
16222 ## to build partial link objects instead (modify the lines with -shared and
16223 ## gnatlink below)
16225 ## With this makefile, you can change any file in the system or add any new
16226 ## file, and everything will be recompiled correctly (only the relevant shared
16227 ## objects will be recompiled, and the main program will be re-linked).
16229 # The list of computer software component for your project. This might be
16230 # generated automatically.
16231 CSC_LIST=aa bb cc
16233 # Name of the main program (no extension)
16234 MAIN=main
16236 # If we need to build objects with -fPIC, uncomment the following line
16237 #NEED_FPIC=-fPIC
16239 # The following variable should give the directory containing libgnat.so
16240 # You can get this directory through 'gnatls -v'. This is usually the last
16241 # directory in the Object_Path.
16242 GLIB=@dots{}
16244 # The directories for the libraries
16245 # (This macro expands the list of CSC to the list of shared libraries, you
16246 # could simply use the expanded form:
16247 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16248 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16250 $@{MAIN@}: objects $@{LIB_DIR@}
16251     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16252     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16254 objects::
16255     # recompile the sources
16256     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16258 # Note: In a future version of GNAT, the following commands will be simplified
16259 # by a new tool, gnatmlib
16260 $@{LIB_DIR@}:
16261     mkdir -p $@{dir $@@ @}
16262     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16263     cd $@{dir $@@ @} && cp -f ../*.ali .
16265 # The dependencies for the modules
16266 # Note that we have to force the expansion of *.o, since in some cases
16267 # make won't be able to do it itself.
16268 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16269 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16270 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16272 # Make sure all of the shared libraries are in the path before starting the
16273 # program
16274 run::
16275     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16277 clean::
16278     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16279     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16280     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16281     $@{RM@} *.o *.ali $@{MAIN@}
16282 @end smallexample
16284 @node Automatically Creating a List of Directories
16285 @section Automatically Creating a List of Directories
16287 @noindent
16288 In most makefiles, you will have to specify a list of directories, and
16289 store it in a variable. For small projects, it is often easier to
16290 specify each of them by hand, since you then have full control over what
16291 is the proper order for these directories, which ones should be
16292 included.
16294 However, in larger projects, which might involve hundreds of
16295 subdirectories, it might be more convenient to generate this list
16296 automatically.
16298 The example below presents two methods. The first one, although less
16299 general, gives you more control over the list. It involves wildcard
16300 characters, that are automatically expanded by @command{make}. Its
16301 shortcoming is that you need to explicitly specify some of the
16302 organization of your project, such as for instance the directory tree
16303 depth, whether some directories are found in a separate tree, @enddots{}
16305 The second method is the most general one. It requires an external
16306 program, called @command{find}, which is standard on all Unix systems. All
16307 the directories found under a given root directory will be added to the
16308 list.
16310 @smallexample
16311 @iftex
16312 @leftskip=0cm
16313 @font@heightrm=cmr8
16314 @heightrm
16315 @end iftex
16316 # The examples below are based on the following directory hierarchy:
16317 # All the directories can contain any number of files
16318 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16319 #                       ->  ab
16320 #                       ->  ac
16321 #                ->  b  ->  ba  ->  baa
16322 #                       ->  bb
16323 #                       ->  bc
16324 # This Makefile creates a variable called DIRS, that can be reused any time
16325 # you need this list (see the other examples in this section)
16327 # The root of your project's directory hierarchy
16328 ROOT_DIRECTORY=.
16330 ####
16331 # First method: specify explicitly the list of directories
16332 # This allows you to specify any subset of all the directories you need.
16333 ####
16335 DIRS := a/aa/ a/ab/ b/ba/
16337 ####
16338 # Second method: use wildcards
16339 # Note that the argument(s) to wildcard below should end with a '/'.
16340 # Since wildcards also return file names, we have to filter them out
16341 # to avoid duplicate directory names.
16342 # We thus use make's @code{dir} and @code{sort} functions.
16343 # It sets DIRs to the following value (note that the directories aaa and baa
16344 # are not given, unless you change the arguments to wildcard).
16345 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16346 ####
16348 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16349                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16351 ####
16352 # Third method: use an external program
16353 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16354 # This is the most complete command: it sets DIRs to the following value:
16355 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16356 ####
16358 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16360 @end smallexample
16362 @node Generating the Command Line Switches
16363 @section Generating the Command Line Switches
16365 @noindent
16366 Once you have created the list of directories as explained in the
16367 previous section (@pxref{Automatically Creating a List of Directories}),
16368 you can easily generate the command line arguments to pass to gnatmake.
16370 For the sake of completeness, this example assumes that the source path
16371 is not the same as the object path, and that you have two separate lists
16372 of directories.
16374 @smallexample
16375 # see "Automatically creating a list of directories" to create
16376 # these variables
16377 SOURCE_DIRS=
16378 OBJECT_DIRS=
16380 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16381 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16383 all:
16384         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16385 @end smallexample
16387 @node Overcoming Command Line Length Limits
16388 @section Overcoming Command Line Length Limits
16390 @noindent
16391 One problem that might be encountered on big projects is that many
16392 operating systems limit the length of the command line. It is thus hard to give
16393 gnatmake the list of source and object directories.
16395 This example shows how you can set up environment variables, which will
16396 make @command{gnatmake} behave exactly as if the directories had been
16397 specified on the command line, but have a much higher length limit (or
16398 even none on most systems).
16400 It assumes that you have created a list of directories in your Makefile,
16401 using one of the methods presented in
16402 @ref{Automatically Creating a List of Directories}.
16403 For the sake of completeness, we assume that the object
16404 path (where the ALI files are found) is different from the sources patch.
16406 Note a small trick in the Makefile below: for efficiency reasons, we
16407 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16408 expanded immediately by @code{make}. This way we overcome the standard
16409 make behavior which is to expand the variables only when they are
16410 actually used.
16412 On Windows, if you are using the standard Windows command shell, you must
16413 replace colons with semicolons in the assignments to these variables.
16415 @smallexample
16416 @iftex
16417 @leftskip=0cm
16418 @font@heightrm=cmr8
16419 @heightrm
16420 @end iftex
16421 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16422 # This is the same thing as putting the -I arguments on the command line.
16423 # (the equivalent of using -aI on the command line would be to define
16424 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16425 # You can of course have different values for these variables.
16427 # Note also that we need to keep the previous values of these variables, since
16428 # they might have been set before running 'make' to specify where the GNAT
16429 # library is installed.
16431 # see "Automatically creating a list of directories" to create these
16432 # variables
16433 SOURCE_DIRS=
16434 OBJECT_DIRS=
16436 empty:=
16437 space:=$@{empty@} $@{empty@}
16438 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16439 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16440 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16441 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16442 export ADA_INCLUDE_PATH
16443 export ADA_OBJECT_PATH
16445 all:
16446         gnatmake main_unit
16447 @end smallexample
16448 @end ifclear
16450 @node Memory Management Issues
16451 @chapter Memory Management Issues
16453 @noindent
16454 This chapter describes some useful memory pools provided in the GNAT library
16455 and in particular the GNAT Debug Pool facility, which can be used to detect
16456 incorrect uses of access values (including ``dangling references'').
16457 @ifclear vms
16458 It also describes the @command{gnatmem} tool, which can be used to track down
16459 ``memory leaks''.
16460 @end ifclear
16462 @menu
16463 * Some Useful Memory Pools::
16464 * The GNAT Debug Pool Facility::
16465 @ifclear vms
16466 * The gnatmem Tool::
16467 @end ifclear
16468 @end menu
16470 @node Some Useful Memory Pools
16471 @section Some Useful Memory Pools
16472 @findex Memory Pool
16473 @cindex storage, pool
16475 @noindent
16476 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16477 storage pool. Allocations use the standard system call @code{malloc} while
16478 deallocations use the standard system call @code{free}. No reclamation is
16479 performed when the pool goes out of scope. For performance reasons, the
16480 standard default Ada allocators/deallocators do not use any explicit storage
16481 pools but if they did, they could use this storage pool without any change in
16482 behavior. That is why this storage pool is used  when the user
16483 manages to make the default implicit allocator explicit as in this example:
16484 @smallexample @c ada
16485    type T1 is access Something;
16486     -- no Storage pool is defined for T2
16487    type T2 is access Something_Else;
16488    for T2'Storage_Pool use T1'Storage_Pool;
16489    -- the above is equivalent to
16490    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16491 @end smallexample
16493 @noindent
16494 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16495 pool. The allocation strategy is similar to @code{Pool_Local}'s
16496 except that the all
16497 storage allocated with this pool is reclaimed when the pool object goes out of
16498 scope. This pool provides a explicit mechanism similar to the implicit one
16499 provided by several Ada 83 compilers for allocations performed through a local
16500 access type and whose purpose was to reclaim memory when exiting the
16501 scope of a given local access. As an example, the following program does not
16502 leak memory even though it does not perform explicit deallocation:
16504 @smallexample @c ada
16505 with System.Pool_Local;
16506 procedure Pooloc1 is
16507    procedure Internal is
16508       type A is access Integer;
16509       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16510       for A'Storage_Pool use X;
16511       v : A;
16512    begin
16513       for I in  1 .. 50 loop
16514          v := new Integer;
16515       end loop;
16516    end Internal;
16517 begin
16518    for I in  1 .. 100 loop
16519       Internal;
16520    end loop;
16521 end Pooloc1;
16522 @end smallexample
16524 @noindent
16525 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16526 @code{Storage_Size} is specified for an access type.
16527 The whole storage for the pool is
16528 allocated at once, usually on the stack at the point where the access type is
16529 elaborated. It is automatically reclaimed when exiting the scope where the
16530 access type is defined. This package is not intended to be used directly by the
16531 user and it is implicitly used for each such declaration:
16533 @smallexample @c ada
16534    type T1 is access Something;
16535    for T1'Storage_Size use 10_000;
16536 @end smallexample
16538 @node The GNAT Debug Pool Facility
16539 @section The GNAT Debug Pool Facility
16540 @findex Debug Pool
16541 @cindex storage, pool, memory corruption
16543 @noindent
16544 The use of unchecked deallocation and unchecked conversion can easily
16545 lead to incorrect memory references. The problems generated by such
16546 references are usually difficult to tackle because the symptoms can be
16547 very remote from the origin of the problem. In such cases, it is
16548 very helpful to detect the problem as early as possible. This is the
16549 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16551 In order to use the GNAT specific debugging pool, the user must
16552 associate a debug pool object with each of the access types that may be
16553 related to suspected memory problems. See Ada Reference Manual 13.11.
16554 @smallexample @c ada
16555 type Ptr is access Some_Type;
16556 Pool : GNAT.Debug_Pools.Debug_Pool;
16557 for Ptr'Storage_Pool use Pool;
16558 @end smallexample
16560 @noindent
16561 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16562 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16563 allow the user to redefine allocation and deallocation strategies. They
16564 also provide a checkpoint for each dereference, through the use of
16565 the primitive operation @code{Dereference} which is implicitly called at
16566 each dereference of an access value.
16568 Once an access type has been associated with a debug pool, operations on
16569 values of the type may raise four distinct exceptions,
16570 which correspond to four potential kinds of memory corruption:
16571 @itemize @bullet
16572 @item
16573 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16574 @item
16575 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16576 @item
16577 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16578 @item
16579 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16580 @end itemize
16582 @noindent
16583 For types associated with a Debug_Pool, dynamic allocation is performed using
16584 the standard GNAT allocation routine. References to all allocated chunks of
16585 memory are kept in an internal dictionary. Several deallocation strategies are
16586 provided, whereupon the user can choose to release the memory to the system,
16587 keep it allocated for further invalid access checks, or fill it with an easily
16588 recognizable pattern for debug sessions. The memory pattern is the old IBM
16589 hexadecimal convention: @code{16#DEADBEEF#}.
16591 See the documentation in the file g-debpoo.ads for more information on the
16592 various strategies.
16594 Upon each dereference, a check is made that the access value denotes a
16595 properly allocated memory location. Here is a complete example of use of
16596 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16597 @smallexample @c ada
16598 @iftex
16599 @leftskip=0cm
16600 @end iftex
16601 with Gnat.Io; use Gnat.Io;
16602 with Unchecked_Deallocation;
16603 with Unchecked_Conversion;
16604 with GNAT.Debug_Pools;
16605 with System.Storage_Elements;
16606 with Ada.Exceptions; use Ada.Exceptions;
16607 procedure Debug_Pool_Test is
16609    type T is access Integer;
16610    type U is access all T;
16612    P : GNAT.Debug_Pools.Debug_Pool;
16613    for T'Storage_Pool use P;
16615    procedure Free is new Unchecked_Deallocation (Integer, T);
16616    function UC is new Unchecked_Conversion (U, T);
16617    A, B : aliased T;
16619    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16621 begin
16622    Info (P);
16623    A := new Integer;
16624    B := new Integer;
16625    B := A;
16626    Info (P);
16627    Free (A);
16628    begin
16629       Put_Line (Integer'Image(B.all));
16630    exception
16631       when E : others => Put_Line ("raised: " & Exception_Name (E));
16632    end;
16633    begin
16634       Free (B);
16635    exception
16636       when E : others => Put_Line ("raised: " & Exception_Name (E));
16637    end;
16638    B := UC(A'Access);
16639    begin
16640       Put_Line (Integer'Image(B.all));
16641    exception
16642       when E : others => Put_Line ("raised: " & Exception_Name (E));
16643    end;
16644    begin
16645       Free (B);
16646    exception
16647       when E : others => Put_Line ("raised: " & Exception_Name (E));
16648    end;
16649    Info (P);
16650 end Debug_Pool_Test;
16651 @end smallexample
16653 @noindent
16654 The debug pool mechanism provides the following precise diagnostics on the
16655 execution of this erroneous program:
16656 @smallexample
16657 Debug Pool info:
16658   Total allocated bytes :  0
16659   Total deallocated bytes :  0
16660   Current Water Mark:  0
16661   High Water Mark:  0
16663 Debug Pool info:
16664   Total allocated bytes :  8
16665   Total deallocated bytes :  0
16666   Current Water Mark:  8
16667   High Water Mark:  8
16669 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16670 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16671 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16672 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16673 Debug Pool info:
16674   Total allocated bytes :  8
16675   Total deallocated bytes :  4
16676   Current Water Mark:  4
16677   High Water Mark:  8
16678 @end smallexample
16680 @ifclear vms
16681 @node The gnatmem Tool
16682 @section The @command{gnatmem} Tool
16683 @findex gnatmem
16685 @noindent
16686 The @code{gnatmem} utility monitors dynamic allocation and
16687 deallocation activity in a program, and displays information about
16688 incorrect deallocations and possible sources of memory leaks.
16689 It is designed to work in association with a static runtime library
16690 only and in this context provides three types of information:
16691 @itemize @bullet
16692 @item
16693 General information concerning memory management, such as the total
16694 number of allocations and deallocations, the amount of allocated
16695 memory and the high water mark, i.e.@: the largest amount of allocated
16696 memory in the course of program execution.
16698 @item
16699 Backtraces for all incorrect deallocations, that is to say deallocations
16700 which do not correspond to a valid allocation.
16702 @item
16703 Information on each allocation that is potentially the origin of a memory
16704 leak.
16705 @end itemize
16707 @menu
16708 * Running gnatmem::
16709 * Switches for gnatmem::
16710 * Example of gnatmem Usage::
16711 @end menu
16713 @node Running gnatmem
16714 @subsection Running @code{gnatmem}
16716 @noindent
16717 @code{gnatmem} makes use of the output created by the special version of
16718 allocation and deallocation routines that record call information. This
16719 allows to obtain accurate dynamic memory usage history at a minimal cost to
16720 the execution speed. Note however, that @code{gnatmem} is not supported on
16721 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16722 Solaris and Windows NT/2000/XP (x86).
16724 @noindent
16725 The @code{gnatmem} command has the form
16727 @smallexample
16728 @c    $ gnatmem @ovar{switches} user_program
16729 @c Expanding @ovar macro inline (explanation in macro def comments)
16730       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16731 @end smallexample
16733 @noindent
16734 The program must have been linked with the instrumented version of the
16735 allocation and deallocation routines. This is done by linking with the
16736 @file{libgmem.a} library. For correct symbolic backtrace information,
16737 the user program should be compiled with debugging options
16738 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16740 @smallexample
16741 $ gnatmake -g my_program -largs -lgmem
16742 @end smallexample
16744 @noindent
16745 As library @file{libgmem.a} contains an alternate body for package
16746 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16747 when an executable is linked with library @file{libgmem.a}. It is then not
16748 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16750 @noindent
16751 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16752 This file contains information about all allocations and deallocations
16753 performed by the program. It is produced by the instrumented allocations and
16754 deallocations routines and will be used by @code{gnatmem}.
16756 In order to produce symbolic backtrace information for allocations and
16757 deallocations performed by the GNAT run-time library, you need to use a
16758 version of that library that has been compiled with the @option{-g} switch
16759 (see @ref{Rebuilding the GNAT Run-Time Library}).
16761 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16762 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16763 @option{-i} switch, gnatmem will assume that this file can be found in the
16764 current directory. For example, after you have executed @file{my_program},
16765 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16767 @smallexample
16768 $ gnatmem my_program
16769 @end smallexample
16771 @noindent
16772 This will produce the output with the following format:
16774 *************** debut cc
16775 @smallexample
16776 $ gnatmem my_program
16778 Global information
16779 ------------------
16780    Total number of allocations        :  45
16781    Total number of deallocations      :   6
16782    Final Water Mark (non freed mem)   :  11.29 Kilobytes
16783    High Water Mark                    :  11.40 Kilobytes
16788 Allocation Root # 2
16789 -------------------
16790  Number of non freed allocations    :  11
16791  Final Water Mark (non freed mem)   :   1.16 Kilobytes
16792  High Water Mark                    :   1.27 Kilobytes
16793  Backtrace                          :
16794    my_program.adb:23 my_program.alloc
16798 @end smallexample
16800 The first block of output gives general information. In this case, the
16801 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16802 Unchecked_Deallocation routine occurred.
16804 @noindent
16805 Subsequent paragraphs display  information on all allocation roots.
16806 An allocation root is a specific point in the execution of the program
16807 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16808 construct. This root is represented by an execution backtrace (or subprogram
16809 call stack). By default the backtrace depth for allocations roots is 1, so
16810 that a root corresponds exactly to a source location. The backtrace can
16811 be made deeper, to make the root more specific.
16813 @node Switches for gnatmem
16814 @subsection Switches for @code{gnatmem}
16816 @noindent
16817 @code{gnatmem} recognizes the following switches:
16819 @table @option
16821 @item -q
16822 @cindex @option{-q} (@code{gnatmem})
16823 Quiet. Gives the minimum output needed to identify the origin of the
16824 memory leaks. Omits statistical information.
16826 @item @var{N}
16827 @cindex @var{N} (@code{gnatmem})
16828 N is an integer literal (usually between 1 and 10) which controls the
16829 depth of the backtraces defining allocation root. The default value for
16830 N is 1. The deeper the backtrace, the more precise the localization of
16831 the root. Note that the total number of roots can depend on this
16832 parameter. This parameter must be specified @emph{before} the name of the
16833 executable to be analyzed, to avoid ambiguity.
16835 @item -b n
16836 @cindex @option{-b} (@code{gnatmem})
16837 This switch has the same effect as just depth parameter.
16839 @item -i @var{file}
16840 @cindex @option{-i} (@code{gnatmem})
16841 Do the @code{gnatmem} processing starting from @file{file}, rather than
16842 @file{gmem.out} in the current directory.
16844 @item -m n
16845 @cindex @option{-m} (@code{gnatmem})
16846 This switch causes @code{gnatmem} to mask the allocation roots that have less
16847 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16848 examine even the roots that didn't result in leaks.
16850 @item -s order
16851 @cindex @option{-s} (@code{gnatmem})
16852 This switch causes @code{gnatmem} to sort the allocation roots according to the
16853 specified order of sort criteria, each identified by a single letter. The
16854 currently supported criteria are @code{n, h, w} standing respectively for
16855 number of unfreed allocations, high watermark, and final watermark
16856 corresponding to a specific root. The default order is @code{nwh}.
16858 @end table
16860 @node Example of gnatmem Usage
16861 @subsection Example of @code{gnatmem} Usage
16863 @noindent
16864 The following example shows the use of @code{gnatmem}
16865 on a simple memory-leaking program.
16866 Suppose that we have the following Ada program:
16868 @smallexample @c ada
16869 @group
16870 @cartouche
16871 with Unchecked_Deallocation;
16872 procedure Test_Gm is
16874    type T is array (1..1000) of Integer;
16875    type Ptr is access T;
16876    procedure Free is new Unchecked_Deallocation (T, Ptr);
16877    A : Ptr;
16879    procedure My_Alloc is
16880    begin
16881       A := new T;
16882    end My_Alloc;
16884    procedure My_DeAlloc is
16885       B : Ptr := A;
16886    begin
16887       Free (B);
16888    end My_DeAlloc;
16890 begin
16891    My_Alloc;
16892    for I in 1 .. 5 loop
16893       for J in I .. 5 loop
16894          My_Alloc;
16895       end loop;
16896       My_Dealloc;
16897    end loop;
16898 end;
16899 @end cartouche
16900 @end group
16901 @end smallexample
16903 @noindent
16904 The program needs to be compiled with debugging option and linked with
16905 @code{gmem} library:
16907 @smallexample
16908 $ gnatmake -g test_gm -largs -lgmem
16909 @end smallexample
16911 @noindent
16912 Then we execute the program as usual:
16914 @smallexample
16915 $ test_gm
16916 @end smallexample
16918 @noindent
16919 Then @code{gnatmem} is invoked simply with
16920 @smallexample
16921 $ gnatmem test_gm
16922 @end smallexample
16924 @noindent
16925 which produces the following output (result may vary on different platforms):
16927 @smallexample
16928 Global information
16929 ------------------
16930    Total number of allocations        :  18
16931    Total number of deallocations      :   5
16932    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16933    High Water Mark                    :  56.90 Kilobytes
16935 Allocation Root # 1
16936 -------------------
16937  Number of non freed allocations    :  11
16938  Final Water Mark (non freed mem)   :  42.97 Kilobytes
16939  High Water Mark                    :  46.88 Kilobytes
16940  Backtrace                          :
16941    test_gm.adb:11 test_gm.my_alloc
16943 Allocation Root # 2
16944 -------------------
16945  Number of non freed allocations    :   1
16946  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16947  High Water Mark                    :  10.02 Kilobytes
16948  Backtrace                          :
16949    s-secsta.adb:81 system.secondary_stack.ss_init
16951 Allocation Root # 3
16952 -------------------
16953  Number of non freed allocations    :   1
16954  Final Water Mark (non freed mem)   :  12 Bytes
16955  High Water Mark                    :  12 Bytes
16956  Backtrace                          :
16957    s-secsta.adb:181 system.secondary_stack.ss_init
16958 @end smallexample
16960 @noindent
16961 Note that the GNAT run time contains itself a certain number of
16962 allocations that have no  corresponding deallocation,
16963 as shown here for root #2 and root
16964 #3. This is a normal behavior when the number of non-freed allocations
16965 is one, it allocates dynamic data structures that the run time needs for
16966 the complete lifetime of the program. Note also that there is only one
16967 allocation root in the user program with a single line back trace:
16968 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16969 program shows that 'My_Alloc' is called at 2 different points in the
16970 source (line 21 and line 24). If those two allocation roots need to be
16971 distinguished, the backtrace depth parameter can be used:
16973 @smallexample
16974 $ gnatmem 3 test_gm
16975 @end smallexample
16977 @noindent
16978 which will give the following output:
16980 @smallexample
16981 Global information
16982 ------------------
16983    Total number of allocations        :  18
16984    Total number of deallocations      :   5
16985    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16986    High Water Mark                    :  56.90 Kilobytes
16988 Allocation Root # 1
16989 -------------------
16990  Number of non freed allocations    :  10
16991  Final Water Mark (non freed mem)   :  39.06 Kilobytes
16992  High Water Mark                    :  42.97 Kilobytes
16993  Backtrace                          :
16994    test_gm.adb:11 test_gm.my_alloc
16995    test_gm.adb:24 test_gm
16996    b_test_gm.c:52 main
16998 Allocation Root # 2
16999 -------------------
17000  Number of non freed allocations    :   1
17001  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17002  High Water Mark                    :  10.02 Kilobytes
17003  Backtrace                          :
17004    s-secsta.adb:81  system.secondary_stack.ss_init
17005    s-secsta.adb:283 <system__secondary_stack___elabb>
17006    b_test_gm.c:33   adainit
17008 Allocation Root # 3
17009 -------------------
17010  Number of non freed allocations    :   1
17011  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17012  High Water Mark                    :   3.91 Kilobytes
17013  Backtrace                          :
17014    test_gm.adb:11 test_gm.my_alloc
17015    test_gm.adb:21 test_gm
17016    b_test_gm.c:52 main
17018 Allocation Root # 4
17019 -------------------
17020  Number of non freed allocations    :   1
17021  Final Water Mark (non freed mem)   :  12 Bytes
17022  High Water Mark                    :  12 Bytes
17023  Backtrace                          :
17024    s-secsta.adb:181 system.secondary_stack.ss_init
17025    s-secsta.adb:283 <system__secondary_stack___elabb>
17026    b_test_gm.c:33   adainit
17027 @end smallexample
17029 @noindent
17030 The allocation root #1 of the first example has been split in 2 roots #1
17031 and #3 thanks to the more precise associated backtrace.
17033 @end ifclear
17035 @node Stack Related Facilities
17036 @chapter Stack Related Facilities
17038 @noindent
17039 This chapter describes some useful tools associated with stack
17040 checking and analysis. In
17041 particular, it deals with dynamic and static stack usage measurements.
17043 @menu
17044 * Stack Overflow Checking::
17045 * Static Stack Usage Analysis::
17046 * Dynamic Stack Usage Analysis::
17047 @end menu
17049 @node Stack Overflow Checking
17050 @section Stack Overflow Checking
17051 @cindex Stack Overflow Checking
17052 @cindex -fstack-check
17054 @noindent
17055 For most operating systems, @command{gcc} does not perform stack overflow
17056 checking by default. This means that if the main environment task or
17057 some other task exceeds the available stack space, then unpredictable
17058 behavior will occur. Most native systems offer some level of protection by
17059 adding a guard page at the end of each task stack. This mechanism is usually
17060 not enough for dealing properly with stack overflow situations because
17061 a large local variable could ``jump'' above the guard page.
17062 Furthermore, when the
17063 guard page is hit, there may not be any space left on the stack for executing
17064 the exception propagation code. Enabling stack checking avoids
17065 such situations.
17067 To activate stack checking, compile all units with the gcc option
17068 @option{-fstack-check}. For example:
17070 @smallexample
17071 gcc -c -fstack-check package1.adb
17072 @end smallexample
17074 @noindent
17075 Units compiled with this option will generate extra instructions to check
17076 that any use of the stack (for procedure calls or for declaring local
17077 variables in declare blocks) does not exceed the available stack space.
17078 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17080 For declared tasks, the stack size is controlled by the size
17081 given in an applicable @code{Storage_Size} pragma or by the value specified
17082 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17083 the default size as defined in the GNAT runtime otherwise.
17085 For the environment task, the stack size depends on
17086 system defaults and is unknown to the compiler. Stack checking
17087 may still work correctly if a fixed
17088 size stack is allocated, but this cannot be guaranteed.
17089 @ifclear vms
17090 To ensure that a clean exception is signalled for stack
17091 overflow, set the environment variable
17092 @env{GNAT_STACK_LIMIT} to indicate the maximum
17093 stack area that can be used, as in:
17094 @cindex GNAT_STACK_LIMIT
17096 @smallexample
17097 SET GNAT_STACK_LIMIT 1600
17098 @end smallexample
17100 @noindent
17101 The limit is given in kilobytes, so the above declaration would
17102 set the stack limit of the environment task to 1.6 megabytes.
17103 Note that the only purpose of this usage is to limit the amount
17104 of stack used by the environment task. If it is necessary to
17105 increase the amount of stack for the environment task, then this
17106 is an operating systems issue, and must be addressed with the
17107 appropriate operating systems commands.
17108 @end ifclear
17109 @ifset vms
17110 To have a fixed size stack in the environment task, the stack must be put
17111 in the P0 address space and its size specified.  Use these switches to
17112 create a p0 image:
17114 @smallexample
17115 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17116 @end smallexample
17118 @noindent
17119 The quotes are required to keep case.  The number after @samp{STACK=} is the
17120 size of the environmental task stack in pagelets (512 bytes).  In this example
17121 the stack size is about 2 megabytes.
17123 @noindent
17124 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17125 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17126 more details about the @option{/p0image} qualifier and the @option{stack}
17127 option.
17128 @end ifset
17130 @node Static Stack Usage Analysis
17131 @section Static Stack Usage Analysis
17132 @cindex Static Stack Usage Analysis
17133 @cindex -fstack-usage
17135 @noindent
17136 A unit compiled with @option{-fstack-usage} will generate an extra file
17137 that specifies
17138 the maximum amount of stack used, on a per-function basis.
17139 The file has the same
17140 basename as the target object file with a @file{.su} extension.
17141 Each line of this file is made up of three fields:
17143 @itemize
17144 @item
17145 The name of the function.
17146 @item
17147 A number of bytes.
17148 @item
17149 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17150 @end itemize
17152 The second field corresponds to the size of the known part of the function
17153 frame.
17155 The qualifier @code{static} means that the function frame size
17156 is purely static.
17157 It usually means that all local variables have a static size.
17158 In this case, the second field is a reliable measure of the function stack
17159 utilization.
17161 The qualifier @code{dynamic} means that the function frame size is not static.
17162 It happens mainly when some local variables have a dynamic size. When this
17163 qualifier appears alone, the second field is not a reliable measure
17164 of the function stack analysis. When it is qualified with  @code{bounded}, it
17165 means that the second field is a reliable maximum of the function stack
17166 utilization.
17168 @node Dynamic Stack Usage Analysis
17169 @section Dynamic Stack Usage Analysis
17171 @noindent
17172 It is possible to measure the maximum amount of stack used by a task, by
17173 adding a switch to @command{gnatbind}, as:
17175 @smallexample
17176 $ gnatbind -u0 file
17177 @end smallexample
17179 @noindent
17180 With this option, at each task termination, its stack usage is  output on
17181 @file{stderr}.
17182 It is not always convenient to output the stack usage when the program
17183 is still running. Hence, it is possible to delay this output until program
17184 termination. for a given number of tasks specified as the argument of the
17185 @option{-u} option. For instance:
17187 @smallexample
17188 $ gnatbind -u100 file
17189 @end smallexample
17191 @noindent
17192 will buffer the stack usage information of the first 100 tasks to terminate and
17193 output this info at program termination. Results are displayed in four
17194 columns:
17196 @noindent
17197 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
17199 @noindent
17200 where:
17202 @table @emph
17203 @item Index
17204 is a number associated with each task.
17206 @item Task Name
17207 is the name of the task analyzed.
17209 @item Stack Size
17210 is the maximum size for the stack.
17212 @item Stack Usage
17213 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17214 is not entirely analyzed, and it's not possible to know exactly how
17215 much has actually been used. The report thus contains the theoretical stack usage
17216 (Value) and the possible variation (Variation) around this value.
17218 @end table
17220 @noindent
17221 The environment task stack, e.g., the stack that contains the main unit, is
17222 only processed when the environment variable GNAT_STACK_LIMIT is set.
17225 @c *********************************
17226 @c *            GNATCHECK          *
17227 @c *********************************
17228 @node Verifying Properties Using gnatcheck
17229 @chapter Verifying Properties Using @command{gnatcheck}
17230 @findex gnatcheck
17231 @cindex @command{gnatcheck}
17233 @noindent
17234 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17235 of Ada source files according to a given set of semantic rules.
17236 @cindex ASIS
17238 In order to check compliance with a given rule, @command{gnatcheck} has to
17239 semantically analyze the Ada sources.
17240 Therefore, checks can only be performed on
17241 legal Ada units. Moreover, when a unit depends semantically upon units located
17242 outside the current directory, the source search path has to be provided when
17243 calling @command{gnatcheck}, either through a specified project file or
17244 through @command{gnatcheck} switches as described below.
17246 A number of rules are predefined in @command{gnatcheck} and are described
17247 later in this chapter.
17248 You can also add new rules, by modifying the @command{gnatcheck} code and
17249 rebuilding the tool. In order to add a simple rule making some local checks,
17250 a small amount of straightforward ASIS-based programming is usually needed.
17252 Project support for @command{gnatcheck} is provided by the GNAT
17253 driver (see @ref{The GNAT Driver and Project Files}).
17255 Invoking @command{gnatcheck} on the command line has the form:
17257 @smallexample
17258 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
17259 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17260 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17261 @c Expanding @ovar macro inline (explanation in macro def comments)
17262 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
17263       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17264       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17265 @end smallexample
17267 @noindent
17268 where
17269 @itemize @bullet
17270 @item
17271 @var{switches} specify the general tool options
17273 @item
17274 Each @var{filename} is the name (including the extension) of a source
17275 file to process. ``Wildcards'' are allowed, and
17276 the file name may contain path information.
17278 @item
17279 Each @var{arg_list_filename} is the name (including the extension) of a text
17280 file containing the names of the source files to process, separated by spaces
17281 or line breaks.
17283 @item
17284 @var{gcc_switches} is a list of switches for
17285 @command{gcc}. They will be passed on to all compiler invocations made by
17286 @command{gnatcheck} to generate the ASIS trees. Here you can provide
17287 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17288 and use the @option{-gnatec} switch to set the configuration file,
17289 use the @option{-gnat05} switch if sources should be compiled in
17290 Ada 2005 mode etc.
17292 @item
17293 @var{rule_options} is a list of options for controlling a set of
17294 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
17295 @end itemize
17297 @noindent
17298 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
17299 supplied.
17301 @menu
17302 * Format of the Report File::
17303 * General gnatcheck Switches::
17304 * gnatcheck Rule Options::
17305 * Adding the Results of Compiler Checks to gnatcheck Output::
17306 * Project-Wide Checks::
17307 * Rule exemption::
17308 * Predefined Rules::
17309 * Example of gnatcheck Usage::
17310 @end menu
17312 @node Format of the Report File
17313 @section Format of the Report File
17314 @cindex Report file (for @code{gnatcheck})
17316 @noindent
17317 The @command{gnatcheck} tool outputs on @file{stderr} all messages concerning
17318 rule violations except if running in quiet mode.  It also creates a text file
17319 that contains the complete report of the last gnatcheck run. By default this file
17320 is named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
17321 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
17322 name and/or location of the report file. This report contains:
17324 @itemize @bullet
17326 @item general details of the @command{gnatcheck} run: date and time of the run,
17327 the version of the tool that has generated this report, full parameters
17328 of the  @command{gnatcheck} invocation, reference to the list of checked
17329 sources and applied rules (coding standard);
17330 @item summary of the run (number of checked sources and detected violations);
17331 @item list of exempted coding standard violations;
17332 @item list of non-exempted coding standard violations;
17333 @item list of problems in the definition of exemption sections;
17334 @item list of language violations (compile-time errors) detected in processed sources;
17335 @end itemize
17337 @node General gnatcheck Switches
17338 @section General @command{gnatcheck} Switches
17340 @noindent
17341 The following switches control the general @command{gnatcheck} behavior
17343 @table @option
17344 @c !sort!
17345 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
17346 @item ^-a^/ALL^
17347 Process all units including those with read-only ALI files such as
17348 those from the GNAT Run-Time library.
17350 @ifclear vms
17351 @ignore
17352 @cindex @option{-d} (@command{gnatcheck})
17353 @item -d
17354 Debug mode
17355 @end ignore
17357 @cindex @option{-dd} (@command{gnatcheck})
17358 @item -dd
17359 Progress indicator mode (for use in GPS).
17360 @end ifclear
17362 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
17363 @item ^-h^/HELP^
17364 List the predefined and user-defined rules. For more details see
17365 @ref{Predefined Rules}.
17367 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
17368 @item ^-l^/LOCS^
17369 Use full source locations references in the report file. For a construct from
17370 a generic instantiation a full source location is a chain from the location
17371 of this construct in the generic unit to the place where this unit is
17372 instantiated.
17374 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
17375 @item ^-log^/LOG^
17376 Duplicate all the output sent to @file{stderr} into a log file. The log file
17377 is named @file{gnatcheck.log} and is located in the current directory.
17379 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
17380 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
17381 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
17382 the range 0@dots{}1000;
17383 the default value is 500. Zero means that there is no limitation on
17384 the number of diagnostic messages to be output.
17386 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
17387 @item ^-q^/QUIET^
17388 Quiet mode. All the diagnostics about rule violations are placed in the
17389 @command{gnatcheck} report file only, without duplication on @file{stdout}.
17391 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
17392 @item ^-s^/SHORT^
17393 Short format of the report file (no version information, no list of applied
17394 rules, no list of checked sources is included)
17396 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
17397 @item ^--include-file^/INCLUDE_FILE^
17398 Append the content of the specified text file to the report file
17400 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
17401 @item ^-t^/TIME^
17402 Print out execution time.
17404 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
17405 @item ^-v^/VERBOSE^
17406 Verbose mode; @command{gnatcheck} generates version information and then
17407 a trace of sources being processed.
17409 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
17410 @item ^-o ^/OUTPUT=^@var{report_file}
17411 Set name of report file file to @var{report_file} .
17413 @end table
17415 @node gnatcheck Rule Options
17416 @section @command{gnatcheck} Rule Options
17418 @noindent
17419 The following options control the processing performed by
17420 @command{gnatcheck}.
17422 @table @option
17423 @cindex @option{+ALL} (@command{gnatcheck})
17424 @item +ALL
17425 Turn all the rule checks ON.
17427 @cindex @option{-ALL} (@command{gnatcheck})
17428 @item -ALL
17429 Turn all the rule checks OFF.
17431 @cindex @option{+R} (@command{gnatcheck})
17432 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
17433 Turn on the check for a specified rule with the specified parameter, if any.
17434 @var{rule_id} must be the identifier of one of the currently implemented rules
17435 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
17436 are not case-sensitive. The @var{param} item must
17437 be a string representing a valid parameter(s) for the specified rule.
17438 If it contains any space characters then this string must be enclosed in
17439 quotation marks.
17441 @cindex @option{-R} (@command{gnatcheck})
17442 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
17443 Turn off the check for a specified rule with the specified parameter, if any.
17445 @cindex @option{-from} (@command{gnatcheck})
17446 @item -from=@var{rule_option_filename}
17447 Read the rule options from the text file @var{rule_option_filename}, referred
17448 to as a ``coding standard file'' below.
17450 @end table
17452 @noindent
17453 The default behavior is that all the rule checks are disabled.
17455 A coding standard file is a text file that contains a set of rule options
17456 described above.
17457 @cindex Coding standard file (for @code{gnatcheck})
17458 The file may contain empty lines and Ada-style comments (comment
17459 lines and end-of-line comments). There can be several rule options on a
17460 single line (separated by a space).
17462 A coding standard file may reference other coding standard files by including
17463 more @option{-from=@var{rule_option_filename}}
17464 options, each such option being replaced with the content of the
17465 corresponding coding standard file during processing. In case a
17466 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
17467 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
17468 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
17469 processing fails with an error message.
17472 @node Adding the Results of Compiler Checks to gnatcheck Output
17473 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
17475 @noindent
17476 The @command{gnatcheck} tool can include in the generated diagnostic messages
17477 and in
17478 the report file the results of the checks performed by the compiler. Though
17479 disabled by default, this effect may be obtained by using @option{+R} with
17480 the following rule identifiers and parameters:
17482 @table @option
17483 @item Restrictions
17484 To record restrictions violations (which are performed by the compiler if the
17485 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
17486 use the @code{Restrictions} rule
17487 with the same parameters as pragma
17488 @code{Restrictions} or @code{Restriction_Warnings}.
17490 @item Style_Checks
17491 To record compiler style checks (@pxref{Style Checking}), use the
17492 @code{Style_Checks} rule.
17493 This rule takes a parameter in one of the following forms:
17494 @itemize
17495 @item
17496 @code{All_Checks},
17497 which enables the standard style checks corresponding to the @option{-gnatyy}
17498 GNAT style check option, or
17500 @item
17501 a string with the same
17502 structure and semantics as the @code{string_LITERAL} parameter of the
17503 GNAT pragma @code{Style_Checks}
17504 (for further information about this pragma,
17505 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
17506 @end itemize
17508 @noindent
17509 For example, the
17510 @code{+RStyle_Checks:O} rule option activates
17511 the compiler style check that corresponds to
17512 @code{-gnatyO} style check option.
17514 @item Warnings
17515 To record compiler warnings (@pxref{Warning Message Control}), use the
17516 @code{Warnings} rule with a parameter that is a valid
17517 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
17518 (for further information about this pragma,
17519 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
17520 Note that in case of gnatcheck
17521 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
17522 all the specific warnings, but not suppresses the warning mode,
17523 and 'e' parameter, corresponding to @option{-gnatwe} that means
17524 "treat warnings as errors", does not have any effect.
17526 @end table
17528 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
17529 option with the corresponding restriction name as a parameter. @code{-R} is
17530 not available for @code{Style_Checks} and @code{Warnings} options, to disable
17531 warnings and style checks, use the corresponding warning and style options.
17533 @node Project-Wide Checks
17534 @section Project-Wide Checks
17535 @cindex Project-wide checks (for @command{gnatcheck})
17537 @noindent
17538 In order to perform checks on all units of a given project, you can use
17539 the GNAT driver along with the @option{-P} option:
17540 @smallexample
17541    gnat check -Pproj -rules -from=my_rules
17542 @end smallexample
17544 @noindent
17545 If the project @code{proj} depends upon other projects, you can perform
17546 checks on the project closure using the @option{-U} option:
17547 @smallexample
17548    gnat check -Pproj -U -rules -from=my_rules
17549 @end smallexample
17551 @noindent
17552 Finally, if not all the units are relevant to a particular main
17553 program in the project closure, you can perform checks for the set
17554 of units needed to create a given main program (unit closure) using
17555 the @option{-U} option followed by the name of the main unit:
17556 @smallexample
17557    gnat check -Pproj -U main -rules -from=my_rules
17558 @end smallexample
17561 @node Rule exemption
17562 @section Rule exemption
17563 @cindex Rule exemption (for @command{gnatcheck})
17565 @noindent
17566 One of the most useful applications of @command{gnatcheck} is to
17567 automate the enforcement of project-specific coding standards,
17568 for example in safety-critical systems where particular features
17569 must be restricted in order to simplify the certification effort.
17570 However, it may sometimes be appropriate to violate a coding standard rule,
17571 and in such cases the rationale for the violation should be provided
17572 in the source program itself so that the individuals
17573 reviewing or maintaining the program can immediately understand the intent.
17575 The @command{gnatcheck} tool supports this practice with the notion of
17576 a ``rule exemption'' covering a specific source code section. Normally
17577 rule violation messages are issued both on @file{stderr}
17578 and in a report file. In contrast, exempted violations are not listed on
17579 @file{stderr}; thus users invoking @command{gnatcheck} interactively
17580 (e.g. in its GPS interface) do not need to pay attention to known and
17581 justified violations. However, exempted violations along with their
17582 justification are documented in a special section of the report file that
17583 @command{gnatcheck} generates.
17585 @menu
17586 * Using pragma Annotate to Control Rule Exemption::
17587 * gnatcheck Annotations Rules::
17588 @end menu
17590 @node Using pragma Annotate to Control Rule Exemption
17591 @subsection Using pragma @code{Annotate} to Control Rule Exemption
17592 @cindex Using pragma Annotate to control rule exemption
17594 @noindent
17595 Rule exemption is controlled by pragma @code{Annotate} when its first
17596 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
17597 exemption control annotations is as follows:
17599 @smallexample @c ada
17600 @group
17601 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
17603 @i{exemption_control} ::= Exempt_On | Exempt_Off
17605 @i{Rule_Name}         ::= string_literal
17607 @i{justification}     ::= string_literal
17608 @end group
17609 @end smallexample
17611 @noindent
17612 When a @command{gnatcheck} annotation has more then four arguments,
17613 @command{gnatcheck} issues a warning and ignores the additional arguments.
17614 If the additional arguments do not follow the syntax above,
17615 @command{gnatcheck} emits a warning and ignores the annotation.
17617 The @i{@code{Rule_Name}} argument should be the name of some existing
17618 @command{gnatcheck} rule.
17619 Otherwise a warning message is generated and the pragma is
17620 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
17621 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
17623 A source code section where an exemption is active for a given rule is
17624 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
17626 @smallexample @c ada
17627 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
17628 -- source code section
17629 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
17630 @end smallexample
17633 @node gnatcheck Annotations Rules
17634 @subsection @command{gnatcheck} Annotations Rules
17635 @cindex @command{gnatcheck} annotations rules
17637 @itemize @bullet
17639 @item
17640 An ``Exempt_Off'' annotation can only appear after a corresponding
17641 ``Exempt_On'' annotation.
17643 @item
17644 Exempted source code sections are only based on the source location of the
17645 annotations. Any source construct between the two
17646 annotations is part of the exempted source code section.
17648 @item
17649 Exempted source code sections for different rules are independent. They can
17650 be nested or intersect with one another without limitation.
17651 Creating nested or intersecting source code sections for the same rule is
17652 not allowed.
17654 @item
17655 Malformed exempted source code sections are reported by a warning, and
17656 the corresponding rule exemptions are ignored.
17658 @item
17659 When an exempted source code section does not contain at least one violation
17660 of the exempted rule, a warning is emitted on @file{stderr}.
17662 @item
17663 If an ``Exempt_On'' annotation pragma does not have a matching
17664 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
17665 exemption for the given rule is ignored and a warning is issued.
17666 @end itemize
17669 @node Predefined Rules
17670 @section Predefined Rules
17671 @cindex Predefined rules (for @command{gnatcheck})
17673 @ignore
17674 @c (Jan 2007) Since the global rules are still under development and are not
17675 @c documented, there is no point in explaining the difference between
17676 @c global and local rules
17677 @noindent
17678 A rule in @command{gnatcheck} is either local or global.
17679 A @emph{local rule} is a rule that applies to a well-defined section
17680 of a program and that can be checked by analyzing only this section.
17681 A @emph{global rule} requires analysis of some global properties of the
17682 whole program (mostly related to the program call graph).
17683 As of @value{NOW}, the implementation of global rules should be
17684 considered to be at a preliminary stage. You can use the
17685 @option{+GLOBAL} option to enable all the global rules, and the
17686 @option{-GLOBAL} rule option to disable all the global rules.
17688 All the global rules in the list below are
17689 so indicated by marking them ``GLOBAL''.
17690 This +GLOBAL and -GLOBAL options are not
17691 included in the list of gnatcheck options above, because at the moment they
17692 are considered as a temporary debug options.
17694 @command{gnatcheck} performs rule checks for generic
17695 instances only for global rules.  This limitation may be relaxed in a later
17696 release.
17697 @end ignore
17699 @noindent
17700 The predefined rules implemented in @command{gnatcheck}
17701 are described in a companion document,
17702 @cite{GNATcheck Reference Manual -- Predefined Rules}.
17703 The rule identifier is
17704 used as a parameter of @command{gnatcheck}'s @option{+R} or @option{-R}
17705 switches.
17708 @node Example of gnatcheck Usage
17709 @section Example of @command{gnatcheck} Usage
17711 @noindent
17712 Here is a simple example. Suppose that in the current directory we have a
17713 project file named @file{gnatcheck_example.gpr} with the following content:
17715 @smallexample @c projectfile
17716 project Gnatcheck_Example is
17718    for Source_Dirs use ("src");
17719    for Object_Dir use "obj";
17720    for Main use ("main.adb");
17722    package Check is
17723       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
17724    end Check;
17726 end Gnatcheck_Example;
17727 @end smallexample
17729 @noindent
17730 And the file named @file{coding_standard} is also located in the current
17731 directory and has the following content:
17733 @smallexample
17734 -----------------------------------------------------
17735 -- This is a sample gnatcheck coding standard file --
17736 -----------------------------------------------------
17738 --  First, turning on rules, that are directly implemented in gnatcheck
17739 +RAbstract_Type_Declarations
17740 +RAnonymous_Arrays
17741 +RLocal_Packages
17742 +RFloat_Equality_Checks
17743 +REXIT_Statements_With_No_Loop_Name
17745 --  Then, activating compiler checks of interest:
17746 +RStyle_Checks:e
17747 --  This style check checks if a unit name is present on END keyword that
17748 --  is the end of the unit declaration
17749 @end smallexample
17751 @noindent
17752 And the subdirectory @file{src} contains the following Ada sources:
17754 @file{pack.ads}:
17756 @smallexample @c ada
17757 package Pack is
17758    type T is abstract tagged private;
17759    procedure P (X : T) is abstract;
17761    package Inner is
17762       type My_Float is digits 8;
17763       function Is_Equal (L, R : My_Float) return Boolean;
17764    end Inner;
17765 private
17766    type T is abstract tagged null record;
17767 end;
17768 @end smallexample
17770 @noindent
17771 @file{pack.adb}:
17773 @smallexample @c ada
17774 package body Pack is
17775    package body Inner is
17776       function Is_Equal (L, R : My_Float) return Boolean is
17777       begin
17778          return L = R;
17779       end;
17780    end Inner;
17781 end Pack;
17782 @end smallexample
17784 @noindent
17785 and @file{main.adb}
17787 @smallexample @c ada
17788 with Pack; use Pack;
17789 procedure Main is
17791    pragma Annotate
17792      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
17793    Float_Array : array (1 .. 10) of Inner.My_Float;
17794    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
17796    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
17798    use Inner;
17800    B : Boolean := False;
17802 begin
17803    for J in Float_Array'Range loop
17804       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
17805          B := True;
17806          exit;
17807       end if;
17808    end loop;
17809 end Main;
17810 @end smallexample
17812 @noindent
17813 And suppose we call @command{gnatcheck} from the current directory using
17814 the @command{gnat} driver:
17816 @smallexample
17817    gnat check -Pgnatcheck_example.gpr
17818 @end smallexample
17820 @noindent
17821 As a result, @command{gnatcheck} is called to check all the files from the
17822 project @file{gnatcheck_example.gpr} using the coding standard defined by
17823 the file @file{coding_standard}. As the result, the @command{gnatcheck}
17824 report file named @file{gnatcheck.out} will be created in the current
17825 directory, and it will have the following content:
17827 @smallexample
17828 RULE CHECKING REPORT
17830 1. OVERVIEW
17832 Date and time of execution: 2009.10.28 14:17
17833 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
17834 Command line:
17836 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
17838 Coding standard (applied rules):
17839    Abstract_Type_Declarations
17840    Anonymous_Arrays
17841    EXIT_Statements_With_No_Loop_Name
17842    Float_Equality_Checks
17843    Local_Packages
17845    Compiler style checks: -gnatye
17847 Number of coding standard violations: 6
17848 Number of exempted coding standard violations: 1
17850 2. DETECTED RULE VIOLATIONS
17852 2.1. NON-EXEMPTED VIOLATIONS
17854 Source files with non-exempted violations
17855    pack.ads
17856    pack.adb
17857    main.adb
17859 List of violations grouped by files, and ordered by increasing source location:
17861 pack.ads:2:4: declaration of abstract type
17862 pack.ads:5:4: declaration of local package
17863 pack.ads:10:30: declaration of abstract type
17864 pack.ads:11:1: (style) "end Pack" required
17865 pack.adb:5:19: use of equality operation for float values
17866 pack.adb:6:7: (style) "end Is_Equal" required
17867 main.adb:9:26: anonymous array type
17868 main.adb:19:10: exit statement with no loop name
17870 2.2. EXEMPTED VIOLATIONS
17872 Source files with exempted violations
17873    main.adb
17875 List of violations grouped by files, and ordered by increasing source location:
17877 main.adb:6:18: anonymous array type
17878    (this one is fine)
17880 2.3. SOURCE FILES WITH NO VIOLATION
17882    No files without violations
17884 END OF REPORT
17885 @end smallexample
17888 @c *********************************
17889 @node Creating Sample Bodies Using gnatstub
17890 @chapter Creating Sample Bodies Using @command{gnatstub}
17891 @findex gnatstub
17893 @noindent
17894 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17895 for library unit declarations.
17897 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17898 driver (see @ref{The GNAT Driver and Project Files}).
17900 To create a body stub, @command{gnatstub} has to compile the library
17901 unit declaration. Therefore, bodies can be created only for legal
17902 library units. Moreover, if a library unit depends semantically upon
17903 units located outside the current directory, you have to provide
17904 the source search path when calling @command{gnatstub}, see the description
17905 of @command{gnatstub} switches below.
17907 By default, all the program unit body stubs generated by @code{gnatstub}
17908 raise the predefined @code{Program_Error} exception, which will catch
17909 accidental calls of generated stubs. This behavior can be changed with
17910 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17912 @menu
17913 * Running gnatstub::
17914 * Switches for gnatstub::
17915 @end menu
17917 @node Running gnatstub
17918 @section Running @command{gnatstub}
17920 @noindent
17921 @command{gnatstub} has the command-line interface of the form
17923 @smallexample
17924 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17925 @c Expanding @ovar macro inline (explanation in macro def comments)
17926 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17927 @end smallexample
17929 @noindent
17930 where
17931 @table @var
17932 @item filename
17933 is the name of the source file that contains a library unit declaration
17934 for which a body must be created. The file name may contain the path
17935 information.
17936 The file name does not have to follow the GNAT file name conventions. If the
17937 name
17938 does not follow GNAT file naming conventions, the name of the body file must
17939 be provided
17940 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17941 If the file name follows the GNAT file naming
17942 conventions and the name of the body file is not provided,
17943 @command{gnatstub}
17944 creates the name
17945 of the body file from the argument file name by replacing the @file{.ads}
17946 suffix
17947 with the @file{.adb} suffix.
17949 @item directory
17950 indicates the directory in which the body stub is to be placed (the default
17951 is the
17952 current directory)
17954 @item @samp{@var{gcc_switches}} is a list of switches for
17955 @command{gcc}. They will be passed on to all compiler invocations made by
17956 @command{gnatelim} to generate the ASIS trees. Here you can provide
17957 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17958 use the @option{-gnatec} switch to set the configuration file,
17959 use the @option{-gnat05} switch if sources should be compiled in
17960 Ada 2005 mode etc.
17962 @item switches
17963 is an optional sequence of switches as described in the next section
17964 @end table
17966 @node Switches for gnatstub
17967 @section Switches for @command{gnatstub}
17969 @table @option
17970 @c !sort!
17972 @item ^-f^/FULL^
17973 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17974 If the destination directory already contains a file with the name of the
17975 body file
17976 for the argument spec file, replace it with the generated body stub.
17978 @item ^-hs^/HEADER=SPEC^
17979 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17980 Put the comment header (i.e., all the comments preceding the
17981 compilation unit) from the source of the library unit declaration
17982 into the body stub.
17984 @item ^-hg^/HEADER=GENERAL^
17985 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17986 Put a sample comment header into the body stub.
17988 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17989 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17990 Use the content of the file as the comment header for a generated body stub.
17992 @ifclear vms
17993 @item -IDIR
17994 @cindex @option{-IDIR} (@command{gnatstub})
17995 @itemx -I-
17996 @cindex @option{-I-} (@command{gnatstub})
17997 @end ifclear
17998 @ifset vms
17999 @item /NOCURRENT_DIRECTORY
18000 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18001 @end ifset
18002 ^These switches have ^This switch has^ the same meaning as in calls to
18003 @command{gcc}.
18004 ^They define ^It defines ^ the source search path in the call to
18005 @command{gcc} issued
18006 by @command{gnatstub} to compile an argument source file.
18008 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18009 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18010 This switch has the same meaning as in calls to @command{gcc}.
18011 It defines the additional configuration file to be passed to the call to
18012 @command{gcc} issued
18013 by @command{gnatstub} to compile an argument source file.
18015 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18016 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18017 (@var{n} is a non-negative integer). Set the maximum line length in the
18018 body stub to @var{n}; the default is 79. The maximum value that can be
18019 specified is 32767. Note that in the special case of configuration
18020 pragma files, the maximum is always 32767 regardless of whether or
18021 not this switch appears.
18023 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18024 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18025 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18026 the generated body sample to @var{n}.
18027 The default indentation is 3.
18029 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18030 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18031 Order local bodies alphabetically. (By default local bodies are ordered
18032 in the same way as the corresponding local specs in the argument spec file.)
18034 @item ^-i^/INDENTATION=^@var{n}
18035 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18036 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18038 @item ^-k^/TREE_FILE=SAVE^
18039 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18040 Do not remove the tree file (i.e., the snapshot of the compiler internal
18041 structures used by @command{gnatstub}) after creating the body stub.
18043 @item ^-l^/LINE_LENGTH=^@var{n}
18044 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18045 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18047 @item ^--no-exception^/NO_EXCEPTION^
18048 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
18049 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18050 This is not always possible for function stubs.
18052 @item ^--no-local-header^/NO_LOCAL_HEADER^
18053 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
18054 Do not place local comment header with unit name before body stub for a
18055 unit.
18057 @item ^-o ^/BODY=^@var{body-name}
18058 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18059 Body file name.  This should be set if the argument file name does not
18060 follow
18061 the GNAT file naming
18062 conventions. If this switch is omitted the default name for the body will be
18063 obtained
18064 from the argument file name according to the GNAT file naming conventions.
18066 @item ^-q^/QUIET^
18067 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18068 Quiet mode: do not generate a confirmation when a body is
18069 successfully created, and do not generate a message when a body is not
18070 required for an
18071 argument unit.
18073 @item ^-r^/TREE_FILE=REUSE^
18074 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18075 Reuse the tree file (if it exists) instead of creating it.  Instead of
18076 creating the tree file for the library unit declaration, @command{gnatstub}
18077 tries to find it in the current directory and use it for creating
18078 a body. If the tree file is not found, no body is created. This option
18079 also implies @option{^-k^/SAVE^}, whether or not
18080 the latter is set explicitly.
18082 @item ^-t^/TREE_FILE=OVERWRITE^
18083 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18084 Overwrite the existing tree file.  If the current directory already
18085 contains the file which, according to the GNAT file naming rules should
18086 be considered as a tree file for the argument source file,
18087 @command{gnatstub}
18088 will refuse to create the tree file needed to create a sample body
18089 unless this option is set.
18091 @item ^-v^/VERBOSE^
18092 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18093 Verbose mode: generate version information.
18095 @end table
18097 @c *********************************
18098 @node Generating Ada Bindings for C and C++ headers
18099 @chapter Generating Ada Bindings for C and C++ headers
18100 @findex binding
18102 @noindent
18103 GNAT now comes with a binding generator for C and C++ headers which is
18104 intended to do 95% of the tedious work of generating Ada specs from C
18105 or C++ header files.
18107 Note that this capability is not intended to generate 100% correct Ada specs,
18108 and will is some cases require manual adjustments, although it can often
18109 be used out of the box in practice.
18111 Some of the known limitations include:
18113 @itemize @bullet
18114 @item only very simple character constant macros are translated into Ada
18115 constants. Function macros (macros with arguments) are partially translated
18116 as comments, to be completed manually if needed.
18117 @item some extensions (e.g. vector types) are not supported
18118 @item pointers to pointers or complex structures are mapped to System.Address
18119 @item identifiers with identical name (except casing) will generate compilation
18120       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
18121 @end itemize
18123 The code generated is using the Ada 2005 syntax, which makes it
18124 easier to interface with other languages than previous versions of Ada.
18126 @menu
18127 * Running the binding generator::
18128 * Generating bindings for C++ headers::
18129 * Switches::
18130 @end menu
18132 @node Running the binding generator
18133 @section Running the binding generator
18135 @noindent
18136 The binding generator is part of the @command{gcc} compiler and can be
18137 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18138 spec files for the header files specified on the command line, and all
18139 header files needed by these files transitivitely. For example:
18141 @smallexample
18142 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18143 $ gcc -c -gnat05 *.ads
18144 @end smallexample
18146 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18147 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18148 correspond to the files @file{/usr/include/time.h},
18149 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18150 mode these Ada specs.
18152 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18153 and will attempt to generate corresponding Ada comments.
18155 If you want to generate a single Ada file and not the transitive closure, you
18156 can use instead the @option{-fdump-ada-spec-slim} switch.
18158 Note that we recommend when possible to use the @command{g++} driver to
18159 generate bindings, even for most C headers, since this will in general
18160 generate better Ada specs. For generating bindings for C++ headers, it is
18161 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18162 is equivalent in this case. If @command{g++} cannot work on your C headers
18163 because of incompatibilities between C and C++, then you can fallback to
18164 @command{gcc} instead.
18166 For an example of better bindings generated from the C++ front-end,
18167 the name of the parameters (when available) are actually ignored by the C
18168 front-end. Consider the following C header:
18170 @smallexample
18171 extern void foo (int variable);
18172 @end smallexample
18174 with the C front-end, @code{variable} is ignored, and the above is handled as:
18176 @smallexample
18177 extern void foo (int);
18178 @end smallexample
18180 generating a generic:
18182 @smallexample
18183 procedure foo (param1 : int);
18184 @end smallexample
18186 with the C++ front-end, the name is available, and we generate:
18188 @smallexample
18189 procedure foo (variable : int);
18190 @end smallexample
18192 In some cases, the generated bindings will be more complete or more meaningful
18193 when defining some macros, which you can do via the @option{-D} switch. This
18194 is for example the case with @file{Xlib.h} under GNU/Linux:
18196 @smallexample
18197 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18198 @end smallexample
18200 The above will generate more complete bindings than a straight call without
18201 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18203 In other cases, it is not possible to parse a header file in a stand alone
18204 manner, because other include files need to be included first. In this
18205 case, the solution is to create a small header file including the needed
18206 @code{#include} and possible @code{#define} directives. For example, to
18207 generate Ada bindings for @file{readline/readline.h}, you need to first
18208 include @file{stdio.h}, so you can create a file with the following two
18209 lines in e.g. @file{readline1.h}:
18211 @smallexample
18212 #include <stdio.h>
18213 #include <readline/readline.h>
18214 @end smallexample
18216 and then generate Ada bindings from this file:
18218 @smallexample
18219 $ g++ -c -fdump-ada-spec readline1.h
18220 @end smallexample
18222 @node Generating bindings for C++ headers
18223 @section Generating bindings for C++ headers
18225 @noindent
18226 Generating bindings for C++ headers is done using the same options, always
18227 with the @command{g++} compiler.
18229 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18230 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18231 multiple inheritance of abstract classes will be mapped to Ada interfaces
18232 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18233 information on interfacing to C++).
18235 For example, given the following C++ header file:
18237 @smallexample
18238 @group
18239 @cartouche
18240 class Carnivore @{
18241 public:
18242    virtual int Number_Of_Teeth () = 0;
18245 class Domestic @{
18246 public:
18247    virtual void Set_Owner (char* Name) = 0;
18250 class Animal @{
18251 public:
18252   int Age_Count;
18253   virtual void Set_Age (int New_Age);
18256 class Dog : Animal, Carnivore, Domestic @{
18257  public:
18258   int  Tooth_Count;
18259   char *Owner;
18261   virtual int  Number_Of_Teeth ();
18262   virtual void Set_Owner (char* Name);
18264   Dog();
18266 @end cartouche
18267 @end group
18268 @end smallexample
18270 The corresponding Ada code is generated:
18272 @smallexample @c ada
18273 @group
18274 @cartouche
18275   package Class_Carnivore is
18276     type Carnivore is limited interface;
18277     pragma Import (CPP, Carnivore);
18279     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18280   end;
18281   use Class_Carnivore;
18283   package Class_Domestic is
18284     type Domestic is limited interface;
18285     pragma Import (CPP, Domestic);
18287     procedure Set_Owner
18288       (this : access Domestic;
18289        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18290   end;
18291   use Class_Domestic;
18293   package Class_Animal is
18294     type Animal is tagged limited record
18295       Age_Count : aliased int;
18296     end record;
18297     pragma Import (CPP, Animal);
18299     procedure Set_Age (this : access Animal; New_Age : int);
18300     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18301   end;
18302   use Class_Animal;
18304   package Class_Dog is
18305     type Dog is new Animal and Carnivore and Domestic with record
18306       Tooth_Count : aliased int;
18307       Owner : Interfaces.C.Strings.chars_ptr;
18308     end record;
18309     pragma Import (CPP, Dog);
18311     function Number_Of_Teeth (this : access Dog) return int;
18312     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18314     procedure Set_Owner
18315       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18316     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18318     function New_Dog return Dog;
18319     pragma CPP_Constructor (New_Dog);
18320     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18321   end;
18322   use Class_Dog;
18323 @end cartouche
18324 @end group
18325 @end smallexample
18327 @node Switches
18328 @section Switches
18330 @table @option
18331 @item -fdump-ada-spec
18332 @cindex @option{-fdump-ada-spec} (@command{gcc})
18333 Generate Ada spec files for the given header files transitively (including
18334 all header files that these headers depend upon).
18336 @item -fdump-ada-spec-slim
18337 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18338 Generate Ada spec files for the header files specified on the command line
18339 only.
18341 @item -C
18342 @cindex @option{-C} (@command{gcc})
18343 Extract comments from headers and generate Ada comments in the Ada spec files.
18344 @end table
18346 @node Other Utility Programs
18347 @chapter Other Utility Programs
18349 @noindent
18350 This chapter discusses some other utility programs available in the Ada
18351 environment.
18353 @menu
18354 * Using Other Utility Programs with GNAT::
18355 * The External Symbol Naming Scheme of GNAT::
18356 * Converting Ada Files to html with gnathtml::
18357 * Installing gnathtml::
18358 @ifset vms
18359 * LSE::
18360 * Profiling::
18361 @end ifset
18362 @end menu
18364 @node Using Other Utility Programs with GNAT
18365 @section Using Other Utility Programs with GNAT
18367 @noindent
18368 The object files generated by GNAT are in standard system format and in
18369 particular the debugging information uses this format. This means
18370 programs generated by GNAT can be used with existing utilities that
18371 depend on these formats.
18373 @ifclear vms
18374 In general, any utility program that works with C will also often work with
18375 Ada programs generated by GNAT. This includes software utilities such as
18376 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18377 as Purify.
18378 @end ifclear
18380 @node The External Symbol Naming Scheme of GNAT
18381 @section The External Symbol Naming Scheme of GNAT
18383 @noindent
18384 In order to interpret the output from GNAT, when using tools that are
18385 originally intended for use with other languages, it is useful to
18386 understand the conventions used to generate link names from the Ada
18387 entity names.
18389 All link names are in all lowercase letters. With the exception of library
18390 procedure names, the mechanism used is simply to use the full expanded
18391 Ada name with dots replaced by double underscores. For example, suppose
18392 we have the following package spec:
18394 @smallexample @c ada
18395 @group
18396 @cartouche
18397 package QRS is
18398    MN : Integer;
18399 end QRS;
18400 @end cartouche
18401 @end group
18402 @end smallexample
18404 @noindent
18405 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18406 the corresponding link name is @code{qrs__mn}.
18407 @findex Export
18408 Of course if a @code{pragma Export} is used this may be overridden:
18410 @smallexample @c ada
18411 @group
18412 @cartouche
18413 package Exports is
18414    Var1 : Integer;
18415    pragma Export (Var1, C, External_Name => "var1_name");
18416    Var2 : Integer;
18417    pragma Export (Var2, C, Link_Name => "var2_link_name");
18418 end Exports;
18419 @end cartouche
18420 @end group
18421 @end smallexample
18423 @noindent
18424 In this case, the link name for @var{Var1} is whatever link name the
18425 C compiler would assign for the C function @var{var1_name}. This typically
18426 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18427 system conventions, but other possibilities exist. The link name for
18428 @var{Var2} is @var{var2_link_name}, and this is not operating system
18429 dependent.
18431 @findex _main
18432 One exception occurs for library level procedures. A potential ambiguity
18433 arises between the required name @code{_main} for the C main program,
18434 and the name we would otherwise assign to an Ada library level procedure
18435 called @code{Main} (which might well not be the main program).
18437 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18438 names. So if we have a library level procedure such as
18440 @smallexample @c ada
18441 @group
18442 @cartouche
18443 procedure Hello (S : String);
18444 @end cartouche
18445 @end group
18446 @end smallexample
18448 @noindent
18449 the external name of this procedure will be @var{_ada_hello}.
18452 @node Converting Ada Files to html with gnathtml
18453 @section Converting Ada Files to HTML with @code{gnathtml}
18455 @noindent
18456 This @code{Perl} script allows Ada source files to be browsed using
18457 standard Web browsers. For installation procedure, see the section
18458 @xref{Installing gnathtml}.
18460 Ada reserved keywords are highlighted in a bold font and Ada comments in
18461 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18462 switch to suppress the generation of cross-referencing information, user
18463 defined variables and types will appear in a different color; you will
18464 be able to click on any identifier and go to its declaration.
18466 The command line is as follow:
18467 @smallexample
18468 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18469 @c Expanding @ovar macro inline (explanation in macro def comments)
18470 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18471 @end smallexample
18473 @noindent
18474 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18475 an html file for every ada file, and a global file called @file{index.htm}.
18476 This file is an index of every identifier defined in the files.
18478 The available ^switches^options^ are the following ones:
18480 @table @option
18481 @item -83
18482 @cindex @option{-83} (@code{gnathtml})
18483 Only the Ada 83 subset of keywords will be highlighted.
18485 @item -cc @var{color}
18486 @cindex @option{-cc} (@code{gnathtml})
18487 This option allows you to change the color used for comments. The default
18488 value is green. The color argument can be any name accepted by html.
18490 @item -d
18491 @cindex @option{-d} (@code{gnathtml})
18492 If the Ada files depend on some other files (for instance through
18493 @code{with} clauses, the latter files will also be converted to html.
18494 Only the files in the user project will be converted to html, not the files
18495 in the run-time library itself.
18497 @item -D
18498 @cindex @option{-D} (@code{gnathtml})
18499 This command is the same as @option{-d} above, but @command{gnathtml} will
18500 also look for files in the run-time library, and generate html files for them.
18502 @item -ext @var{extension}
18503 @cindex @option{-ext} (@code{gnathtml})
18504 This option allows you to change the extension of the generated HTML files.
18505 If you do not specify an extension, it will default to @file{htm}.
18507 @item -f
18508 @cindex @option{-f} (@code{gnathtml})
18509 By default, gnathtml will generate html links only for global entities
18510 ('with'ed units, global variables and types,@dots{}).  If you specify
18511 @option{-f} on the command line, then links will be generated for local
18512 entities too.
18514 @item -l @var{number}
18515 @cindex @option{-l} (@code{gnathtml})
18516 If this ^switch^option^ is provided and @var{number} is not 0, then
18517 @code{gnathtml} will number the html files every @var{number} line.
18519 @item -I @var{dir}
18520 @cindex @option{-I} (@code{gnathtml})
18521 Specify a directory to search for library files (@file{.ALI} files) and
18522 source files. You can provide several -I switches on the command line,
18523 and the directories will be parsed in the order of the command line.
18525 @item -o @var{dir}
18526 @cindex @option{-o} (@code{gnathtml})
18527 Specify the output directory for html files. By default, gnathtml will
18528 saved the generated html files in a subdirectory named @file{html/}.
18530 @item -p @var{file}
18531 @cindex @option{-p} (@code{gnathtml})
18532 If you are using Emacs and the most recent Emacs Ada mode, which provides
18533 a full Integrated Development Environment for compiling, checking,
18534 running and debugging applications, you may use @file{.gpr} files
18535 to give the directories where Emacs can find sources and object files.
18537 Using this ^switch^option^, you can tell gnathtml to use these files.
18538 This allows you to get an html version of your application, even if it
18539 is spread over multiple directories.
18541 @item -sc @var{color}
18542 @cindex @option{-sc} (@code{gnathtml})
18543 This ^switch^option^ allows you to change the color used for symbol
18544 definitions.
18545 The default value is red. The color argument can be any name accepted by html.
18547 @item -t @var{file}
18548 @cindex @option{-t} (@code{gnathtml})
18549 This ^switch^option^ provides the name of a file. This file contains a list of
18550 file names to be converted, and the effect is exactly as though they had
18551 appeared explicitly on the command line. This
18552 is the recommended way to work around the command line length limit on some
18553 systems.
18555 @end table
18557 @node Installing gnathtml
18558 @section Installing @code{gnathtml}
18560 @noindent
18561 @code{Perl} needs to be installed on your machine to run this script.
18562 @code{Perl} is freely available for almost every architecture and
18563 Operating System via the Internet.
18565 On Unix systems, you  may want to modify  the  first line of  the script
18566 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18567 is. The syntax of this line is:
18568 @smallexample
18569 #!full_path_name_to_perl
18570 @end smallexample
18572 @noindent
18573 Alternatively, you may run the script using the following command line:
18575 @smallexample
18576 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18577 @c Expanding @ovar macro inline (explanation in macro def comments)
18578 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18579 @end smallexample
18581 @ifset vms
18582 @node LSE
18583 @section LSE
18584 @findex LSE
18586 @noindent
18587 The GNAT distribution provides an Ada 95 template for the HP Language
18588 Sensitive Editor (LSE), a component of DECset. In order to
18589 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18591 @node Profiling
18592 @section Profiling
18593 @findex PCA
18595 @noindent
18596 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18597 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18598 the collection phase with the /DEBUG qualifier.
18600 @smallexample
18601 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18602 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18603 $ RUN/DEBUG <PROGRAM_NAME>
18604 @end smallexample
18605 @noindent
18606 @end ifset
18608 @ifclear vms
18609 @c ******************************
18610 @node Code Coverage and Profiling
18611 @chapter Code Coverage and Profiling
18612 @cindex Code Coverage
18613 @cindex Profiling
18615 @noindent
18616 This chapter describes how to use @code{gcov} - coverage testing tool - and
18617 @code{gprof} - profiler tool - on your Ada programs.
18619 @menu
18620 * Code Coverage of Ada Programs using gcov::
18621 * Profiling an Ada Program using gprof::
18622 @end menu
18624 @node Code Coverage of Ada Programs using gcov
18625 @section Code Coverage of Ada Programs using gcov
18626 @cindex gcov
18627 @cindex -fprofile-arcs
18628 @cindex -ftest-coverage
18629 @cindex -coverage
18630 @cindex Code Coverage
18632 @noindent
18633 @code{gcov} is a test coverage program: it analyzes the execution of a given
18634 program on selected tests, to help you determine the portions of the program
18635 that are still untested.
18637 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18638 User's Guide. You can refer to this documentation for a more complete
18639 description.
18641 This chapter provides a quick startup guide, and
18642 details some Gnat-specific features.
18644 @menu
18645 * Quick startup guide::
18646 * Gnat specifics::
18647 @end menu
18649 @node Quick startup guide
18650 @subsection Quick startup guide
18652 In order to perform coverage analysis of a program using @code{gcov}, 3
18653 steps are needed:
18655 @itemize @bullet
18656 @item
18657 Code instrumentation during the compilation process
18658 @item
18659 Execution of the instrumented program
18660 @item
18661 Execution of the @code{gcov} tool to generate the result.
18662 @end itemize
18664 The code instrumentation needed by gcov is created at the object level:
18665 The source code is not modified in any way, because the instrumentation code is
18666 inserted by gcc during the compilation process. To compile your code with code
18667 coverage activated, you need to recompile your whole project using the
18668 switches
18669 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18670 @code{-fprofile-arcs}.
18672 @smallexample
18673 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18674    -largs -fprofile-arcs
18675 @end smallexample
18677 This compilation process will create @file{.gcno} files together with
18678 the usual object files.
18680 Once the program is compiled with coverage instrumentation, you can
18681 run it as many times as needed - on portions of a test suite for
18682 example. The first execution will produce @file{.gcda} files at the
18683 same location as the @file{.gcno} files.  The following executions
18684 will update those files, so that a cumulative result of the covered
18685 portions of the program is generated.
18687 Finally, you need to call the @code{gcov} tool. The different options of
18688 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18690 This will create annotated source files with a @file{.gcov} extension:
18691 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18693 @node Gnat specifics
18694 @subsection Gnat specifics
18696 Because Ada semantics, portions of the source code may be shared among
18697 several object files. This is the case for example when generics are
18698 involved, when inlining is active  or when declarations generate  initialisation
18699 calls. In order to take
18700 into account this shared code, you need to call @code{gcov} on all
18701 source files of the tested program at once.
18703 The list of source files might exceed the system's maximum command line
18704 length. In order to bypass this limitation, a new mechanism has been
18705 implemented in @code{gcov}: you can now list all your project's files into a
18706 text file, and provide this file to gcov as a parameter,  preceded by a @@
18707 (e.g. @samp{gcov @@mysrclist.txt}).
18709 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18710 not supported as there can be unresolved symbols during the final link.
18712 @node Profiling an Ada Program using gprof
18713 @section Profiling an Ada Program using gprof
18714 @cindex gprof
18715 @cindex -pg
18716 @cindex Profiling
18718 @noindent
18719 This section is not meant to be an exhaustive documentation of @code{gprof}.
18720 Full documentation for it can be found in the GNU Profiler User's Guide
18721 documentation that is part of this GNAT distribution.
18723 Profiling a program helps determine the parts of a program that are executed
18724 most often, and are therefore the most time-consuming.
18726 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18727 better handle Ada programs and multitasking.
18728 It is currently supported on the following platforms
18729 @itemize @bullet
18730 @item
18731 linux x86/x86_64
18732 @item
18733 solaris sparc/sparc64/x86
18734 @item
18735 windows x86
18736 @end itemize
18738 @noindent
18739 In order to profile a program using @code{gprof}, 3 steps are needed:
18741 @itemize @bullet
18742 @item
18743 Code instrumentation, requiring a full recompilation of the project with the
18744 proper switches.
18745 @item
18746 Execution of the program under the analysis conditions, i.e. with the desired
18747 input.
18748 @item
18749 Analysis of the results using the @code{gprof} tool.
18750 @end itemize
18752 @noindent
18753 The following sections detail the different steps, and indicate how
18754 to interpret the results:
18755 @menu
18756 * Compilation for profiling::
18757 * Program execution::
18758 * Running gprof::
18759 * Interpretation of profiling results::
18760 @end menu
18762 @node Compilation for profiling
18763 @subsection Compilation for profiling
18764 @cindex -pg
18765 @cindex Profiling
18767 In order to profile a program the first step is to tell the compiler
18768 to generate the necessary profiling information. The compiler switch to be used
18769 is @code{-pg}, which must be added to other compilation switches. This
18770 switch needs to be specified both during compilation and link stages, and can
18771 be specified once when using gnatmake:
18773 @smallexample
18774 gnatmake -f -pg -P my_project
18775 @end smallexample
18777 @noindent
18778 Note that only the objects that were compiled with the @samp{-pg} switch will
18779 be profiled; if you need to profile your whole project, use the @samp{-f}
18780 gnatmake switch to force full recompilation.
18782 @node Program execution
18783 @subsection Program execution
18785 @noindent
18786 Once the program has been compiled for profiling, you can run it as usual.
18788 The only constraint imposed by profiling is that the program must terminate
18789 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18790 properly analyzed.
18792 Once the program completes execution, a data file called @file{gmon.out} is
18793 generated in the directory where the program was launched from. If this file
18794 already exists, it will be overwritten.
18796 @node Running gprof
18797 @subsection Running gprof
18799 @noindent
18800 The @code{gprof} tool is called as follow:
18802 @smallexample
18803 gprof my_prog gmon.out
18804 @end smallexample
18806 @noindent
18807 or simpler:
18809 @smallexample
18810 gprof my_prog
18811 @end smallexample
18813 @noindent
18814 The complete form of the gprof command line is the following:
18816 @smallexample
18817 gprof [^switches^options^] [executable [data-file]]
18818 @end smallexample
18820 @noindent
18821 @code{gprof} supports numerous ^switch^options^. The order of these
18822 ^switch^options^ does not matter. The full list of options can be found in
18823 the GNU Profiler User's Guide documentation that comes with this documentation.
18825 The following is the subset of those switches that is most relevant:
18827 @table @option
18829 @item --demangle[=@var{style}]
18830 @itemx --no-demangle
18831 @cindex @option{--demangle} (@code{gprof})
18832 These options control whether symbol names should be demangled when
18833 printing output.  The default is to demangle C++ symbols.  The
18834 @code{--no-demangle} option may be used to turn off demangling. Different
18835 compilers have different mangling styles.  The optional demangling style
18836 argument can be used to choose an appropriate demangling style for your
18837 compiler, in particular Ada symbols generated by GNAT can be demangled using
18838 @code{--demangle=gnat}.
18840 @item -e @var{function_name}
18841 @cindex @option{-e} (@code{gprof})
18842 The @samp{-e @var{function}} option tells @code{gprof} not to print
18843 information about the function @var{function_name} (and its
18844 children@dots{}) in the call graph.  The function will still be listed
18845 as a child of any functions that call it, but its index number will be
18846 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
18847 given; only one @var{function_name} may be indicated with each @samp{-e}
18848 option.
18850 @item -E @var{function_name}
18851 @cindex @option{-E} (@code{gprof})
18852 The @code{-E @var{function}} option works like the @code{-e} option, but
18853 execution time spent in the function (and children who were not called from
18854 anywhere else), will not be used to compute the percentages-of-time for
18855 the call graph.  More than one @samp{-E} option may be given; only one
18856 @var{function_name} may be indicated with each @samp{-E} option.
18858 @item -f @var{function_name}
18859 @cindex @option{-f} (@code{gprof})
18860 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18861 call graph to the function @var{function_name} and its children (and
18862 their children@dots{}).  More than one @samp{-f} option may be given;
18863 only one @var{function_name} may be indicated with each @samp{-f}
18864 option.
18866 @item -F @var{function_name}
18867 @cindex @option{-F} (@code{gprof})
18868 The @samp{-F @var{function}} option works like the @code{-f} option, but
18869 only time spent in the function and its children (and their
18870 children@dots{}) will be used to determine total-time and
18871 percentages-of-time for the call graph.  More than one @samp{-F} option
18872 may be given; only one @var{function_name} may be indicated with each
18873 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
18875 @end table
18877 @node Interpretation of profiling results
18878 @subsection Interpretation of profiling results
18880 @noindent
18882 The results of the profiling analysis are represented by two arrays: the
18883 'flat profile' and the 'call graph'. Full documentation of those outputs
18884 can be found in the GNU Profiler User's Guide.
18886 The flat profile shows the time spent in each function of the program, and how
18887 many time it has been called. This allows you to locate easily the most
18888 time-consuming functions.
18890 The call graph shows, for each subprogram, the subprograms that call it,
18891 and the subprograms that it calls. It also provides an estimate of the time
18892 spent in each of those callers/called subprograms.
18893 @end ifclear
18895 @c ******************************
18896 @node Running and Debugging Ada Programs
18897 @chapter Running and Debugging Ada Programs
18898 @cindex Debugging
18900 @noindent
18901 This chapter discusses how to debug Ada programs.
18902 @ifset vms
18903 It applies to GNAT on the Alpha OpenVMS platform;
18904 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18905 since HP has implemented Ada support in the OpenVMS debugger on I64.
18906 @end ifset
18908 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18910 @enumerate
18911 @item
18912 The illegality may be a violation of the static semantics of Ada. In
18913 that case GNAT diagnoses the constructs in the program that are illegal.
18914 It is then a straightforward matter for the user to modify those parts of
18915 the program.
18917 @item
18918 The illegality may be a violation of the dynamic semantics of Ada. In
18919 that case the program compiles and executes, but may generate incorrect
18920 results, or may terminate abnormally with some exception.
18922 @item
18923 When presented with a program that contains convoluted errors, GNAT
18924 itself may terminate abnormally without providing full diagnostics on
18925 the incorrect user program.
18926 @end enumerate
18928 @menu
18929 * The GNAT Debugger GDB::
18930 * Running GDB::
18931 * Introduction to GDB Commands::
18932 * Using Ada Expressions::
18933 * Calling User-Defined Subprograms::
18934 * Using the Next Command in a Function::
18935 * Ada Exceptions::
18936 * Ada Tasks::
18937 * Debugging Generic Units::
18938 * Remote Debugging using gdbserver::
18939 * GNAT Abnormal Termination or Failure to Terminate::
18940 * Naming Conventions for GNAT Source Files::
18941 * Getting Internal Debugging Information::
18942 * Stack Traceback::
18943 @end menu
18945 @cindex Debugger
18946 @findex gdb
18948 @node The GNAT Debugger GDB
18949 @section The GNAT Debugger GDB
18951 @noindent
18952 @code{GDB} is a general purpose, platform-independent debugger that
18953 can be used to debug mixed-language programs compiled with @command{gcc},
18954 and in particular is capable of debugging Ada programs compiled with
18955 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18956 complex Ada data structures.
18958 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18959 @ifset vms
18960 located in the GNU:[DOCS] directory,
18961 @end ifset
18962 for full details on the usage of @code{GDB}, including a section on
18963 its usage on programs. This manual should be consulted for full
18964 details. The section that follows is a brief introduction to the
18965 philosophy and use of @code{GDB}.
18967 When GNAT programs are compiled, the compiler optionally writes debugging
18968 information into the generated object file, including information on
18969 line numbers, and on declared types and variables. This information is
18970 separate from the generated code. It makes the object files considerably
18971 larger, but it does not add to the size of the actual executable that
18972 will be loaded into memory, and has no impact on run-time performance. The
18973 generation of debug information is triggered by the use of the
18974 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18975 used to carry out the compilations. It is important to emphasize that
18976 the use of these options does not change the generated code.
18978 The debugging information is written in standard system formats that
18979 are used by many tools, including debuggers and profilers. The format
18980 of the information is typically designed to describe C types and
18981 semantics, but GNAT implements a translation scheme which allows full
18982 details about Ada types and variables to be encoded into these
18983 standard C formats. Details of this encoding scheme may be found in
18984 the file exp_dbug.ads in the GNAT source distribution. However, the
18985 details of this encoding are, in general, of no interest to a user,
18986 since @code{GDB} automatically performs the necessary decoding.
18988 When a program is bound and linked, the debugging information is
18989 collected from the object files, and stored in the executable image of
18990 the program. Again, this process significantly increases the size of
18991 the generated executable file, but it does not increase the size of
18992 the executable program itself. Furthermore, if this program is run in
18993 the normal manner, it runs exactly as if the debug information were
18994 not present, and takes no more actual memory.
18996 However, if the program is run under control of @code{GDB}, the
18997 debugger is activated.  The image of the program is loaded, at which
18998 point it is ready to run.  If a run command is given, then the program
18999 will run exactly as it would have if @code{GDB} were not present. This
19000 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19001 entirely non-intrusive until a breakpoint is encountered.  If no
19002 breakpoint is ever hit, the program will run exactly as it would if no
19003 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19004 the debugging information and can respond to user commands to inspect
19005 variables, and more generally to report on the state of execution.
19007 @c **************
19008 @node Running GDB
19009 @section Running GDB
19011 @noindent
19012 This section describes how to initiate the debugger.
19013 @c The above sentence is really just filler, but it was otherwise
19014 @c clumsy to get the first paragraph nonindented given the conditional
19015 @c nature of the description
19017 @ifclear vms
19018 The debugger can be launched from a @code{GPS} menu or
19019 directly from the command line. The description below covers the latter use.
19020 All the commands shown can be used in the @code{GPS} debug console window,
19021 but there are usually more GUI-based ways to achieve the same effect.
19022 @end ifclear
19024 The command to run @code{GDB} is
19026 @smallexample
19027 $ ^gdb program^GDB PROGRAM^
19028 @end smallexample
19030 @noindent
19031 where @code{^program^PROGRAM^} is the name of the executable file. This
19032 activates the debugger and results in a prompt for debugger commands.
19033 The simplest command is simply @code{run}, which causes the program to run
19034 exactly as if the debugger were not present. The following section
19035 describes some of the additional commands that can be given to @code{GDB}.
19037 @c *******************************
19038 @node Introduction to GDB Commands
19039 @section Introduction to GDB Commands
19041 @noindent
19042 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19043 Debugging with GDB, gdb, Debugging with GDB},
19044 @ifset vms
19045 located in the GNU:[DOCS] directory,
19046 @end ifset
19047 for extensive documentation on the use
19048 of these commands, together with examples of their use. Furthermore,
19049 the command @command{help} invoked from within GDB activates a simple help
19050 facility which summarizes the available commands and their options.
19051 In this section we summarize a few of the most commonly
19052 used commands to give an idea of what @code{GDB} is about. You should create
19053 a simple program with debugging information and experiment with the use of
19054 these @code{GDB} commands on the program as you read through the
19055 following section.
19057 @table @code
19058 @item set args @var{arguments}
19059 The @var{arguments} list above is a list of arguments to be passed to
19060 the program on a subsequent run command, just as though the arguments
19061 had been entered on a normal invocation of the program. The @code{set args}
19062 command is not needed if the program does not require arguments.
19064 @item run
19065 The @code{run} command causes execution of the program to start from
19066 the beginning. If the program is already running, that is to say if
19067 you are currently positioned at a breakpoint, then a prompt will ask
19068 for confirmation that you want to abandon the current execution and
19069 restart.
19071 @item breakpoint @var{location}
19072 The breakpoint command sets a breakpoint, that is to say a point at which
19073 execution will halt and @code{GDB} will await further
19074 commands. @var{location} is
19075 either a line number within a file, given in the format @code{file:linenumber},
19076 or it is the name of a subprogram. If you request that a breakpoint be set on
19077 a subprogram that is overloaded, a prompt will ask you to specify on which of
19078 those subprograms you want to breakpoint. You can also
19079 specify that all of them should be breakpointed. If the program is run
19080 and execution encounters the breakpoint, then the program
19081 stops and @code{GDB} signals that the breakpoint was encountered by
19082 printing the line of code before which the program is halted.
19084 @item catch exception @var{name}
19085 This command causes the program execution to stop whenever exception
19086 @var{name} is raised.  If @var{name} is omitted, then the execution is
19087 suspended when any exception is raised.
19089 @item print @var{expression}
19090 This will print the value of the given expression. Most simple
19091 Ada expression formats are properly handled by @code{GDB}, so the expression
19092 can contain function calls, variables, operators, and attribute references.
19094 @item continue
19095 Continues execution following a breakpoint, until the next breakpoint or the
19096 termination of the program.
19098 @item step
19099 Executes a single line after a breakpoint. If the next statement
19100 is a subprogram call, execution continues into (the first statement of)
19101 the called subprogram.
19103 @item next
19104 Executes a single line. If this line is a subprogram call, executes and
19105 returns from the call.
19107 @item list
19108 Lists a few lines around the current source location. In practice, it
19109 is usually more convenient to have a separate edit window open with the
19110 relevant source file displayed. Successive applications of this command
19111 print subsequent lines. The command can be given an argument which is a
19112 line number, in which case it displays a few lines around the specified one.
19114 @item backtrace
19115 Displays a backtrace of the call chain. This command is typically
19116 used after a breakpoint has occurred, to examine the sequence of calls that
19117 leads to the current breakpoint. The display includes one line for each
19118 activation record (frame) corresponding to an active subprogram.
19120 @item up
19121 At a breakpoint, @code{GDB} can display the values of variables local
19122 to the current frame. The command @code{up} can be used to
19123 examine the contents of other active frames, by moving the focus up
19124 the stack, that is to say from callee to caller, one frame at a time.
19126 @item down
19127 Moves the focus of @code{GDB} down from the frame currently being
19128 examined to the frame of its callee (the reverse of the previous command),
19130 @item frame @var{n}
19131 Inspect the frame with the given number. The value 0 denotes the frame
19132 of the current breakpoint, that is to say the top of the call stack.
19134 @end table
19136 @noindent
19137 The above list is a very short introduction to the commands that
19138 @code{GDB} provides. Important additional capabilities, including conditional
19139 breakpoints, the ability to execute command sequences on a breakpoint,
19140 the ability to debug at the machine instruction level and many other
19141 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19142 Debugging with GDB}.  Note that most commands can be abbreviated
19143 (for example, c for continue, bt for backtrace).
19145 @node Using Ada Expressions
19146 @section Using Ada Expressions
19147 @cindex Ada expressions
19149 @noindent
19150 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19151 extensions. The philosophy behind the design of this subset is
19153 @itemize @bullet
19154 @item
19155 That @code{GDB} should provide basic literals and access to operations for
19156 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19157 leaving more sophisticated computations to subprograms written into the
19158 program (which therefore may be called from @code{GDB}).
19160 @item
19161 That type safety and strict adherence to Ada language restrictions
19162 are not particularly important to the @code{GDB} user.
19164 @item
19165 That brevity is important to the @code{GDB} user.
19166 @end itemize
19168 @noindent
19169 Thus, for brevity, the debugger acts as if there were
19170 implicit @code{with} and @code{use} clauses in effect for all user-written
19171 packages, thus making it unnecessary to fully qualify most names with
19172 their packages, regardless of context. Where this causes ambiguity,
19173 @code{GDB} asks the user's intent.
19175 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19176 GDB, gdb, Debugging with GDB}.
19178 @node Calling User-Defined Subprograms
19179 @section Calling User-Defined Subprograms
19181 @noindent
19182 An important capability of @code{GDB} is the ability to call user-defined
19183 subprograms while debugging. This is achieved simply by entering
19184 a subprogram call statement in the form:
19186 @smallexample
19187 call subprogram-name (parameters)
19188 @end smallexample
19190 @noindent
19191 The keyword @code{call} can be omitted in the normal case where the
19192 @code{subprogram-name} does not coincide with any of the predefined
19193 @code{GDB} commands.
19195 The effect is to invoke the given subprogram, passing it the
19196 list of parameters that is supplied. The parameters can be expressions and
19197 can include variables from the program being debugged. The
19198 subprogram must be defined
19199 at the library level within your program, and @code{GDB} will call the
19200 subprogram within the environment of your program execution (which
19201 means that the subprogram is free to access or even modify variables
19202 within your program).
19204 The most important use of this facility is in allowing the inclusion of
19205 debugging routines that are tailored to particular data structures
19206 in your program. Such debugging routines can be written to provide a suitably
19207 high-level description of an abstract type, rather than a low-level dump
19208 of its physical layout. After all, the standard
19209 @code{GDB print} command only knows the physical layout of your
19210 types, not their abstract meaning. Debugging routines can provide information
19211 at the desired semantic level and are thus enormously useful.
19213 For example, when debugging GNAT itself, it is crucial to have access to
19214 the contents of the tree nodes used to represent the program internally.
19215 But tree nodes are represented simply by an integer value (which in turn
19216 is an index into a table of nodes).
19217 Using the @code{print} command on a tree node would simply print this integer
19218 value, which is not very useful. But the PN routine (defined in file
19219 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19220 a useful high level representation of the tree node, which includes the
19221 syntactic category of the node, its position in the source, the integers
19222 that denote descendant nodes and parent node, as well as varied
19223 semantic information. To study this example in more detail, you might want to
19224 look at the body of the PN procedure in the stated file.
19226 @node Using the Next Command in a Function
19227 @section Using the Next Command in a Function
19229 @noindent
19230 When you use the @code{next} command in a function, the current source
19231 location will advance to the next statement as usual. A special case
19232 arises in the case of a @code{return} statement.
19234 Part of the code for a return statement is the ``epilog'' of the function.
19235 This is the code that returns to the caller. There is only one copy of
19236 this epilog code, and it is typically associated with the last return
19237 statement in the function if there is more than one return. In some
19238 implementations, this epilog is associated with the first statement
19239 of the function.
19241 The result is that if you use the @code{next} command from a return
19242 statement that is not the last return statement of the function you
19243 may see a strange apparent jump to the last return statement or to
19244 the start of the function. You should simply ignore this odd jump.
19245 The value returned is always that from the first return statement
19246 that was stepped through.
19248 @node Ada Exceptions
19249 @section Stopping when Ada Exceptions are Raised
19250 @cindex Exceptions
19252 @noindent
19253 You can set catchpoints that stop the program execution when your program
19254 raises selected exceptions.
19256 @table @code
19257 @item catch exception
19258 Set a catchpoint that stops execution whenever (any task in the) program
19259 raises any exception.
19261 @item catch exception @var{name}
19262 Set a catchpoint that stops execution whenever (any task in the) program
19263 raises the exception @var{name}.
19265 @item catch exception unhandled
19266 Set a catchpoint that stops executino whenever (any task in the) program
19267 raises an exception for which there is no handler.
19269 @item info exceptions
19270 @itemx info exceptions @var{regexp}
19271 The @code{info exceptions} command permits the user to examine all defined
19272 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19273 argument, prints out only those exceptions whose name matches @var{regexp}.
19274 @end table
19276 @node Ada Tasks
19277 @section Ada Tasks
19278 @cindex Tasks
19280 @noindent
19281 @code{GDB} allows the following task-related commands:
19283 @table @code
19284 @item info tasks
19285 This command shows a list of current Ada tasks, as in the following example:
19287 @smallexample
19288 @iftex
19289 @leftskip=0cm
19290 @end iftex
19291 (gdb) info tasks
19292   ID       TID P-ID   Thread Pri State                 Name
19293    1   8088000   0   807e000  15 Child Activation Wait main_task
19294    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19295    3   809a800   1   80a4800  15 Child Activation Wait a
19296 *  4   80ae800   3   80b8000  15 Running               c
19297 @end smallexample
19299 @noindent
19300 In this listing, the asterisk before the first task indicates it to be the
19301 currently running task. The first column lists the task ID that is used
19302 to refer to tasks in the following commands.
19304 @item break @var{linespec} task @var{taskid}
19305 @itemx break @var{linespec} task @var{taskid} if @dots{}
19306 @cindex Breakpoints and tasks
19307 These commands are like the @code{break @dots{} thread @dots{}}.
19308 @var{linespec} specifies source lines.
19310 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19311 to specify that you only want @code{GDB} to stop the program when a
19312 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19313 numeric task identifiers assigned by @code{GDB}, shown in the first
19314 column of the @samp{info tasks} display.
19316 If you do not specify @samp{task @var{taskid}} when you set a
19317 breakpoint, the breakpoint applies to @emph{all} tasks of your
19318 program.
19320 You can use the @code{task} qualifier on conditional breakpoints as
19321 well; in this case, place @samp{task @var{taskid}} before the
19322 breakpoint condition (before the @code{if}).
19324 @item task @var{taskno}
19325 @cindex Task switching
19327 This command allows to switch to the task referred by @var{taskno}. In
19328 particular, This allows to browse the backtrace of the specified
19329 task. It is advised to switch back to the original task before
19330 continuing execution otherwise the scheduling of the program may be
19331 perturbed.
19332 @end table
19334 @noindent
19335 For more detailed information on the tasking support,
19336 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19338 @node Debugging Generic Units
19339 @section Debugging Generic Units
19340 @cindex Debugging Generic Units
19341 @cindex Generics
19343 @noindent
19344 GNAT always uses code expansion for generic instantiation. This means that
19345 each time an instantiation occurs, a complete copy of the original code is
19346 made, with appropriate substitutions of formals by actuals.
19348 It is not possible to refer to the original generic entities in
19349 @code{GDB}, but it is always possible to debug a particular instance of
19350 a generic, by using the appropriate expanded names. For example, if we have
19352 @smallexample @c ada
19353 @group
19354 @cartouche
19355 procedure g is
19357    generic package k is
19358       procedure kp (v1 : in out integer);
19359    end k;
19361    package body k is
19362       procedure kp (v1 : in out integer) is
19363       begin
19364          v1 := v1 + 1;
19365       end kp;
19366    end k;
19368    package k1 is new k;
19369    package k2 is new k;
19371    var : integer := 1;
19373 begin
19374    k1.kp (var);
19375    k2.kp (var);
19376    k1.kp (var);
19377    k2.kp (var);
19378 end;
19379 @end cartouche
19380 @end group
19381 @end smallexample
19383 @noindent
19384 Then to break on a call to procedure kp in the k2 instance, simply
19385 use the command:
19387 @smallexample
19388 (gdb) break g.k2.kp
19389 @end smallexample
19391 @noindent
19392 When the breakpoint occurs, you can step through the code of the
19393 instance in the normal manner and examine the values of local variables, as for
19394 other units.
19396 @node Remote Debugging using gdbserver
19397 @section Remote Debugging using gdbserver
19398 @cindex Remote Debugging using gdbserver
19400 @noindent
19401 On platforms where gdbserver is supported, it is possible to use this tool
19402 to debug your application remotely.  This can be useful in situations
19403 where the program needs to be run on a target host that is different
19404 from the host used for development, particularly when the target has
19405 a limited amount of resources (either CPU and/or memory).
19407 To do so, start your program using gdbserver on the target machine.
19408 gdbserver then automatically suspends the execution of your program
19409 at its entry point, waiting for a debugger to connect to it.  The
19410 following commands starts an application and tells gdbserver to
19411 wait for a connection with the debugger on localhost port 4444.
19413 @smallexample
19414 $ gdbserver localhost:4444 program
19415 Process program created; pid = 5685
19416 Listening on port 4444
19417 @end smallexample
19419 Once gdbserver has started listening, we can tell the debugger to establish
19420 a connection with this gdbserver, and then start the same debugging session
19421 as if the program was being debugged on the same host, directly under
19422 the control of GDB.
19424 @smallexample
19425 $ gdb program
19426 (gdb) target remote targethost:4444
19427 Remote debugging using targethost:4444
19428 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19429 (gdb) b foo.adb:3
19430 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19431 (gdb) continue
19432 Continuing.
19434 Breakpoint 1, foo () at foo.adb:4
19435 4       end foo;
19436 @end smallexample
19438 It is also possible to use gdbserver to attach to an already running
19439 program, in which case the execution of that program is simply suspended
19440 until the connection between the debugger and gdbserver is established.
19442 For more information on how to use gdbserver, @ref{Top, Server, Using
19443 the gdbserver Program, gdb, Debugging with GDB}.  GNAT Pro provides support
19444 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19446 @node GNAT Abnormal Termination or Failure to Terminate
19447 @section GNAT Abnormal Termination or Failure to Terminate
19448 @cindex GNAT Abnormal Termination or Failure to Terminate
19450 @noindent
19451 When presented with programs that contain serious errors in syntax
19452 or semantics,
19453 GNAT may on rare occasions  experience problems in operation, such
19454 as aborting with a
19455 segmentation fault or illegal memory access, raising an internal
19456 exception, terminating abnormally, or failing to terminate at all.
19457 In such cases, you can activate
19458 various features of GNAT that can help you pinpoint the construct in your
19459 program that is the likely source of the problem.
19461 The following strategies are presented in increasing order of
19462 difficulty, corresponding to your experience in using GNAT and your
19463 familiarity with compiler internals.
19465 @enumerate
19466 @item
19467 Run @command{gcc} with the @option{-gnatf}. This first
19468 switch causes all errors on a given line to be reported. In its absence,
19469 only the first error on a line is displayed.
19471 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19472 are encountered, rather than after compilation is terminated. If GNAT
19473 terminates prematurely or goes into an infinite loop, the last error
19474 message displayed may help to pinpoint the culprit.
19476 @item
19477 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19478 mode, @command{gcc} produces ongoing information about the progress of the
19479 compilation and provides the name of each procedure as code is
19480 generated. This switch allows you to find which Ada procedure was being
19481 compiled when it encountered a code generation problem.
19483 @item
19484 @cindex @option{-gnatdc} switch
19485 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19486 switch that does for the front-end what @option{^-v^VERBOSE^} does
19487 for the back end. The system prints the name of each unit,
19488 either a compilation unit or nested unit, as it is being analyzed.
19489 @item
19490 Finally, you can start
19491 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19492 front-end of GNAT, and can be run independently (normally it is just
19493 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19494 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19495 @code{where} command is the first line of attack; the variable
19496 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19497 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19498 which the execution stopped, and @code{input_file name} indicates the name of
19499 the source file.
19500 @end enumerate
19502 @node Naming Conventions for GNAT Source Files
19503 @section Naming Conventions for GNAT Source Files
19505 @noindent
19506 In order to examine the workings of the GNAT system, the following
19507 brief description of its organization may be helpful:
19509 @itemize @bullet
19510 @item
19511 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19513 @item
19514 All files prefixed with @file{^par^PAR^} are components of the parser. The
19515 numbers correspond to chapters of the Ada Reference Manual. For example,
19516 parsing of select statements can be found in @file{par-ch9.adb}.
19518 @item
19519 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19520 numbers correspond to chapters of the Ada standard. For example, all
19521 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19522 addition, some features of the language require sufficient special processing
19523 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19524 dynamic dispatching, etc.
19526 @item
19527 All files prefixed with @file{^exp^EXP^} perform normalization and
19528 expansion of the intermediate representation (abstract syntax tree, or AST).
19529 these files use the same numbering scheme as the parser and semantics files.
19530 For example, the construction of record initialization procedures is done in
19531 @file{exp_ch3.adb}.
19533 @item
19534 The files prefixed with @file{^bind^BIND^} implement the binder, which
19535 verifies the consistency of the compilation, determines an order of
19536 elaboration, and generates the bind file.
19538 @item
19539 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19540 data structures used by the front-end.
19542 @item
19543 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19544 the abstract syntax tree as produced by the parser.
19546 @item
19547 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19548 all entities, computed during semantic analysis.
19550 @item
19551 Library management issues are dealt with in files with prefix
19552 @file{^lib^LIB^}.
19554 @item
19555 @findex Ada
19556 @cindex Annex A
19557 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19558 defined in Annex A.
19560 @item
19561 @findex Interfaces
19562 @cindex Annex B
19563 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19564 defined in Annex B.
19566 @item
19567 @findex System
19568 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19569 both language-defined children and GNAT run-time routines.
19571 @item
19572 @findex GNAT
19573 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19574 general-purpose packages, fully documented in their specs. All
19575 the other @file{.c} files are modifications of common @command{gcc} files.
19576 @end itemize
19578 @node Getting Internal Debugging Information
19579 @section Getting Internal Debugging Information
19581 @noindent
19582 Most compilers have internal debugging switches and modes. GNAT
19583 does also, except GNAT internal debugging switches and modes are not
19584 secret. A summary and full description of all the compiler and binder
19585 debug flags are in the file @file{debug.adb}. You must obtain the
19586 sources of the compiler to see the full detailed effects of these flags.
19588 The switches that print the source of the program (reconstructed from
19589 the internal tree) are of general interest for user programs, as are the
19590 options to print
19591 the full internal tree, and the entity table (the symbol table
19592 information). The reconstructed source provides a readable version of the
19593 program after the front-end has completed analysis and  expansion,
19594 and is useful when studying the performance of specific constructs.
19595 For example, constraint checks are indicated, complex aggregates
19596 are replaced with loops and assignments, and tasking primitives
19597 are replaced with run-time calls.
19599 @node Stack Traceback
19600 @section Stack Traceback
19601 @cindex traceback
19602 @cindex stack traceback
19603 @cindex stack unwinding
19605 @noindent
19606 Traceback is a mechanism to display the sequence of subprogram calls that
19607 leads to a specified execution point in a program. Often (but not always)
19608 the execution point is an instruction at which an exception has been raised.
19609 This mechanism is also known as @i{stack unwinding} because it obtains
19610 its information by scanning the run-time stack and recovering the activation
19611 records of all active subprograms. Stack unwinding is one of the most
19612 important tools for program debugging.
19614 The first entry stored in traceback corresponds to the deepest calling level,
19615 that is to say the subprogram currently executing the instruction
19616 from which we want to obtain the traceback.
19618 Note that there is no runtime performance penalty when stack traceback
19619 is enabled, and no exception is raised during program execution.
19621 @menu
19622 * Non-Symbolic Traceback::
19623 * Symbolic Traceback::
19624 @end menu
19626 @node Non-Symbolic Traceback
19627 @subsection Non-Symbolic Traceback
19628 @cindex traceback, non-symbolic
19630 @noindent
19631 Note: this feature is not supported on all platforms. See
19632 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19633 platforms.
19635 @menu
19636 * Tracebacks From an Unhandled Exception::
19637 * Tracebacks From Exception Occurrences (non-symbolic)::
19638 * Tracebacks From Anywhere in a Program (non-symbolic)::
19639 @end menu
19641 @node Tracebacks From an Unhandled Exception
19642 @subsubsection Tracebacks From an Unhandled Exception
19644 @noindent
19645 A runtime non-symbolic traceback is a list of addresses of call instructions.
19646 To enable this feature you must use the @option{-E}
19647 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19648 of exception information. You can retrieve this information using the
19649 @code{addr2line} tool.
19651 Here is a simple example:
19653 @smallexample @c ada
19654 @cartouche
19655 procedure STB is
19657    procedure P1 is
19658    begin
19659       raise Constraint_Error;
19660    end P1;
19662    procedure P2 is
19663    begin
19664       P1;
19665    end P2;
19667 begin
19668    P2;
19669 end STB;
19670 @end cartouche
19671 @end smallexample
19673 @smallexample
19674 $ gnatmake stb -bargs -E
19675 $ stb
19677 Execution terminated by unhandled exception
19678 Exception name: CONSTRAINT_ERROR
19679 Message: stb.adb:5
19680 Call stack traceback locations:
19681 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19682 @end smallexample
19684 @noindent
19685 As we see the traceback lists a sequence of addresses for the unhandled
19686 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19687 guess that this exception come from procedure P1. To translate these
19688 addresses into the source lines where the calls appear, the
19689 @code{addr2line} tool, described below, is invaluable. The use of this tool
19690 requires the program to be compiled with debug information.
19692 @smallexample
19693 $ gnatmake -g stb -bargs -E
19694 $ stb
19696 Execution terminated by unhandled exception
19697 Exception name: CONSTRAINT_ERROR
19698 Message: stb.adb:5
19699 Call stack traceback locations:
19700 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19702 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19703    0x4011f1 0x77e892a4
19705 00401373 at d:/stb/stb.adb:5
19706 0040138B at d:/stb/stb.adb:10
19707 0040139C at d:/stb/stb.adb:14
19708 00401335 at d:/stb/b~stb.adb:104
19709 004011C4 at /build/@dots{}/crt1.c:200
19710 004011F1 at /build/@dots{}/crt1.c:222
19711 77E892A4 in ?? at ??:0
19712 @end smallexample
19714 @noindent
19715 The @code{addr2line} tool has several other useful options:
19717 @table @code
19718 @item --functions
19719 to get the function name corresponding to any location
19721 @item --demangle=gnat
19722 to use the gnat decoding mode for the function names. Note that
19723 for binutils version 2.9.x the option is simply @option{--demangle}.
19724 @end table
19726 @smallexample
19727 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19728    0x40139c 0x401335 0x4011c4 0x4011f1
19730 00401373 in stb.p1 at d:/stb/stb.adb:5
19731 0040138B in stb.p2 at d:/stb/stb.adb:10
19732 0040139C in stb at d:/stb/stb.adb:14
19733 00401335 in main at d:/stb/b~stb.adb:104
19734 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19735 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19736 @end smallexample
19738 @noindent
19739 From this traceback we can see that the exception was raised in
19740 @file{stb.adb} at line 5, which was reached from a procedure call in
19741 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19742 which contains the call to the main program.
19743 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19744 and the output will vary from platform to platform.
19746 It is also possible to use @code{GDB} with these traceback addresses to debug
19747 the program. For example, we can break at a given code location, as reported
19748 in the stack traceback:
19750 @smallexample
19751 $ gdb -nw stb
19752 @ifclear vms
19753 @noindent
19754 Furthermore, this feature is not implemented inside Windows DLL. Only
19755 the non-symbolic traceback is reported in this case.
19756 @end ifclear
19758 (gdb) break *0x401373
19759 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19760 @end smallexample
19762 @noindent
19763 It is important to note that the stack traceback addresses
19764 do not change when debug information is included. This is particularly useful
19765 because it makes it possible to release software without debug information (to
19766 minimize object size), get a field report that includes a stack traceback
19767 whenever an internal bug occurs, and then be able to retrieve the sequence
19768 of calls with the same program compiled with debug information.
19770 @node Tracebacks From Exception Occurrences (non-symbolic)
19771 @subsubsection Tracebacks From Exception Occurrences
19773 @noindent
19774 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19775 The stack traceback is attached to the exception information string, and can
19776 be retrieved in an exception handler within the Ada program, by means of the
19777 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19779 @smallexample @c ada
19780 with Ada.Text_IO;
19781 with Ada.Exceptions;
19783 procedure STB is
19785    use Ada;
19786    use Ada.Exceptions;
19788    procedure P1 is
19789       K : Positive := 1;
19790    begin
19791       K := K - 1;
19792    exception
19793       when E : others =>
19794          Text_IO.Put_Line (Exception_Information (E));
19795    end P1;
19797    procedure P2 is
19798    begin
19799       P1;
19800    end P2;
19802 begin
19803    P2;
19804 end STB;
19805 @end smallexample
19807 @noindent
19808 This program will output:
19810 @smallexample
19811 $ stb
19813 Exception name: CONSTRAINT_ERROR
19814 Message: stb.adb:12
19815 Call stack traceback locations:
19816 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19817 @end smallexample
19819 @node Tracebacks From Anywhere in a Program (non-symbolic)
19820 @subsubsection Tracebacks From Anywhere in a Program
19822 @noindent
19823 It is also possible to retrieve a stack traceback from anywhere in a
19824 program. For this you need to
19825 use the @code{GNAT.Traceback} API. This package includes a procedure called
19826 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19827 display procedures described below. It is not necessary to use the
19828 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19829 is invoked explicitly.
19831 @noindent
19832 In the following example we compute a traceback at a specific location in
19833 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19834 convert addresses to strings:
19836 @smallexample @c ada
19837 with Ada.Text_IO;
19838 with GNAT.Traceback;
19839 with GNAT.Debug_Utilities;
19841 procedure STB is
19843    use Ada;
19844    use GNAT;
19845    use GNAT.Traceback;
19847    procedure P1 is
19848       TB  : Tracebacks_Array (1 .. 10);
19849       --  We are asking for a maximum of 10 stack frames.
19850       Len : Natural;
19851       --  Len will receive the actual number of stack frames returned.
19852    begin
19853       Call_Chain (TB, Len);
19855       Text_IO.Put ("In STB.P1 : ");
19857       for K in 1 .. Len loop
19858          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19859          Text_IO.Put (' ');
19860       end loop;
19862       Text_IO.New_Line;
19863    end P1;
19865    procedure P2 is
19866    begin
19867       P1;
19868    end P2;
19870 begin
19871    P2;
19872 end STB;
19873 @end smallexample
19875 @smallexample
19876 $ gnatmake -g stb
19877 $ stb
19879 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19880 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19881 @end smallexample
19883 @noindent
19884 You can then get further information by invoking the @code{addr2line}
19885 tool as described earlier (note that the hexadecimal addresses
19886 need to be specified in C format, with a leading ``0x'').
19888 @node Symbolic Traceback
19889 @subsection Symbolic Traceback
19890 @cindex traceback, symbolic
19892 @noindent
19893 A symbolic traceback is a stack traceback in which procedure names are
19894 associated with each code location.
19896 @noindent
19897 Note that this feature is not supported on all platforms. See
19898 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19899 list of currently supported platforms.
19901 @noindent
19902 Note that the symbolic traceback requires that the program be compiled
19903 with debug information. If it is not compiled with debug information
19904 only the non-symbolic information will be valid.
19906 @menu
19907 * Tracebacks From Exception Occurrences (symbolic)::
19908 * Tracebacks From Anywhere in a Program (symbolic)::
19909 @end menu
19911 @node Tracebacks From Exception Occurrences (symbolic)
19912 @subsubsection Tracebacks From Exception Occurrences
19914 @smallexample @c ada
19915 with Ada.Text_IO;
19916 with GNAT.Traceback.Symbolic;
19918 procedure STB is
19920    procedure P1 is
19921    begin
19922       raise Constraint_Error;
19923    end P1;
19925    procedure P2 is
19926    begin
19927       P1;
19928    end P2;
19930    procedure P3 is
19931    begin
19932       P2;
19933    end P3;
19935 begin
19936    P3;
19937 exception
19938    when E : others =>
19939       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19940 end STB;
19941 @end smallexample
19943 @smallexample
19944 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19945 $ stb
19947 0040149F in stb.p1 at stb.adb:8
19948 004014B7 in stb.p2 at stb.adb:13
19949 004014CF in stb.p3 at stb.adb:18
19950 004015DD in ada.stb at stb.adb:22
19951 00401461 in main at b~stb.adb:168
19952 004011C4 in __mingw_CRTStartup at crt1.c:200
19953 004011F1 in mainCRTStartup at crt1.c:222
19954 77E892A4 in ?? at ??:0
19955 @end smallexample
19957 @noindent
19958 In the above example the ``.\'' syntax in the @command{gnatmake} command
19959 is currently required by @command{addr2line} for files that are in
19960 the current working directory.
19961 Moreover, the exact sequence of linker options may vary from platform
19962 to platform.
19963 The above @option{-largs} section is for Windows platforms. By contrast,
19964 under Unix there is no need for the @option{-largs} section.
19965 Differences across platforms are due to details of linker implementation.
19967 @node Tracebacks From Anywhere in a Program (symbolic)
19968 @subsubsection Tracebacks From Anywhere in a Program
19970 @noindent
19971 It is possible to get a symbolic stack traceback
19972 from anywhere in a program, just as for non-symbolic tracebacks.
19973 The first step is to obtain a non-symbolic
19974 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19975 information. Here is an example:
19977 @smallexample @c ada
19978 with Ada.Text_IO;
19979 with GNAT.Traceback;
19980 with GNAT.Traceback.Symbolic;
19982 procedure STB is
19984    use Ada;
19985    use GNAT.Traceback;
19986    use GNAT.Traceback.Symbolic;
19988    procedure P1 is
19989       TB  : Tracebacks_Array (1 .. 10);
19990       --  We are asking for a maximum of 10 stack frames.
19991       Len : Natural;
19992       --  Len will receive the actual number of stack frames returned.
19993    begin
19994       Call_Chain (TB, Len);
19995       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19996    end P1;
19998    procedure P2 is
19999    begin
20000       P1;
20001    end P2;
20003 begin
20004    P2;
20005 end STB;
20006 @end smallexample
20008 @c ******************************
20009 @ifset vms
20010 @node Compatibility with HP Ada
20011 @chapter Compatibility with HP Ada
20012 @cindex Compatibility
20014 @noindent
20015 @cindex DEC Ada
20016 @cindex HP Ada
20017 @cindex Compatibility between GNAT and HP Ada
20018 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20019 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20020 GNAT is highly compatible
20021 with HP Ada, and it should generally be straightforward to port code
20022 from the HP Ada environment to GNAT. However, there are a few language
20023 and implementation differences of which the user must be aware. These
20024 differences are discussed in this chapter. In
20025 addition, the operating environment and command structure for the
20026 compiler are different, and these differences are also discussed.
20028 For further details on these and other compatibility issues,
20029 see Appendix E of the HP publication
20030 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20032 Except where otherwise indicated, the description of GNAT for OpenVMS
20033 applies to both the Alpha and I64 platforms.
20035 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20036 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20038 The discussion in this chapter addresses specifically the implementation
20039 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20040 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20041 GNAT always follows the Alpha implementation.
20043 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20044 attributes are recognized, although only a subset of them can sensibly
20045 be implemented.  The description of pragmas in
20046 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20047 indicates whether or not they are applicable to non-VMS systems.
20049 @menu
20050 * Ada Language Compatibility::
20051 * Differences in the Definition of Package System::
20052 * Language-Related Features::
20053 * The Package STANDARD::
20054 * The Package SYSTEM::
20055 * Tasking and Task-Related Features::
20056 * Pragmas and Pragma-Related Features::
20057 * Library of Predefined Units::
20058 * Bindings::
20059 * Main Program Definition::
20060 * Implementation-Defined Attributes::
20061 * Compiler and Run-Time Interfacing::
20062 * Program Compilation and Library Management::
20063 * Input-Output::
20064 * Implementation Limits::
20065 * Tools and Utilities::
20066 @end menu
20068 @node Ada Language Compatibility
20069 @section Ada Language Compatibility
20071 @noindent
20072 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20073 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20074 with Ada 83, and therefore Ada 83 programs will compile
20075 and run under GNAT with
20076 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20077 provides details on specific incompatibilities.
20079 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20080 as well as the pragma @code{ADA_83}, to force the compiler to
20081 operate in Ada 83 mode. This mode does not guarantee complete
20082 conformance to Ada 83, but in practice is sufficient to
20083 eliminate most sources of incompatibilities.
20084 In particular, it eliminates the recognition of the
20085 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20086 in Ada 83 programs is legal, and handles the cases of packages
20087 with optional bodies, and generics that instantiate unconstrained
20088 types without the use of @code{(<>)}.
20090 @node Differences in the Definition of Package System
20091 @section Differences in the Definition of Package @code{System}
20093 @noindent
20094 An Ada compiler is allowed to add
20095 implementation-dependent declarations to package @code{System}.
20096 In normal mode,
20097 GNAT does not take advantage of this permission, and the version of
20098 @code{System} provided by GNAT exactly matches that defined in the Ada
20099 Reference Manual.
20101 However, HP Ada adds an extensive set of declarations to package
20102 @code{System},
20103 as fully documented in the HP Ada manuals. To minimize changes required
20104 for programs that make use of these extensions, GNAT provides the pragma
20105 @code{Extend_System} for extending the definition of package System. By using:
20106 @cindex pragma @code{Extend_System}
20107 @cindex @code{Extend_System} pragma
20109 @smallexample @c ada
20110 @group
20111 @cartouche
20112 pragma Extend_System (Aux_DEC);
20113 @end cartouche
20114 @end group
20115 @end smallexample
20117 @noindent
20118 the set of definitions in @code{System} is extended to include those in
20119 package @code{System.Aux_DEC}.
20120 @cindex @code{System.Aux_DEC} package
20121 @cindex @code{Aux_DEC} package (child of @code{System})
20122 These definitions are incorporated directly into package @code{System},
20123 as though they had been declared there. For a
20124 list of the declarations added, see the spec of this package,
20125 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20126 @cindex @file{s-auxdec.ads} file
20127 The pragma @code{Extend_System} is a configuration pragma, which means that
20128 it can be placed in the file @file{gnat.adc}, so that it will automatically
20129 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20130 for further details.
20132 An alternative approach that avoids the use of the non-standard
20133 @code{Extend_System} pragma is to add a context clause to the unit that
20134 references these facilities:
20136 @smallexample @c ada
20137 @cartouche
20138 with System.Aux_DEC;
20139 use  System.Aux_DEC;
20140 @end cartouche
20141 @end smallexample
20143 @noindent
20144 The effect is not quite semantically identical to incorporating
20145 the declarations directly into package @code{System},
20146 but most programs will not notice a difference
20147 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20148 to reference the entities directly in package @code{System}.
20149 For units containing such references,
20150 the prefixes must either be removed, or the pragma @code{Extend_System}
20151 must be used.
20153 @node Language-Related Features
20154 @section Language-Related Features
20156 @noindent
20157 The following sections highlight differences in types,
20158 representations of types, operations, alignment, and
20159 related topics.
20161 @menu
20162 * Integer Types and Representations::
20163 * Floating-Point Types and Representations::
20164 * Pragmas Float_Representation and Long_Float::
20165 * Fixed-Point Types and Representations::
20166 * Record and Array Component Alignment::
20167 * Address Clauses::
20168 * Other Representation Clauses::
20169 @end menu
20171 @node Integer Types and Representations
20172 @subsection Integer Types and Representations
20174 @noindent
20175 The set of predefined integer types is identical in HP Ada and GNAT.
20176 Furthermore the representation of these integer types is also identical,
20177 including the capability of size clauses forcing biased representation.
20179 In addition,
20180 HP Ada for OpenVMS Alpha systems has defined the
20181 following additional integer types in package @code{System}:
20183 @itemize @bullet
20185 @item
20186 @code{INTEGER_8}
20188 @item
20189 @code{INTEGER_16}
20191 @item
20192 @code{INTEGER_32}
20194 @item
20195 @code{INTEGER_64}
20197 @item
20198 @code{LARGEST_INTEGER}
20199 @end itemize
20201 @noindent
20202 In GNAT, the first four of these types may be obtained from the
20203 standard Ada package @code{Interfaces}.
20204 Alternatively, by use of the pragma @code{Extend_System}, identical
20205 declarations can be referenced directly in package @code{System}.
20206 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20208 @node Floating-Point Types and Representations
20209 @subsection Floating-Point Types and Representations
20210 @cindex Floating-Point types
20212 @noindent
20213 The set of predefined floating-point types is identical in HP Ada and GNAT.
20214 Furthermore the representation of these floating-point
20215 types is also identical. One important difference is that the default
20216 representation for HP Ada is @code{VAX_Float}, but the default representation
20217 for GNAT is IEEE.
20219 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20220 pragma @code{Float_Representation} as described in the HP Ada
20221 documentation.
20222 For example, the declarations:
20224 @smallexample @c ada
20225 @cartouche
20226 type F_Float is digits 6;
20227 pragma Float_Representation (VAX_Float, F_Float);
20228 @end cartouche
20229 @end smallexample
20231 @noindent
20232 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20233 format.
20234 This set of declarations actually appears in @code{System.Aux_DEC},
20235 which contains
20236 the full set of additional floating-point declarations provided in
20237 the HP Ada version of package @code{System}.
20238 This and similar declarations may be accessed in a user program
20239 by using pragma @code{Extend_System}. The use of this
20240 pragma, and the related pragma @code{Long_Float} is described in further
20241 detail in the following section.
20243 @node Pragmas Float_Representation and Long_Float
20244 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20246 @noindent
20247 HP Ada provides the pragma @code{Float_Representation}, which
20248 acts as a program library switch to allow control over
20249 the internal representation chosen for the predefined
20250 floating-point types declared in the package @code{Standard}.
20251 The format of this pragma is as follows:
20253 @smallexample @c ada
20254 @cartouche
20255 pragma Float_Representation(VAX_Float | IEEE_Float);
20256 @end cartouche
20257 @end smallexample
20259 @noindent
20260 This pragma controls the representation of floating-point
20261 types as follows:
20263 @itemize @bullet
20264 @item
20265 @code{VAX_Float} specifies that floating-point
20266 types are represented by default with the VAX system hardware types
20267 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20268 Note that the @code{H-floating}
20269 type was available only on VAX systems, and is not available
20270 in either HP Ada or GNAT.
20272 @item
20273 @code{IEEE_Float} specifies that floating-point
20274 types are represented by default with the IEEE single and
20275 double floating-point types.
20276 @end itemize
20278 @noindent
20279 GNAT provides an identical implementation of the pragma
20280 @code{Float_Representation}, except that it functions as a
20281 configuration pragma. Note that the
20282 notion of configuration pragma corresponds closely to the
20283 HP Ada notion of a program library switch.
20285 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20286 which is different
20287 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20288 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20289 advisable to change the format of numbers passed to standard library
20290 routines, and if necessary explicit type conversions may be needed.
20292 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20293 efficient, and (given that it conforms to an international standard)
20294 potentially more portable.
20295 The situation in which @code{VAX_Float} may be useful is in interfacing
20296 to existing code and data that expect the use of @code{VAX_Float}.
20297 In such a situation use the predefined @code{VAX_Float}
20298 types in package @code{System}, as extended by
20299 @code{Extend_System}. For example, use @code{System.F_Float}
20300 to specify the 32-bit @code{F-Float} format.
20302 @noindent
20303 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20304 to allow control over the internal representation chosen
20305 for the predefined type @code{Long_Float} and for floating-point
20306 type declarations with digits specified in the range 7 .. 15.
20307 The format of this pragma is as follows:
20309 @smallexample @c ada
20310 @cartouche
20311 pragma Long_Float (D_FLOAT | G_FLOAT);
20312 @end cartouche
20313 @end smallexample
20315 @node Fixed-Point Types and Representations
20316 @subsection Fixed-Point Types and Representations
20318 @noindent
20319 On HP Ada for OpenVMS Alpha systems, rounding is
20320 away from zero for both positive and negative numbers.
20321 Therefore, @code{+0.5} rounds to @code{1},
20322 and @code{-0.5} rounds to @code{-1}.
20324 On GNAT the results of operations
20325 on fixed-point types are in accordance with the Ada
20326 rules. In particular, results of operations on decimal
20327 fixed-point types are truncated.
20329 @node Record and Array Component Alignment
20330 @subsection Record and Array Component Alignment
20332 @noindent
20333 On HP Ada for OpenVMS Alpha, all non-composite components
20334 are aligned on natural boundaries. For example, 1-byte
20335 components are aligned on byte boundaries, 2-byte
20336 components on 2-byte boundaries, 4-byte components on 4-byte
20337 byte boundaries, and so on. The OpenVMS Alpha hardware
20338 runs more efficiently with naturally aligned data.
20340 On GNAT, alignment rules are compatible
20341 with HP Ada for OpenVMS Alpha.
20343 @node Address Clauses
20344 @subsection Address Clauses
20346 @noindent
20347 In HP Ada and GNAT, address clauses are supported for
20348 objects and imported subprograms.
20349 The predefined type @code{System.Address} is a private type
20350 in both compilers on Alpha OpenVMS, with the same representation
20351 (it is simply a machine pointer). Addition, subtraction, and comparison
20352 operations are available in the standard Ada package
20353 @code{System.Storage_Elements}, or in package @code{System}
20354 if it is extended to include @code{System.Aux_DEC} using a
20355 pragma @code{Extend_System} as previously described.
20357 Note that code that @code{with}'s both this extended package @code{System}
20358 and the package @code{System.Storage_Elements} should not @code{use}
20359 both packages, or ambiguities will result. In general it is better
20360 not to mix these two sets of facilities. The Ada package was
20361 designed specifically to provide the kind of features that HP Ada
20362 adds directly to package @code{System}.
20364 The type @code{System.Address} is a 64-bit integer type in GNAT for
20365 I64 OpenVMS.  For more information,
20366 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20368 GNAT is compatible with HP Ada in its handling of address
20369 clauses, except for some limitations in
20370 the form of address clauses for composite objects with
20371 initialization. Such address clauses are easily replaced
20372 by the use of an explicitly-defined constant as described
20373 in the Ada Reference Manual (13.1(22)). For example, the sequence
20374 of declarations:
20376 @smallexample @c ada
20377 @cartouche
20378 X, Y : Integer := Init_Func;
20379 Q : String (X .. Y) := "abc";
20380 @dots{}
20381 for Q'Address use Compute_Address;
20382 @end cartouche
20383 @end smallexample
20385 @noindent
20386 will be rejected by GNAT, since the address cannot be computed at the time
20387 that @code{Q} is declared. To achieve the intended effect, write instead:
20389 @smallexample @c ada
20390 @group
20391 @cartouche
20392 X, Y : Integer := Init_Func;
20393 Q_Address : constant Address := Compute_Address;
20394 Q : String (X .. Y) := "abc";
20395 @dots{}
20396 for Q'Address use Q_Address;
20397 @end cartouche
20398 @end group
20399 @end smallexample
20401 @noindent
20402 which will be accepted by GNAT (and other Ada compilers), and is also
20403 compatible with Ada 83. A fuller description of the restrictions
20404 on address specifications is found in @ref{Top, GNAT Reference Manual,
20405 About This Guide, gnat_rm, GNAT Reference Manual}.
20407 @node Other Representation Clauses
20408 @subsection Other Representation Clauses
20410 @noindent
20411 GNAT implements in a compatible manner all the representation
20412 clauses supported by HP Ada. In addition, GNAT
20413 implements the representation clause forms that were introduced in Ada 95,
20414 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20416 @node The Package STANDARD
20417 @section The Package @code{STANDARD}
20419 @noindent
20420 The package @code{STANDARD}, as implemented by HP Ada, is fully
20421 described in the @cite{Ada Reference Manual} and in the
20422 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20423 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20425 In addition, HP Ada supports the Latin-1 character set in
20426 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20427 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20428 the type @code{WIDE_CHARACTER}.
20430 The floating-point types supported by GNAT are those
20431 supported by HP Ada, but the defaults are different, and are controlled by
20432 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20434 @node The Package SYSTEM
20435 @section The Package @code{SYSTEM}
20437 @noindent
20438 HP Ada provides a specific version of the package
20439 @code{SYSTEM} for each platform on which the language is implemented.
20440 For the complete spec of the package @code{SYSTEM}, see
20441 Appendix F of the @cite{HP Ada Language Reference Manual}.
20443 On HP Ada, the package @code{SYSTEM} includes the following conversion
20444 functions:
20445 @itemize @bullet
20446 @item @code{TO_ADDRESS(INTEGER)}
20448 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20450 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20452 @item @code{TO_INTEGER(ADDRESS)}
20454 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20456 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20457 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20458 @end itemize
20460 @noindent
20461 By default, GNAT supplies a version of @code{SYSTEM} that matches
20462 the definition given in the @cite{Ada Reference Manual}.
20463 This
20464 is a subset of the HP system definitions, which is as
20465 close as possible to the original definitions. The only difference
20466 is that the definition of @code{SYSTEM_NAME} is different:
20468 @smallexample @c ada
20469 @cartouche
20470 type Name is (SYSTEM_NAME_GNAT);
20471 System_Name : constant Name := SYSTEM_NAME_GNAT;
20472 @end cartouche
20473 @end smallexample
20475 @noindent
20476 Also, GNAT adds the Ada declarations for
20477 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20479 However, the use of the following pragma causes GNAT
20480 to extend the definition of package @code{SYSTEM} so that it
20481 encompasses the full set of HP-specific extensions,
20482 including the functions listed above:
20484 @smallexample @c ada
20485 @cartouche
20486 pragma Extend_System (Aux_DEC);
20487 @end cartouche
20488 @end smallexample
20490 @noindent
20491 The pragma @code{Extend_System} is a configuration pragma that
20492 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20493 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20495 HP Ada does not allow the recompilation of the package
20496 @code{SYSTEM}. Instead HP Ada provides several pragmas
20497 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20498 to modify values in the package @code{SYSTEM}.
20499 On OpenVMS Alpha systems, the pragma
20500 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20501 its single argument.
20503 GNAT does permit the recompilation of package @code{SYSTEM} using
20504 the special switch @option{-gnatg}, and this switch can be used if
20505 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20506 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20507 or @code{MEMORY_SIZE} by any other means.
20509 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20510 enumeration literal @code{SYSTEM_NAME_GNAT}.
20512 The definitions provided by the use of
20514 @smallexample @c ada
20515 pragma Extend_System (AUX_Dec);
20516 @end smallexample
20518 @noindent
20519 are virtually identical to those provided by the HP Ada 83 package
20520 @code{SYSTEM}. One important difference is that the name of the
20521 @code{TO_ADDRESS}
20522 function for type @code{UNSIGNED_LONGWORD} is changed to
20523 @code{TO_ADDRESS_LONG}.
20524 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20525 discussion of why this change was necessary.
20527 @noindent
20528 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20529 is in fact
20530 an extension to Ada 83 not strictly compatible with the reference manual.
20531 GNAT, in order to be exactly compatible with the standard,
20532 does not provide this capability. In HP Ada 83, the
20533 point of this definition is to deal with a call like:
20535 @smallexample @c ada
20536 TO_ADDRESS (16#12777#);
20537 @end smallexample
20539 @noindent
20540 Normally, according to Ada 83 semantics, one would expect this to be
20541 ambiguous, since it matches both the @code{INTEGER} and
20542 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20543 However, in HP Ada 83, there is no ambiguity, since the
20544 definition using @i{universal_integer} takes precedence.
20546 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20547 it is
20548 not possible to be 100% compatible. Since there are many programs using
20549 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20550 GNAT was
20551 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20552 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20554 @smallexample @c ada
20555 function To_Address (X : Integer) return Address;
20556 pragma Pure_Function (To_Address);
20558 function To_Address_Long (X : Unsigned_Longword) return Address;
20559 pragma Pure_Function (To_Address_Long);
20560 @end smallexample
20562 @noindent
20563 This means that programs using @code{TO_ADDRESS} for
20564 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20566 @node Tasking and Task-Related Features
20567 @section Tasking and Task-Related Features
20569 @noindent
20570 This section compares the treatment of tasking in GNAT
20571 and in HP Ada for OpenVMS Alpha.
20572 The GNAT description applies to both Alpha and I64 OpenVMS.
20573 For detailed information on tasking in
20574 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20575 relevant run-time reference manual.
20577 @menu
20578 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20579 * Assigning Task IDs::
20580 * Task IDs and Delays::
20581 * Task-Related Pragmas::
20582 * Scheduling and Task Priority::
20583 * The Task Stack::
20584 * External Interrupts::
20585 @end menu
20587 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20588 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20590 @noindent
20591 On OpenVMS Alpha systems, each Ada task (except a passive
20592 task) is implemented as a single stream of execution
20593 that is created and managed by the kernel. On these
20594 systems, HP Ada tasking support is based on DECthreads,
20595 an implementation of the POSIX standard for threads.
20597 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20598 code that calls DECthreads routines can be used together.
20599 The interaction between Ada tasks and DECthreads routines
20600 can have some benefits. For example when on OpenVMS Alpha,
20601 HP Ada can call C code that is already threaded.
20603 GNAT uses the facilities of DECthreads,
20604 and Ada tasks are mapped to threads.
20606 @node Assigning Task IDs
20607 @subsection Assigning Task IDs
20609 @noindent
20610 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20611 the environment task that executes the main program. On
20612 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20613 that have been created but are not yet activated.
20615 On OpenVMS Alpha systems, task IDs are assigned at
20616 activation. On GNAT systems, task IDs are also assigned at
20617 task creation but do not have the same form or values as
20618 task ID values in HP Ada. There is no null task, and the
20619 environment task does not have a specific task ID value.
20621 @node Task IDs and Delays
20622 @subsection Task IDs and Delays
20624 @noindent
20625 On OpenVMS Alpha systems, tasking delays are implemented
20626 using Timer System Services. The Task ID is used for the
20627 identification of the timer request (the @code{REQIDT} parameter).
20628 If Timers are used in the application take care not to use
20629 @code{0} for the identification, because cancelling such a timer
20630 will cancel all timers and may lead to unpredictable results.
20632 @node Task-Related Pragmas
20633 @subsection Task-Related Pragmas
20635 @noindent
20636 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20637 specification of the size of the guard area for a task
20638 stack. (The guard area forms an area of memory that has no
20639 read or write access and thus helps in the detection of
20640 stack overflow.) On OpenVMS Alpha systems, if the pragma
20641 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20642 area is created. In the absence of a pragma @code{TASK_STORAGE},
20643 a default guard area is created.
20645 GNAT supplies the following task-related pragmas:
20647 @itemize @bullet
20648 @item  @code{TASK_INFO}
20650 This pragma appears within a task definition and
20651 applies to the task in which it appears. The argument
20652 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20654 @item  @code{TASK_STORAGE}
20656 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20657 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20658 @code{SUPPRESS}, and @code{VOLATILE}.
20659 @end itemize
20660 @node Scheduling and Task Priority
20661 @subsection Scheduling and Task Priority
20663 @noindent
20664 HP Ada implements the Ada language requirement that
20665 when two tasks are eligible for execution and they have
20666 different priorities, the lower priority task does not
20667 execute while the higher priority task is waiting. The HP
20668 Ada Run-Time Library keeps a task running until either the
20669 task is suspended or a higher priority task becomes ready.
20671 On OpenVMS Alpha systems, the default strategy is round-
20672 robin with preemption. Tasks of equal priority take turns
20673 at the processor. A task is run for a certain period of
20674 time and then placed at the tail of the ready queue for
20675 its priority level.
20677 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20678 which can be used to enable or disable round-robin
20679 scheduling of tasks with the same priority.
20680 See the relevant HP Ada run-time reference manual for
20681 information on using the pragmas to control HP Ada task
20682 scheduling.
20684 GNAT follows the scheduling rules of Annex D (Real-Time
20685 Annex) of the @cite{Ada Reference Manual}. In general, this
20686 scheduling strategy is fully compatible with HP Ada
20687 although it provides some additional constraints (as
20688 fully documented in Annex D).
20689 GNAT implements time slicing control in a manner compatible with
20690 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20691 are identical to the HP Ada 83 pragma of the same name.
20692 Note that it is not possible to mix GNAT tasking and
20693 HP Ada 83 tasking in the same program, since the two run-time
20694 libraries are not compatible.
20696 @node The Task Stack
20697 @subsection The Task Stack
20699 @noindent
20700 In HP Ada, a task stack is allocated each time a
20701 non-passive task is activated. As soon as the task is
20702 terminated, the storage for the task stack is deallocated.
20703 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20704 a default stack size is used. Also, regardless of the size
20705 specified, some additional space is allocated for task
20706 management purposes. On OpenVMS Alpha systems, at least
20707 one page is allocated.
20709 GNAT handles task stacks in a similar manner. In accordance with
20710 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20711 an alternative method for controlling the task stack size.
20712 The specification of the attribute @code{T'STORAGE_SIZE} is also
20713 supported in a manner compatible with HP Ada.
20715 @node External Interrupts
20716 @subsection External Interrupts
20718 @noindent
20719 On HP Ada, external interrupts can be associated with task entries.
20720 GNAT is compatible with HP Ada in its handling of external interrupts.
20722 @node Pragmas and Pragma-Related Features
20723 @section Pragmas and Pragma-Related Features
20725 @noindent
20726 Both HP Ada and GNAT supply all language-defined pragmas
20727 as specified by the Ada 83 standard. GNAT also supplies all
20728 language-defined pragmas introduced by Ada 95 and Ada 2005.
20729 In addition, GNAT implements the implementation-defined pragmas
20730 from HP Ada 83.
20732 @itemize @bullet
20733 @item  @code{AST_ENTRY}
20735 @item  @code{COMMON_OBJECT}
20737 @item  @code{COMPONENT_ALIGNMENT}
20739 @item  @code{EXPORT_EXCEPTION}
20741 @item  @code{EXPORT_FUNCTION}
20743 @item  @code{EXPORT_OBJECT}
20745 @item  @code{EXPORT_PROCEDURE}
20747 @item  @code{EXPORT_VALUED_PROCEDURE}
20749 @item  @code{FLOAT_REPRESENTATION}
20751 @item  @code{IDENT}
20753 @item  @code{IMPORT_EXCEPTION}
20755 @item  @code{IMPORT_FUNCTION}
20757 @item  @code{IMPORT_OBJECT}
20759 @item  @code{IMPORT_PROCEDURE}
20761 @item  @code{IMPORT_VALUED_PROCEDURE}
20763 @item  @code{INLINE_GENERIC}
20765 @item  @code{INTERFACE_NAME}
20767 @item  @code{LONG_FLOAT}
20769 @item  @code{MAIN_STORAGE}
20771 @item  @code{PASSIVE}
20773 @item  @code{PSECT_OBJECT}
20775 @item  @code{SHARE_GENERIC}
20777 @item  @code{SUPPRESS_ALL}
20779 @item  @code{TASK_STORAGE}
20781 @item  @code{TIME_SLICE}
20783 @item  @code{TITLE}
20784 @end itemize
20786 @noindent
20787 These pragmas are all fully implemented, with the exception of @code{TITLE},
20788 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20789 recognized, but which have no
20790 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20791 use of Ada protected objects. In GNAT, all generics are inlined.
20793 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20794 a separate subprogram specification which must appear before the
20795 subprogram body.
20797 GNAT also supplies a number of implementation-defined pragmas including the
20798 following:
20800 @itemize @bullet
20801 @item  @code{ABORT_DEFER}
20803 @item  @code{ADA_83}
20805 @item  @code{ADA_95}
20807 @item  @code{ADA_05}
20809 @item  @code{Ada_2005}
20811 @item  @code{Ada_12}
20813 @item  @code{Ada_2012}
20815 @item  @code{ANNOTATE}
20817 @item  @code{ASSERT}
20819 @item  @code{C_PASS_BY_COPY}
20821 @item  @code{CPP_CLASS}
20823 @item  @code{CPP_CONSTRUCTOR}
20825 @item  @code{CPP_DESTRUCTOR}
20827 @item  @code{DEBUG}
20829 @item  @code{EXTEND_SYSTEM}
20831 @item  @code{LINKER_ALIAS}
20833 @item  @code{LINKER_SECTION}
20835 @item  @code{MACHINE_ATTRIBUTE}
20837 @item  @code{NO_RETURN}
20839 @item  @code{PURE_FUNCTION}
20841 @item  @code{SOURCE_FILE_NAME}
20843 @item  @code{SOURCE_REFERENCE}
20845 @item  @code{TASK_INFO}
20847 @item  @code{UNCHECKED_UNION}
20849 @item  @code{UNIMPLEMENTED_UNIT}
20851 @item  @code{UNIVERSAL_DATA}
20853 @item  @code{UNSUPPRESS}
20855 @item  @code{WARNINGS}
20857 @item  @code{WEAK_EXTERNAL}
20858 @end itemize
20860 @noindent
20861 For full details on these and other GNAT implementation-defined pragmas,
20862 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20863 Manual}.
20865 @menu
20866 * Restrictions on the Pragma INLINE::
20867 * Restrictions on the Pragma INTERFACE::
20868 * Restrictions on the Pragma SYSTEM_NAME::
20869 @end menu
20871 @node Restrictions on the Pragma INLINE
20872 @subsection Restrictions on Pragma @code{INLINE}
20874 @noindent
20875 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20876 @itemize @bullet
20877 @item  Parameters cannot have a task type.
20879 @item  Function results cannot be task types, unconstrained
20880 array types, or unconstrained types with discriminants.
20882 @item  Bodies cannot declare the following:
20883 @itemize @bullet
20884 @item  Subprogram body or stub (imported subprogram is allowed)
20886 @item  Tasks
20888 @item  Generic declarations
20890 @item  Instantiations
20892 @item  Exceptions
20894 @item  Access types (types derived from access types allowed)
20896 @item  Array or record types
20898 @item  Dependent tasks
20900 @item  Direct recursive calls of subprogram or containing
20901 subprogram, directly or via a renaming
20903 @end itemize
20904 @end itemize
20906 @noindent
20907 In GNAT, the only restriction on pragma @code{INLINE} is that the
20908 body must occur before the call if both are in the same
20909 unit, and the size must be appropriately small. There are
20910 no other specific restrictions which cause subprograms to
20911 be incapable of being inlined.
20913 @node  Restrictions on the Pragma INTERFACE
20914 @subsection  Restrictions on Pragma @code{INTERFACE}
20916 @noindent
20917 The following restrictions on pragma @code{INTERFACE}
20918 are enforced by both HP Ada and GNAT:
20919 @itemize @bullet
20920 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20921 Default is the default on OpenVMS Alpha systems.
20923 @item  Parameter passing: Language specifies default
20924 mechanisms but can be overridden with an @code{EXPORT} pragma.
20926 @itemize @bullet
20927 @item  Ada: Use internal Ada rules.
20929 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20930 record or task type. Result cannot be a string, an
20931 array, or a record.
20933 @item  Fortran: Parameters cannot have a task type. Result cannot
20934 be a string, an array, or a record.
20935 @end itemize
20936 @end itemize
20938 @noindent
20939 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20940 record parameters for all languages.
20942 @node  Restrictions on the Pragma SYSTEM_NAME
20943 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
20945 @noindent
20946 For HP Ada for OpenVMS Alpha, the enumeration literal
20947 for the type @code{NAME} is @code{OPENVMS_AXP}.
20948 In GNAT, the enumeration
20949 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20951 @node  Library of Predefined Units
20952 @section  Library of Predefined Units
20954 @noindent
20955 A library of predefined units is provided as part of the
20956 HP Ada and GNAT implementations. HP Ada does not provide
20957 the package @code{MACHINE_CODE} but instead recommends importing
20958 assembler code.
20960 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20961 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20962 version.
20963 The HP Ada Predefined Library units are modified to remove post-Ada 83
20964 incompatibilities and to make them interoperable with GNAT
20965 (@pxref{Changes to DECLIB}, for details).
20966 The units are located in the @file{DECLIB} directory.
20968 The GNAT RTL is contained in
20969 the @file{ADALIB} directory, and
20970 the default search path is set up to find @code{DECLIB} units in preference
20971 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20972 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20974 @menu
20975 * Changes to DECLIB::
20976 @end menu
20978 @node Changes to DECLIB
20979 @subsection Changes to @code{DECLIB}
20981 @noindent
20982 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20983 compatibility are minor and include the following:
20985 @itemize @bullet
20986 @item  Adjusting the location of pragmas and record representation
20987 clauses to obey Ada 95 (and thus Ada 2005) rules
20989 @item  Adding the proper notation to generic formal parameters
20990 that take unconstrained types in instantiation
20992 @item  Adding pragma @code{ELABORATE_BODY} to package specs
20993 that have package bodies not otherwise allowed
20995 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20996 ``@code{PROTECTD}''.
20997 Currently these are found only in the @code{STARLET} package spec.
20999 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21000 where the address size is constrained to 32 bits.
21001 @end itemize
21003 @noindent
21004 None of the above changes is visible to users.
21006 @node Bindings
21007 @section Bindings
21009 @noindent
21010 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21011 @itemize @bullet
21013 @item  Command Language Interpreter (CLI interface)
21015 @item  DECtalk Run-Time Library (DTK interface)
21017 @item  Librarian utility routines (LBR interface)
21019 @item  General Purpose Run-Time Library (LIB interface)
21021 @item  Math Run-Time Library (MTH interface)
21023 @item  National Character Set Run-Time Library (NCS interface)
21025 @item  Compiled Code Support Run-Time Library (OTS interface)
21027 @item  Parallel Processing Run-Time Library (PPL interface)
21029 @item  Screen Management Run-Time Library (SMG interface)
21031 @item  Sort Run-Time Library (SOR interface)
21033 @item  String Run-Time Library (STR interface)
21035 @item STARLET System Library
21036 @findex Starlet
21038 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21040 @item  X Windows Toolkit (XT interface)
21042 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21043 @end itemize
21045 @noindent
21046 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21047 directory, on both the Alpha and I64 OpenVMS platforms.
21049 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21050 in the
21051 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21052 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21053 @code{Xt}, and @code{X_Lib}
21054 causing the default X/Motif sharable image libraries to be linked in. This
21055 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21056 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21058 It may be necessary to edit these options files to update or correct the
21059 library names if, for example, the newer X/Motif bindings from
21060 @file{ADA$EXAMPLES}
21061 had been (previous to installing GNAT) copied and renamed to supersede the
21062 default @file{ADA$PREDEFINED} versions.
21064 @menu
21065 * Shared Libraries and Options Files::
21066 * Interfaces to C::
21067 @end menu
21069 @node Shared Libraries and Options Files
21070 @subsection Shared Libraries and Options Files
21072 @noindent
21073 When using the HP Ada
21074 predefined X and Motif bindings, the linking with their sharable images is
21075 done automatically by @command{GNAT LINK}.
21076 When using other X and Motif bindings, you need
21077 to add the corresponding sharable images to the command line for
21078 @code{GNAT LINK}. When linking with shared libraries, or with
21079 @file{.OPT} files, you must
21080 also add them to the command line for @command{GNAT LINK}.
21082 A shared library to be used with GNAT is built in the same way as other
21083 libraries under VMS. The VMS Link command can be used in standard fashion.
21085 @node Interfaces to C
21086 @subsection Interfaces to C
21088 @noindent
21089 HP Ada
21090 provides the following Ada types and operations:
21092 @itemize @bullet
21093 @item C types package (@code{C_TYPES})
21095 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21097 @item Other_types (@code{SHORT_INT})
21098 @end itemize
21100 @noindent
21101 Interfacing to C with GNAT, you can use the above approach
21102 described for HP Ada or the facilities of Annex B of
21103 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21104 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21105 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21107 The @option{-gnatF} qualifier forces default and explicit
21108 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21109 to be uppercased for compatibility with the default behavior
21110 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21112 @node Main Program Definition
21113 @section Main Program Definition
21115 @noindent
21116 The following section discusses differences in the
21117 definition of main programs on HP Ada and GNAT.
21118 On HP Ada, main programs are defined to meet the
21119 following conditions:
21120 @itemize @bullet
21121 @item  Procedure with no formal parameters (returns @code{0} upon
21122 normal completion)
21124 @item  Procedure with no formal parameters (returns @code{42} when
21125 an unhandled exception is raised)
21127 @item  Function with no formal parameters whose returned value
21128 is of a discrete type
21130 @item  Procedure with one @code{out} formal of a discrete type for
21131 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21133 @end itemize
21135 @noindent
21136 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21137 a main function or main procedure returns a discrete
21138 value whose size is less than 64 bits (32 on VAX systems),
21139 the value is zero- or sign-extended as appropriate.
21140 On GNAT, main programs are defined as follows:
21141 @itemize @bullet
21142 @item  Must be a non-generic, parameterless subprogram that
21143 is either a procedure or function returning an Ada
21144 @code{STANDARD.INTEGER} (the predefined type)
21146 @item  Cannot be a generic subprogram or an instantiation of a
21147 generic subprogram
21148 @end itemize
21150 @node Implementation-Defined Attributes
21151 @section Implementation-Defined Attributes
21153 @noindent
21154 GNAT provides all HP Ada implementation-defined
21155 attributes.
21157 @node Compiler and Run-Time Interfacing
21158 @section Compiler and Run-Time Interfacing
21160 @noindent
21161 HP Ada provides the following qualifiers to pass options to the linker
21162 (ACS LINK):
21163 @itemize @bullet
21164 @item  @option{/WAIT} and @option{/SUBMIT}
21166 @item  @option{/COMMAND}
21168 @item  @option{/@r{[}NO@r{]}MAP}
21170 @item  @option{/OUTPUT=@var{file-spec}}
21172 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21173 @end itemize
21175 @noindent
21176 To pass options to the linker, GNAT provides the following
21177 switches:
21179 @itemize @bullet
21180 @item   @option{/EXECUTABLE=@var{exec-name}}
21182 @item   @option{/VERBOSE}
21184 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21185 @end itemize
21187 @noindent
21188 For more information on these switches, see
21189 @ref{Switches for gnatlink}.
21190 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21191 to control optimization. HP Ada also supplies the
21192 following pragmas:
21193 @itemize @bullet
21194 @item  @code{OPTIMIZE}
21196 @item  @code{INLINE}
21198 @item  @code{INLINE_GENERIC}
21200 @item  @code{SUPPRESS_ALL}
21202 @item  @code{PASSIVE}
21203 @end itemize
21205 @noindent
21206 In GNAT, optimization is controlled strictly by command
21207 line parameters, as described in the corresponding section of this guide.
21208 The HP pragmas for control of optimization are
21209 recognized but ignored.
21211 Note that in GNAT, the default is optimization off, whereas in HP Ada
21212 the default is that optimization is turned on.
21214 @node Program Compilation and Library Management
21215 @section Program Compilation and Library Management
21217 @noindent
21218 HP Ada and GNAT provide a comparable set of commands to
21219 build programs. HP Ada also provides a program library,
21220 which is a concept that does not exist on GNAT. Instead,
21221 GNAT provides directories of sources that are compiled as
21222 needed.
21224 The following table summarizes
21225 the HP Ada commands and provides
21226 equivalent GNAT commands. In this table, some GNAT
21227 equivalents reflect the fact that GNAT does not use the
21228 concept of a program library. Instead, it uses a model
21229 in which collections of source and object files are used
21230 in a manner consistent with other languages like C and
21231 Fortran. Therefore, standard system file commands are used
21232 to manipulate these elements. Those GNAT commands are marked with
21233 an asterisk.
21234 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21236 @need 1500
21237 @multitable @columnfractions .35 .65
21239 @item @emph{HP Ada Command}
21240 @tab @emph{GNAT Equivalent / Description}
21242 @item @command{ADA}
21243 @tab @command{GNAT COMPILE}@*
21244 Invokes the compiler to compile one or more Ada source files.
21246 @item @command{ACS ATTACH}@*
21247 @tab [No equivalent]@*
21248 Switches control of terminal from current process running the program
21249 library manager.
21251 @item @command{ACS CHECK}
21252 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21253 Forms the execution closure of one
21254 or more compiled units and checks completeness and currency.
21256 @item @command{ACS COMPILE}
21257 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21258 Forms the execution closure of one or
21259 more specified units, checks completeness and currency,
21260 identifies units that have revised source files, compiles same,
21261 and recompiles units that are or will become obsolete.
21262 Also completes incomplete generic instantiations.
21264 @item @command{ACS COPY FOREIGN}
21265 @tab Copy (*)@*
21266 Copies a foreign object file into the program library as a
21267 library unit body.
21269 @item @command{ACS COPY UNIT}
21270 @tab Copy (*)@*
21271 Copies a compiled unit from one program library to another.
21273 @item @command{ACS CREATE LIBRARY}
21274 @tab Create /directory (*)@*
21275 Creates a program library.
21277 @item @command{ACS CREATE SUBLIBRARY}
21278 @tab Create /directory (*)@*
21279 Creates a program sublibrary.
21281 @item @command{ACS DELETE LIBRARY}
21282 @tab @*
21283 Deletes a program library and its contents.
21285 @item @command{ACS DELETE SUBLIBRARY}
21286 @tab @*
21287 Deletes a program sublibrary and its contents.
21289 @item @command{ACS DELETE UNIT}
21290 @tab Delete file (*)@*
21291 On OpenVMS systems, deletes one or more compiled units from
21292 the current program library.
21294 @item @command{ACS DIRECTORY}
21295 @tab Directory (*)@*
21296 On OpenVMS systems, lists units contained in the current
21297 program library.
21299 @item @command{ACS ENTER FOREIGN}
21300 @tab Copy (*)@*
21301 Allows the import of a foreign body as an Ada library
21302 spec and enters a reference to a pointer.
21304 @item @command{ACS ENTER UNIT}
21305 @tab Copy (*)@*
21306 Enters a reference (pointer) from the current program library to
21307 a unit compiled into another program library.
21309 @item @command{ACS EXIT}
21310 @tab [No equivalent]@*
21311 Exits from the program library manager.
21313 @item @command{ACS EXPORT}
21314 @tab Copy (*)@*
21315 Creates an object file that contains system-specific object code
21316 for one or more units. With GNAT, object files can simply be copied
21317 into the desired directory.
21319 @item @command{ACS EXTRACT SOURCE}
21320 @tab Copy (*)@*
21321 Allows access to the copied source file for each Ada compilation unit
21323 @item @command{ACS HELP}
21324 @tab @command{HELP GNAT}@*
21325 Provides online help.
21327 @item @command{ACS LINK}
21328 @tab @command{GNAT LINK}@*
21329 Links an object file containing Ada units into an executable file.
21331 @item @command{ACS LOAD}
21332 @tab Copy (*)@*
21333 Loads (partially compiles) Ada units into the program library.
21334 Allows loading a program from a collection of files into a library
21335 without knowing the relationship among units.
21337 @item @command{ACS MERGE}
21338 @tab Copy (*)@*
21339 Merges into the current program library, one or more units from
21340 another library where they were modified.
21342 @item @command{ACS RECOMPILE}
21343 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21344 Recompiles from   external or copied source files any obsolete
21345 unit in the closure. Also, completes any incomplete generic
21346 instantiations.
21348 @item @command{ACS REENTER}
21349 @tab @command{GNAT MAKE}@*
21350 Reenters current references to units compiled after last entered
21351 with the @command{ACS ENTER UNIT} command.
21353 @item @command{ACS SET LIBRARY}
21354 @tab Set default (*)@*
21355 Defines a program library to be the compilation context as well
21356 as the target library for compiler output and commands in general.
21358 @item @command{ACS SET PRAGMA}
21359 @tab Edit @file{gnat.adc} (*)@*
21360 Redefines specified  values of the library characteristics
21361 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21362 and @code{Float_Representation}.
21364 @item @command{ACS SET SOURCE}
21365 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21366 Defines the source file search list for the @command{ACS COMPILE} command.
21368 @item @command{ACS SHOW LIBRARY}
21369 @tab Directory (*)@*
21370 Lists information about one or more program libraries.
21372 @item @command{ACS SHOW PROGRAM}
21373 @tab [No equivalent]@*
21374 Lists information about the execution closure of one or
21375 more units in the program library.
21377 @item @command{ACS SHOW SOURCE}
21378 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21379 Shows the source file search used when compiling units.
21381 @item @command{ACS SHOW VERSION}
21382 @tab Compile with @option{VERBOSE} option
21383 Displays the version number of the compiler and program library
21384 manager used.
21386 @item @command{ACS SPAWN}
21387 @tab [No equivalent]@*
21388 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21389 command).
21391 @item @command{ACS VERIFY}
21392 @tab [No equivalent]@*
21393 Performs a series of consistency checks on a program library to
21394 determine whether the library structure and library files are in
21395 valid form.
21396 @end multitable
21398 @noindent
21400 @node Input-Output
21401 @section Input-Output
21403 @noindent
21404 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21405 Management Services (RMS) to perform operations on
21406 external files.
21408 @noindent
21409 HP Ada and GNAT predefine an identical set of input-
21410 output packages. To make the use of the
21411 generic @code{TEXT_IO} operations more convenient, HP Ada
21412 provides predefined library packages that instantiate the
21413 integer and floating-point operations for the predefined
21414 integer and floating-point types as shown in the following table.
21416 @multitable @columnfractions .45 .55
21417 @item @emph{Package Name} @tab Instantiation
21419 @item @code{INTEGER_TEXT_IO}
21420 @tab @code{INTEGER_IO(INTEGER)}
21422 @item @code{SHORT_INTEGER_TEXT_IO}
21423 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21425 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21426 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21428 @item @code{FLOAT_TEXT_IO}
21429 @tab @code{FLOAT_IO(FLOAT)}
21431 @item @code{LONG_FLOAT_TEXT_IO}
21432 @tab @code{FLOAT_IO(LONG_FLOAT)}
21433 @end multitable
21435 @noindent
21436 The HP Ada predefined packages and their operations
21437 are implemented using OpenVMS Alpha files and input-output
21438 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21439 Familiarity with the following is recommended:
21440 @itemize @bullet
21441 @item  RMS file organizations and access methods
21443 @item  OpenVMS file specifications and directories
21445 @item  OpenVMS File Definition Language (FDL)
21446 @end itemize
21448 @noindent
21449 GNAT provides I/O facilities that are completely
21450 compatible with HP Ada. The distribution includes the
21451 standard HP Ada versions of all I/O packages, operating
21452 in a manner compatible with HP Ada. In particular, the
21453 following packages are by default the HP Ada (Ada 83)
21454 versions of these packages rather than the renamings
21455 suggested in Annex J of the Ada Reference Manual:
21456 @itemize @bullet
21457 @item  @code{TEXT_IO}
21459 @item  @code{SEQUENTIAL_IO}
21461 @item  @code{DIRECT_IO}
21462 @end itemize
21464 @noindent
21465 The use of the standard child package syntax (for
21466 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21467 packages.
21468 GNAT provides HP-compatible predefined instantiations
21469 of the @code{TEXT_IO} packages, and also
21470 provides the standard predefined instantiations required
21471 by the @cite{Ada Reference Manual}.
21473 For further information on how GNAT interfaces to the file
21474 system or how I/O is implemented in programs written in
21475 mixed languages, see @ref{Implementation of the Standard I/O,,,
21476 gnat_rm, GNAT Reference Manual}.
21477 This chapter covers the following:
21478 @itemize @bullet
21479 @item  Standard I/O packages
21481 @item  @code{FORM} strings
21483 @item  @code{ADA.DIRECT_IO}
21485 @item  @code{ADA.SEQUENTIAL_IO}
21487 @item  @code{ADA.TEXT_IO}
21489 @item  Stream pointer positioning
21491 @item  Reading and writing non-regular files
21493 @item  @code{GET_IMMEDIATE}
21495 @item  Treating @code{TEXT_IO} files as streams
21497 @item  Shared files
21499 @item  Open modes
21500 @end itemize
21502 @node Implementation Limits
21503 @section Implementation Limits
21505 @noindent
21506 The following table lists implementation limits for HP Ada
21507 and GNAT systems.
21508 @multitable @columnfractions .60 .20 .20
21509 @sp 1
21510 @item  @emph{Compilation Parameter}
21511 @tab   @emph{HP Ada}
21512 @tab   @emph{GNAT}
21513 @sp 1
21515 @item  In a subprogram or entry  declaration, maximum number of
21516 formal parameters that are of an unconstrained record type
21517 @tab   32
21518 @tab   No set limit
21519 @sp 1
21521 @item  Maximum identifier length (number of characters)
21522 @tab   255
21523 @tab   32766
21524 @sp 1
21526 @item  Maximum number of characters in a source line
21527 @tab   255
21528 @tab   32766
21529 @sp 1
21531 @item  Maximum collection size   (number of bytes)
21532 @tab   2**31-1
21533 @tab   2**31-1
21534 @sp 1
21536 @item  Maximum number of discriminants for a record type
21537 @tab   245
21538 @tab   No set limit
21539 @sp 1
21541 @item  Maximum number of formal parameters in an entry or
21542 subprogram declaration
21543 @tab   246
21544 @tab    No set limit
21545 @sp 1
21547 @item  Maximum number of dimensions in an array type
21548 @tab   255
21549 @tab   No set limit
21550 @sp 1
21552 @item  Maximum number of library  units and subunits in a compilation.
21553 @tab   4095
21554 @tab   No set limit
21555 @sp 1
21557 @item  Maximum number of library units and subunits in an execution.
21558 @tab   16383
21559 @tab   No set limit
21560 @sp 1
21562 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21563 or @code{PSECT_OBJECT}
21564 @tab   32757
21565 @tab   No set limit
21566 @sp 1
21568 @item  Maximum number of enumeration literals in an enumeration type
21569 definition
21570 @tab   65535
21571 @tab   No set limit
21572 @sp 1
21574 @item  Maximum number of lines in a source file
21575 @tab   65534
21576 @tab   No set limit
21577 @sp 1
21579 @item  Maximum number of bits in any object
21580 @tab   2**31-1
21581 @tab   2**31-1
21582 @sp 1
21584 @item  Maximum size of the static portion of a stack frame (approximate)
21585 @tab   2**31-1
21586 @tab   2**31-1
21587 @end multitable
21589 @node Tools and Utilities
21590 @section Tools and Utilities
21592 @noindent
21593 The following table lists some of the OpenVMS development tools
21594 available for HP Ada, and the corresponding tools for
21595 use with @value{EDITION} on Alpha and I64 platforms.
21596 Aside from the debugger, all the OpenVMS tools identified are part
21597 of the DECset package.
21599 @iftex
21600 @c Specify table in TeX since Texinfo does a poor job
21601 @tex
21602 \smallskip
21603 \smallskip
21604 \settabs\+Language-Sensitive Editor\quad
21605    &Product with HP Ada\quad
21606    &\cr
21607 \+\it Tool
21608    &\it Product with HP Ada
21609    & \it Product with GNAT Pro\cr
21610 \smallskip
21611 \+Code Management System
21612    &HP CMS
21613    & HP CMS\cr
21614 \smallskip
21615 \+Language-Sensitive Editor
21616    &HP LSE
21617    & emacs or HP LSE (Alpha)\cr
21619    &
21620    & HP LSE (I64)\cr
21621 \smallskip
21622 \+Debugger
21623    &OpenVMS Debug
21624    & gdb (Alpha),\cr
21626    &
21627    & OpenVMS Debug (I64)\cr
21628 \smallskip
21629 \+Source Code Analyzer /
21630    &HP SCA
21631    & GNAT XREF\cr
21632 \+Cross Referencer
21633    &
21634    &\cr
21635 \smallskip
21636 \+Test Manager
21637    &HP Digital Test
21638    & HP DTM\cr
21640    &Manager (DTM)
21641    &\cr
21642 \smallskip
21643 \+Performance and
21644    & HP PCA
21645    & HP PCA\cr
21646 \+Coverage Analyzer
21647    &
21648    &\cr
21649 \smallskip
21650 \+Module Management
21651    & HP MMS
21652    & Not applicable\cr
21653 \+ System
21654    &
21655    &\cr
21656 \smallskip
21657 \smallskip
21658 @end tex
21659 @end iftex
21661 @ifnottex
21662 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21663 @c the TeX version above for the printed version
21664 @flushleft
21665 @c @multitable @columnfractions .3 .4 .4
21666 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21667 @item @i{Tool}
21668 @tab @i{Tool with HP Ada}
21669 @tab @i{Tool with @value{EDITION}}
21670 @item Code Management@*System
21671 @tab HP CMS
21672 @tab HP CMS
21673 @item Language-Sensitive@*Editor
21674 @tab HP LSE
21675 @tab emacs or HP LSE (Alpha)
21676 @item
21677 @tab
21678 @tab HP LSE (I64)
21679 @item Debugger
21680 @tab OpenVMS Debug
21681 @tab gdb (Alpha),
21682 @item
21683 @tab
21684 @tab OpenVMS Debug (I64)
21685 @item Source Code Analyzer /@*Cross Referencer
21686 @tab HP SCA
21687 @tab GNAT XREF
21688 @item Test Manager
21689 @tab HP Digital Test@*Manager (DTM)
21690 @tab HP DTM
21691 @item Performance and@*Coverage Analyzer
21692 @tab HP PCA
21693 @tab HP PCA
21694 @item Module Management@*System
21695 @tab HP MMS
21696 @tab Not applicable
21697 @end multitable
21698 @end flushleft
21699 @end ifnottex
21701 @end ifset
21703 @c **************************************
21704 @node Platform-Specific Information for the Run-Time Libraries
21705 @appendix Platform-Specific Information for the Run-Time Libraries
21706 @cindex Tasking and threads libraries
21707 @cindex Threads libraries and tasking
21708 @cindex Run-time libraries (platform-specific information)
21710 @noindent
21711 The GNAT run-time implementation may vary with respect to both the
21712 underlying threads library and the exception handling scheme.
21713 For threads support, one or more of the following are supplied:
21714 @itemize @bullet
21715 @item @b{native threads library}, a binding to the thread package from
21716 the underlying operating system
21718 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21719 POSIX thread package
21720 @end itemize
21722 @noindent
21723 For exception handling, either or both of two models are supplied:
21724 @itemize @bullet
21725 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21726 Most programs should experience a substantial speed improvement by
21727 being compiled with a ZCX run-time.
21728 This is especially true for
21729 tasking applications or applications with many exception handlers.}
21730 @cindex Zero-Cost Exceptions
21731 @cindex ZCX (Zero-Cost Exceptions)
21732 which uses binder-generated tables that
21733 are interrogated at run time to locate a handler
21735 @item @b{setjmp / longjmp} (``SJLJ''),
21736 @cindex setjmp/longjmp Exception Model
21737 @cindex SJLJ (setjmp/longjmp Exception Model)
21738 which uses dynamically-set data to establish
21739 the set of handlers
21740 @end itemize
21742 @noindent
21743 This appendix summarizes which combinations of threads and exception support
21744 are supplied on various GNAT platforms.
21745 It then shows how to select a particular library either
21746 permanently or temporarily,
21747 explains the properties of (and tradeoffs among) the various threads
21748 libraries, and provides some additional
21749 information about several specific platforms.
21751 @menu
21752 * Summary of Run-Time Configurations::
21753 * Specifying a Run-Time Library::
21754 * Choosing the Scheduling Policy::
21755 * Solaris-Specific Considerations::
21756 * Linux-Specific Considerations::
21757 * AIX-Specific Considerations::
21758 * Irix-Specific Considerations::
21759 * RTX-Specific Considerations::
21760 * HP-UX-Specific Considerations::
21761 @end menu
21763 @node Summary of Run-Time Configurations
21764 @section Summary of Run-Time Configurations
21766 @multitable @columnfractions .30 .70
21767 @item @b{alpha-openvms}
21768 @item @code{@ @ }@i{rts-native (default)}
21769 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21770 @item @code{@ @ @ @ }Exceptions @tab ZCX
21772 @item @b{alpha-tru64}
21773 @item @code{@ @ }@i{rts-native (default)}
21774 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21775 @item @code{@ @ @ @ }Exceptions @tab ZCX
21777 @item @code{@ @ }@i{rts-sjlj}
21778 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21779 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21781 @item @b{ia64-hp_linux}
21782 @item @code{@ @ }@i{rts-native (default)}
21783 @item @code{@ @ @ @ }Tasking    @tab pthread library
21784 @item @code{@ @ @ @ }Exceptions @tab ZCX
21786 @item @b{ia64-hpux}
21787 @item @code{@ @ }@i{rts-native (default)}
21788 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21789 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21791 @item @b{ia64-openvms}
21792 @item @code{@ @ }@i{rts-native (default)}
21793 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21794 @item @code{@ @ @ @ }Exceptions @tab ZCX
21796 @item @b{ia64-sgi_linux}
21797 @item @code{@ @ }@i{rts-native (default)}
21798 @item @code{@ @ @ @ }Tasking    @tab pthread library
21799 @item @code{@ @ @ @ }Exceptions @tab ZCX
21801 @item @b{mips-irix}
21802 @item @code{@ @ }@i{rts-native (default)}
21803 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
21804 @item @code{@ @ @ @ }Exceptions @tab ZCX
21806 @item @b{pa-hpux}
21807 @item @code{@ @ }@i{rts-native (default)}
21808 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21809 @item @code{@ @ @ @ }Exceptions @tab ZCX
21811 @item @code{@ @ }@i{rts-sjlj}
21812 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21813 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21815 @item @b{ppc-aix}
21816 @item @code{@ @ }@i{rts-native (default)}
21817 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21818 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21820 @item @b{ppc-darwin}
21821 @item @code{@ @ }@i{rts-native (default)}
21822 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21823 @item @code{@ @ @ @ }Exceptions @tab ZCX
21825 @item @b{sparc-solaris}  @tab
21826 @item @code{@ @ }@i{rts-native (default)}
21827 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21828 @item @code{@ @ @ @ }Exceptions @tab ZCX
21830 @item @code{@ @ }@i{rts-pthread}
21831 @item @code{@ @ @ @ }Tasking    @tab pthread library
21832 @item @code{@ @ @ @ }Exceptions @tab ZCX
21834 @item @code{@ @ }@i{rts-sjlj}
21835 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21836 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21838 @item @b{sparc64-solaris}  @tab
21839 @item @code{@ @ }@i{rts-native (default)}
21840 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21841 @item @code{@ @ @ @ }Exceptions @tab ZCX
21843 @item @b{x86-linux}
21844 @item @code{@ @ }@i{rts-native (default)}
21845 @item @code{@ @ @ @ }Tasking    @tab pthread library
21846 @item @code{@ @ @ @ }Exceptions @tab ZCX
21848 @item @code{@ @ }@i{rts-sjlj}
21849 @item @code{@ @ @ @ }Tasking    @tab pthread library
21850 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21852 @item @b{x86-lynx}
21853 @item @code{@ @ }@i{rts-native (default)}
21854 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21855 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21857 @item @b{x86-solaris}
21858 @item @code{@ @ }@i{rts-native (default)}
21859 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21860 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21862 @item @b{x86-windows}
21863 @item @code{@ @ }@i{rts-native (default)}
21864 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21865 @item @code{@ @ @ @ }Exceptions @tab ZCX
21867 @item @code{@ @ }@i{rts-sjlj (default)}
21868 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21869 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21871 @item @b{x86-windows-rtx}
21872 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21873 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21874 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21876 @item @code{@ @ }@i{rts-rtx-w32}
21877 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21878 @item @code{@ @ @ @ }Exceptions @tab ZCX
21880 @item @b{x86_64-linux}
21881 @item @code{@ @ }@i{rts-native (default)}
21882 @item @code{@ @ @ @ }Tasking    @tab pthread library
21883 @item @code{@ @ @ @ }Exceptions @tab ZCX
21885 @item @code{@ @ }@i{rts-sjlj}
21886 @item @code{@ @ @ @ }Tasking    @tab pthread library
21887 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21889 @end multitable
21891 @node Specifying a Run-Time Library
21892 @section Specifying a Run-Time Library
21894 @noindent
21895 The @file{adainclude} subdirectory containing the sources of the GNAT
21896 run-time library, and the @file{adalib} subdirectory containing the
21897 @file{ALI} files and the static and/or shared GNAT library, are located
21898 in the gcc target-dependent area:
21900 @smallexample
21901 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21902 @end smallexample
21904 @noindent
21905 As indicated above, on some platforms several run-time libraries are supplied.
21906 These libraries are installed in the target dependent area and
21907 contain a complete source and binary subdirectory. The detailed description
21908 below explains the differences between the different libraries in terms of
21909 their thread support.
21911 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21912 This default run time is selected by the means of soft links.
21913 For example on x86-linux:
21915 @smallexample
21916 @group
21917  $(target-dir)
21918      |
21919      +--- adainclude----------+
21920      |                        |
21921      +--- adalib-----------+  |
21922      |                     |  |
21923      +--- rts-native       |  |
21924      |    |                |  |
21925      |    +--- adainclude <---+
21926      |    |                |
21927      |    +--- adalib <----+
21928      |
21929      +--- rts-sjlj
21930           |
21931           +--- adainclude
21932           |
21933           +--- adalib
21934 @end group
21935 @end smallexample
21937 @noindent
21938 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21939 these soft links can be modified with the following commands:
21941 @smallexample
21942 $ cd $target
21943 $ rm -f adainclude adalib
21944 $ ln -s rts-sjlj/adainclude adainclude
21945 $ ln -s rts-sjlj/adalib adalib
21946 @end smallexample
21948 @noindent
21949 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21950 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21951 @file{$target/ada_object_path}.
21953 Selecting another run-time library temporarily can be
21954 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21955 @cindex @option{--RTS} option
21957 @node Choosing the Scheduling Policy
21958 @section Choosing the Scheduling Policy
21960 @noindent
21961 When using a POSIX threads implementation, you have a choice of several
21962 scheduling policies: @code{SCHED_FIFO},
21963 @cindex @code{SCHED_FIFO} scheduling policy
21964 @code{SCHED_RR}
21965 @cindex @code{SCHED_RR} scheduling policy
21966 and @code{SCHED_OTHER}.
21967 @cindex @code{SCHED_OTHER} scheduling policy
21968 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21969 or @code{SCHED_RR} requires special (e.g., root) privileges.
21971 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21972 @code{SCHED_FIFO},
21973 @cindex @code{SCHED_FIFO} scheduling policy
21974 you can use one of the following:
21976 @itemize @bullet
21977 @item
21978 @code{pragma Time_Slice (0.0)}
21979 @cindex pragma Time_Slice
21980 @item
21981 the corresponding binder option @option{-T0}
21982 @cindex @option{-T0} option
21983 @item
21984 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21985 @cindex pragma Task_Dispatching_Policy
21986 @end itemize
21988 @noindent
21989 To specify @code{SCHED_RR},
21990 @cindex @code{SCHED_RR} scheduling policy
21991 you should use @code{pragma Time_Slice} with a
21992 value greater than @code{0.0}, or else use the corresponding @option{-T}
21993 binder option.
21995 @node Solaris-Specific Considerations
21996 @section Solaris-Specific Considerations
21997 @cindex Solaris Sparc threads libraries
21999 @noindent
22000 This section addresses some topics related to the various threads libraries
22001 on Sparc Solaris.
22003 @menu
22004 * Solaris Threads Issues::
22005 @end menu
22007 @node Solaris Threads Issues
22008 @subsection Solaris Threads Issues
22010 @noindent
22011 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22012 library based on POSIX threads --- @emph{rts-pthread}.
22013 @cindex rts-pthread threads library
22014 This run-time library has the advantage of being mostly shared across all
22015 POSIX-compliant thread implementations, and it also provides under
22016 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22017 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22018 and @code{PTHREAD_PRIO_PROTECT}
22019 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22020 semantics that can be selected using the predefined pragma
22021 @code{Locking_Policy}
22022 @cindex pragma Locking_Policy (under rts-pthread)
22023 with respectively
22024 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22025 @cindex @code{Inheritance_Locking} (under rts-pthread)
22026 @cindex @code{Ceiling_Locking} (under rts-pthread)
22028 As explained above, the native run-time library is based on the Solaris thread
22029 library (@code{libthread}) and is the default library.
22031 When the Solaris threads library is used (this is the default), programs
22032 compiled with GNAT can automatically take advantage of
22033 and can thus execute on multiple processors.
22034 The user can alternatively specify a processor on which the program should run
22035 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22036 is made by
22037 setting the environment variable @env{GNAT_PROCESSOR}
22038 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22039 to one of the following:
22041 @table @code
22042 @item -2
22043 Use the default configuration (run the program on all
22044 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22045 unset
22047 @item -1
22048 Let the run-time implementation choose one processor and run the program on
22049 that processor
22051 @item 0 .. Last_Proc
22052 Run the program on the specified processor.
22053 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22054 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22055 @end table
22057 @node Linux-Specific Considerations
22058 @section Linux-Specific Considerations
22059 @cindex Linux threads libraries
22061 @noindent
22062 On GNU/Linux without NPTL support (usually system with GNU C Library
22063 older than 2.3), the signal model is not POSIX compliant, which means
22064 that to send a signal to the process, you need to send the signal to all
22065 threads, e.g.@: by using @code{killpg()}.
22067 @node AIX-Specific Considerations
22068 @section AIX-Specific Considerations
22069 @cindex AIX resolver library
22071 @noindent
22072 On AIX, the resolver library initializes some internal structure on
22073 the first call to @code{get*by*} functions, which are used to implement
22074 @code{GNAT.Sockets.Get_Host_By_Name} and
22075 @code{GNAT.Sockets.Get_Host_By_Address}.
22076 If such initialization occurs within an Ada task, and the stack size for
22077 the task is the default size, a stack overflow may occur.
22079 To avoid this overflow, the user should either ensure that the first call
22080 to @code{GNAT.Sockets.Get_Host_By_Name} or
22081 @code{GNAT.Sockets.Get_Host_By_Addrss}
22082 occurs in the environment task, or use @code{pragma Storage_Size} to
22083 specify a sufficiently large size for the stack of the task that contains
22084 this call.
22086 @node Irix-Specific Considerations
22087 @section Irix-Specific Considerations
22088 @cindex Irix libraries
22090 @noindent
22091 The GCC support libraries coming with the Irix compiler have moved to
22092 their canonical place with respect to the general Irix ABI related
22093 conventions. Running applications built with the default shared GNAT
22094 run-time now requires the LD_LIBRARY_PATH environment variable to
22095 include this location. A possible way to achieve this is to issue the
22096 following command line on a bash prompt:
22098 @smallexample
22099 @group
22100 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22101 @end group
22102 @end smallexample
22104 @node RTX-Specific Considerations
22105 @section RTX-Specific Considerations
22106 @cindex RTX libraries
22108 @noindent
22109 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22110 API. Applications can be built to work in two different modes:
22112 @itemize @bullet
22113 @item
22114 Windows executables that run in Ring 3 to utilize memory protection
22115 (@emph{rts-rtx-w32}).
22117 @item
22118 Real-time subsystem (RTSS) executables that run in Ring 0, where
22119 performance can be optimized with RTSS applications taking precedent
22120 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22121 the Microsoft linker to handle RTSS libraries.
22123 @end itemize
22125 @node HP-UX-Specific Considerations
22126 @section HP-UX-Specific Considerations
22127 @cindex HP-UX Scheduling
22129 @noindent
22130 On HP-UX, appropriate privileges are required to change the scheduling
22131 parameters of a task. The calling process must have appropriate
22132 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22133 successfully change the scheduling parameters.
22135 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22136 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22137 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22139 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22140 one of the following:
22142 @itemize @bullet
22143 @item
22144 @code{pragma Time_Slice (0.0)}
22145 @cindex pragma Time_Slice
22146 @item
22147 the corresponding binder option @option{-T0}
22148 @cindex @option{-T0} option
22149 @item
22150 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22151 @cindex pragma Task_Dispatching_Policy
22152 @end itemize
22154 @noindent
22155 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22156 you should use @code{pragma Time_Slice} with a
22157 value greater than @code{0.0}, or use the corresponding @option{-T}
22158 binder option, or set the @code{pragma Task_Dispatching_Policy
22159 (Round_Robin_Within_Priorities)}.
22161 @c *******************************
22162 @node Example of Binder Output File
22163 @appendix Example of Binder Output File
22165 @noindent
22166 This Appendix displays the source code for @command{gnatbind}'s output
22167 file generated for a simple ``Hello World'' program.
22168 Comments have been added for clarification purposes.
22170 @smallexample @c adanocomment
22171 @iftex
22172 @leftskip=0cm
22173 @end iftex
22174 --  The package is called Ada_Main unless this name is actually used
22175 --  as a unit name in the partition, in which case some other unique
22176 --  name is used.
22178 with System;
22179 package ada_main is
22181    Elab_Final_Code : Integer;
22182    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22184    --  The main program saves the parameters (argument count,
22185    --  argument values, environment pointer) in global variables
22186    --  for later access by other units including
22187    --  Ada.Command_Line.
22189    gnat_argc : Integer;
22190    gnat_argv : System.Address;
22191    gnat_envp : System.Address;
22193    --  The actual variables are stored in a library routine. This
22194    --  is useful for some shared library situations, where there
22195    --  are problems if variables are not in the library.
22197    pragma Import (C, gnat_argc);
22198    pragma Import (C, gnat_argv);
22199    pragma Import (C, gnat_envp);
22201    --  The exit status is similarly an external location
22203    gnat_exit_status : Integer;
22204    pragma Import (C, gnat_exit_status);
22206    GNAT_Version : constant String :=
22207                     "GNAT Version: 6.0.0w (20061115)";
22208    pragma Export (C, GNAT_Version, "__gnat_version");
22210    --  This is the generated adafinal routine that performs
22211    --  finalization at the end of execution. In the case where
22212    --  Ada is the main program, this main program makes a call
22213    --  to adafinal at program termination.
22215    procedure adafinal;
22216    pragma Export (C, adafinal, "adafinal");
22218    --  This is the generated adainit routine that performs
22219    --  initialization at the start of execution. In the case
22220    --  where Ada is the main program, this main program makes
22221    --  a call to adainit at program startup.
22223    procedure adainit;
22224    pragma Export (C, adainit, "adainit");
22226    --  This routine is called at the start of execution. It is
22227    --  a dummy routine that is used by the debugger to breakpoint
22228    --  at the start of execution.
22230    procedure Break_Start;
22231    pragma Import (C, Break_Start, "__gnat_break_start");
22233    --  This is the actual generated main program (it would be
22234    --  suppressed if the no main program switch were used). As
22235    --  required by standard system conventions, this program has
22236    --  the external name main.
22238    function main
22239      (argc : Integer;
22240       argv : System.Address;
22241       envp : System.Address)
22242       return Integer;
22243    pragma Export (C, main, "main");
22245    --  The following set of constants give the version
22246    --  identification values for every unit in the bound
22247    --  partition. This identification is computed from all
22248    --  dependent semantic units, and corresponds to the
22249    --  string that would be returned by use of the
22250    --  Body_Version or Version attributes.
22252    type Version_32 is mod 2 ** 32;
22253    u00001 : constant Version_32 := 16#7880BEB3#;
22254    u00002 : constant Version_32 := 16#0D24CBD0#;
22255    u00003 : constant Version_32 := 16#3283DBEB#;
22256    u00004 : constant Version_32 := 16#2359F9ED#;
22257    u00005 : constant Version_32 := 16#664FB847#;
22258    u00006 : constant Version_32 := 16#68E803DF#;
22259    u00007 : constant Version_32 := 16#5572E604#;
22260    u00008 : constant Version_32 := 16#46B173D8#;
22261    u00009 : constant Version_32 := 16#156A40CF#;
22262    u00010 : constant Version_32 := 16#033DABE0#;
22263    u00011 : constant Version_32 := 16#6AB38FEA#;
22264    u00012 : constant Version_32 := 16#22B6217D#;
22265    u00013 : constant Version_32 := 16#68A22947#;
22266    u00014 : constant Version_32 := 16#18CC4A56#;
22267    u00015 : constant Version_32 := 16#08258E1B#;
22268    u00016 : constant Version_32 := 16#367D5222#;
22269    u00017 : constant Version_32 := 16#20C9ECA4#;
22270    u00018 : constant Version_32 := 16#50D32CB6#;
22271    u00019 : constant Version_32 := 16#39A8BB77#;
22272    u00020 : constant Version_32 := 16#5CF8FA2B#;
22273    u00021 : constant Version_32 := 16#2F1EB794#;
22274    u00022 : constant Version_32 := 16#31AB6444#;
22275    u00023 : constant Version_32 := 16#1574B6E9#;
22276    u00024 : constant Version_32 := 16#5109C189#;
22277    u00025 : constant Version_32 := 16#56D770CD#;
22278    u00026 : constant Version_32 := 16#02F9DE3D#;
22279    u00027 : constant Version_32 := 16#08AB6B2C#;
22280    u00028 : constant Version_32 := 16#3FA37670#;
22281    u00029 : constant Version_32 := 16#476457A0#;
22282    u00030 : constant Version_32 := 16#731E1B6E#;
22283    u00031 : constant Version_32 := 16#23C2E789#;
22284    u00032 : constant Version_32 := 16#0F1BD6A1#;
22285    u00033 : constant Version_32 := 16#7C25DE96#;
22286    u00034 : constant Version_32 := 16#39ADFFA2#;
22287    u00035 : constant Version_32 := 16#571DE3E7#;
22288    u00036 : constant Version_32 := 16#5EB646AB#;
22289    u00037 : constant Version_32 := 16#4249379B#;
22290    u00038 : constant Version_32 := 16#0357E00A#;
22291    u00039 : constant Version_32 := 16#3784FB72#;
22292    u00040 : constant Version_32 := 16#2E723019#;
22293    u00041 : constant Version_32 := 16#623358EA#;
22294    u00042 : constant Version_32 := 16#107F9465#;
22295    u00043 : constant Version_32 := 16#6843F68A#;
22296    u00044 : constant Version_32 := 16#63305874#;
22297    u00045 : constant Version_32 := 16#31E56CE1#;
22298    u00046 : constant Version_32 := 16#02917970#;
22299    u00047 : constant Version_32 := 16#6CCBA70E#;
22300    u00048 : constant Version_32 := 16#41CD4204#;
22301    u00049 : constant Version_32 := 16#572E3F58#;
22302    u00050 : constant Version_32 := 16#20729FF5#;
22303    u00051 : constant Version_32 := 16#1D4F93E8#;
22304    u00052 : constant Version_32 := 16#30B2EC3D#;
22305    u00053 : constant Version_32 := 16#34054F96#;
22306    u00054 : constant Version_32 := 16#5A199860#;
22307    u00055 : constant Version_32 := 16#0E7F912B#;
22308    u00056 : constant Version_32 := 16#5760634A#;
22309    u00057 : constant Version_32 := 16#5D851835#;
22311    --  The following Export pragmas export the version numbers
22312    --  with symbolic names ending in B (for body) or S
22313    --  (for spec) so that they can be located in a link. The
22314    --  information provided here is sufficient to track down
22315    --  the exact versions of units used in a given build.
22317    pragma Export (C, u00001, "helloB");
22318    pragma Export (C, u00002, "system__standard_libraryB");
22319    pragma Export (C, u00003, "system__standard_libraryS");
22320    pragma Export (C, u00004, "adaS");
22321    pragma Export (C, u00005, "ada__text_ioB");
22322    pragma Export (C, u00006, "ada__text_ioS");
22323    pragma Export (C, u00007, "ada__exceptionsB");
22324    pragma Export (C, u00008, "ada__exceptionsS");
22325    pragma Export (C, u00009, "gnatS");
22326    pragma Export (C, u00010, "gnat__heap_sort_aB");
22327    pragma Export (C, u00011, "gnat__heap_sort_aS");
22328    pragma Export (C, u00012, "systemS");
22329    pragma Export (C, u00013, "system__exception_tableB");
22330    pragma Export (C, u00014, "system__exception_tableS");
22331    pragma Export (C, u00015, "gnat__htableB");
22332    pragma Export (C, u00016, "gnat__htableS");
22333    pragma Export (C, u00017, "system__exceptionsS");
22334    pragma Export (C, u00018, "system__machine_state_operationsB");
22335    pragma Export (C, u00019, "system__machine_state_operationsS");
22336    pragma Export (C, u00020, "system__machine_codeS");
22337    pragma Export (C, u00021, "system__storage_elementsB");
22338    pragma Export (C, u00022, "system__storage_elementsS");
22339    pragma Export (C, u00023, "system__secondary_stackB");
22340    pragma Export (C, u00024, "system__secondary_stackS");
22341    pragma Export (C, u00025, "system__parametersB");
22342    pragma Export (C, u00026, "system__parametersS");
22343    pragma Export (C, u00027, "system__soft_linksB");
22344    pragma Export (C, u00028, "system__soft_linksS");
22345    pragma Export (C, u00029, "system__stack_checkingB");
22346    pragma Export (C, u00030, "system__stack_checkingS");
22347    pragma Export (C, u00031, "system__tracebackB");
22348    pragma Export (C, u00032, "system__tracebackS");
22349    pragma Export (C, u00033, "ada__streamsS");
22350    pragma Export (C, u00034, "ada__tagsB");
22351    pragma Export (C, u00035, "ada__tagsS");
22352    pragma Export (C, u00036, "system__string_opsB");
22353    pragma Export (C, u00037, "system__string_opsS");
22354    pragma Export (C, u00038, "interfacesS");
22355    pragma Export (C, u00039, "interfaces__c_streamsB");
22356    pragma Export (C, u00040, "interfaces__c_streamsS");
22357    pragma Export (C, u00041, "system__file_ioB");
22358    pragma Export (C, u00042, "system__file_ioS");
22359    pragma Export (C, u00043, "ada__finalizationB");
22360    pragma Export (C, u00044, "ada__finalizationS");
22361    pragma Export (C, u00045, "system__finalization_rootB");
22362    pragma Export (C, u00046, "system__finalization_rootS");
22363    pragma Export (C, u00047, "system__finalization_implementationB");
22364    pragma Export (C, u00048, "system__finalization_implementationS");
22365    pragma Export (C, u00049, "system__string_ops_concat_3B");
22366    pragma Export (C, u00050, "system__string_ops_concat_3S");
22367    pragma Export (C, u00051, "system__stream_attributesB");
22368    pragma Export (C, u00052, "system__stream_attributesS");
22369    pragma Export (C, u00053, "ada__io_exceptionsS");
22370    pragma Export (C, u00054, "system__unsigned_typesS");
22371    pragma Export (C, u00055, "system__file_control_blockS");
22372    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22373    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22375    -- BEGIN ELABORATION ORDER
22376    -- ada (spec)
22377    -- gnat (spec)
22378    -- gnat.heap_sort_a (spec)
22379    -- gnat.heap_sort_a (body)
22380    -- gnat.htable (spec)
22381    -- gnat.htable (body)
22382    -- interfaces (spec)
22383    -- system (spec)
22384    -- system.machine_code (spec)
22385    -- system.parameters (spec)
22386    -- system.parameters (body)
22387    -- interfaces.c_streams (spec)
22388    -- interfaces.c_streams (body)
22389    -- system.standard_library (spec)
22390    -- ada.exceptions (spec)
22391    -- system.exception_table (spec)
22392    -- system.exception_table (body)
22393    -- ada.io_exceptions (spec)
22394    -- system.exceptions (spec)
22395    -- system.storage_elements (spec)
22396    -- system.storage_elements (body)
22397    -- system.machine_state_operations (spec)
22398    -- system.machine_state_operations (body)
22399    -- system.secondary_stack (spec)
22400    -- system.stack_checking (spec)
22401    -- system.soft_links (spec)
22402    -- system.soft_links (body)
22403    -- system.stack_checking (body)
22404    -- system.secondary_stack (body)
22405    -- system.standard_library (body)
22406    -- system.string_ops (spec)
22407    -- system.string_ops (body)
22408    -- ada.tags (spec)
22409    -- ada.tags (body)
22410    -- ada.streams (spec)
22411    -- system.finalization_root (spec)
22412    -- system.finalization_root (body)
22413    -- system.string_ops_concat_3 (spec)
22414    -- system.string_ops_concat_3 (body)
22415    -- system.traceback (spec)
22416    -- system.traceback (body)
22417    -- ada.exceptions (body)
22418    -- system.unsigned_types (spec)
22419    -- system.stream_attributes (spec)
22420    -- system.stream_attributes (body)
22421    -- system.finalization_implementation (spec)
22422    -- system.finalization_implementation (body)
22423    -- ada.finalization (spec)
22424    -- ada.finalization (body)
22425    -- ada.finalization.list_controller (spec)
22426    -- ada.finalization.list_controller (body)
22427    -- system.file_control_block (spec)
22428    -- system.file_io (spec)
22429    -- system.file_io (body)
22430    -- ada.text_io (spec)
22431    -- ada.text_io (body)
22432    -- hello (body)
22433    -- END ELABORATION ORDER
22435 end ada_main;
22437 --  The following source file name pragmas allow the generated file
22438 --  names to be unique for different main programs. They are needed
22439 --  since the package name will always be Ada_Main.
22441 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22442 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22444 --  Generated package body for Ada_Main starts here
22446 package body ada_main is
22448    --  The actual finalization is performed by calling the
22449    --  library routine in System.Standard_Library.Adafinal
22451    procedure Do_Finalize;
22452    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22454    -------------
22455    -- adainit --
22456    -------------
22458 @findex adainit
22459    procedure adainit is
22461       --  These booleans are set to True once the associated unit has
22462       --  been elaborated. It is also used to avoid elaborating the
22463       --  same unit twice.
22465       E040 : Boolean;
22466       pragma Import (Ada, E040, "interfaces__c_streams_E");
22468       E008 : Boolean;
22469       pragma Import (Ada, E008, "ada__exceptions_E");
22471       E014 : Boolean;
22472       pragma Import (Ada, E014, "system__exception_table_E");
22474       E053 : Boolean;
22475       pragma Import (Ada, E053, "ada__io_exceptions_E");
22477       E017 : Boolean;
22478       pragma Import (Ada, E017, "system__exceptions_E");
22480       E024 : Boolean;
22481       pragma Import (Ada, E024, "system__secondary_stack_E");
22483       E030 : Boolean;
22484       pragma Import (Ada, E030, "system__stack_checking_E");
22486       E028 : Boolean;
22487       pragma Import (Ada, E028, "system__soft_links_E");
22489       E035 : Boolean;
22490       pragma Import (Ada, E035, "ada__tags_E");
22492       E033 : Boolean;
22493       pragma Import (Ada, E033, "ada__streams_E");
22495       E046 : Boolean;
22496       pragma Import (Ada, E046, "system__finalization_root_E");
22498       E048 : Boolean;
22499       pragma Import (Ada, E048, "system__finalization_implementation_E");
22501       E044 : Boolean;
22502       pragma Import (Ada, E044, "ada__finalization_E");
22504       E057 : Boolean;
22505       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22507       E055 : Boolean;
22508       pragma Import (Ada, E055, "system__file_control_block_E");
22510       E042 : Boolean;
22511       pragma Import (Ada, E042, "system__file_io_E");
22513       E006 : Boolean;
22514       pragma Import (Ada, E006, "ada__text_io_E");
22516       --  Set_Globals is a library routine that stores away the
22517       --  value of the indicated set of global values in global
22518       --  variables within the library.
22520       procedure Set_Globals
22521         (Main_Priority            : Integer;
22522          Time_Slice_Value         : Integer;
22523          WC_Encoding              : Character;
22524          Locking_Policy           : Character;
22525          Queuing_Policy           : Character;
22526          Task_Dispatching_Policy  : Character;
22527          Adafinal                 : System.Address;
22528          Unreserve_All_Interrupts : Integer;
22529          Exception_Tracebacks     : Integer);
22530 @findex __gnat_set_globals
22531       pragma Import (C, Set_Globals, "__gnat_set_globals");
22533       --  SDP_Table_Build is a library routine used to build the
22534       --  exception tables. See unit Ada.Exceptions in files
22535       --  a-except.ads/adb for full details of how zero cost
22536       --  exception handling works. This procedure, the call to
22537       --  it, and the two following tables are all omitted if the
22538       --  build is in longjmp/setjmp exception mode.
22540 @findex SDP_Table_Build
22541 @findex Zero Cost Exceptions
22542       procedure SDP_Table_Build
22543         (SDP_Addresses   : System.Address;
22544          SDP_Count       : Natural;
22545          Elab_Addresses  : System.Address;
22546          Elab_Addr_Count : Natural);
22547       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22549       --  Table of Unit_Exception_Table addresses. Used for zero
22550       --  cost exception handling to build the top level table.
22552       ST : aliased constant array (1 .. 23) of System.Address := (
22553         Hello'UET_Address,
22554         Ada.Text_Io'UET_Address,
22555         Ada.Exceptions'UET_Address,
22556         Gnat.Heap_Sort_A'UET_Address,
22557         System.Exception_Table'UET_Address,
22558         System.Machine_State_Operations'UET_Address,
22559         System.Secondary_Stack'UET_Address,
22560         System.Parameters'UET_Address,
22561         System.Soft_Links'UET_Address,
22562         System.Stack_Checking'UET_Address,
22563         System.Traceback'UET_Address,
22564         Ada.Streams'UET_Address,
22565         Ada.Tags'UET_Address,
22566         System.String_Ops'UET_Address,
22567         Interfaces.C_Streams'UET_Address,
22568         System.File_Io'UET_Address,
22569         Ada.Finalization'UET_Address,
22570         System.Finalization_Root'UET_Address,
22571         System.Finalization_Implementation'UET_Address,
22572         System.String_Ops_Concat_3'UET_Address,
22573         System.Stream_Attributes'UET_Address,
22574         System.File_Control_Block'UET_Address,
22575         Ada.Finalization.List_Controller'UET_Address);
22577       --  Table of addresses of elaboration routines. Used for
22578       --  zero cost exception handling to make sure these
22579       --  addresses are included in the top level procedure
22580       --  address table.
22582       EA : aliased constant array (1 .. 23) of System.Address := (
22583         adainit'Code_Address,
22584         Do_Finalize'Code_Address,
22585         Ada.Exceptions'Elab_Spec'Address,
22586         System.Exceptions'Elab_Spec'Address,
22587         Interfaces.C_Streams'Elab_Spec'Address,
22588         System.Exception_Table'Elab_Body'Address,
22589         Ada.Io_Exceptions'Elab_Spec'Address,
22590         System.Stack_Checking'Elab_Spec'Address,
22591         System.Soft_Links'Elab_Body'Address,
22592         System.Secondary_Stack'Elab_Body'Address,
22593         Ada.Tags'Elab_Spec'Address,
22594         Ada.Tags'Elab_Body'Address,
22595         Ada.Streams'Elab_Spec'Address,
22596         System.Finalization_Root'Elab_Spec'Address,
22597         Ada.Exceptions'Elab_Body'Address,
22598         System.Finalization_Implementation'Elab_Spec'Address,
22599         System.Finalization_Implementation'Elab_Body'Address,
22600         Ada.Finalization'Elab_Spec'Address,
22601         Ada.Finalization.List_Controller'Elab_Spec'Address,
22602         System.File_Control_Block'Elab_Spec'Address,
22603         System.File_Io'Elab_Body'Address,
22604         Ada.Text_Io'Elab_Spec'Address,
22605         Ada.Text_Io'Elab_Body'Address);
22607    --  Start of processing for adainit
22609    begin
22611       --  Call SDP_Table_Build to build the top level procedure
22612       --  table for zero cost exception handling (omitted in
22613       --  longjmp/setjmp mode).
22615       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22617       --  Call Set_Globals to record various information for
22618       --  this partition.  The values are derived by the binder
22619       --  from information stored in the ali files by the compiler.
22621 @findex __gnat_set_globals
22622       Set_Globals
22623         (Main_Priority            => -1,
22624          --  Priority of main program, -1 if no pragma Priority used
22626          Time_Slice_Value         => -1,
22627          --  Time slice from Time_Slice pragma, -1 if none used
22629          WC_Encoding              => 'b',
22630          --  Wide_Character encoding used, default is brackets
22632          Locking_Policy           => ' ',
22633          --  Locking_Policy used, default of space means not
22634          --  specified, otherwise it is the first character of
22635          --  the policy name.
22637          Queuing_Policy           => ' ',
22638          --  Queuing_Policy used, default of space means not
22639          --  specified, otherwise it is the first character of
22640          --  the policy name.
22642          Task_Dispatching_Policy  => ' ',
22643          --  Task_Dispatching_Policy used, default of space means
22644          --  not specified, otherwise first character of the
22645          --  policy name.
22647          Adafinal                 => System.Null_Address,
22648          --  Address of Adafinal routine, not used anymore
22650          Unreserve_All_Interrupts => 0,
22651          --  Set true if pragma Unreserve_All_Interrupts was used
22653          Exception_Tracebacks     => 0);
22654          --  Indicates if exception tracebacks are enabled
22656       Elab_Final_Code := 1;
22658       --  Now we have the elaboration calls for all units in the partition.
22659       --  The Elab_Spec and Elab_Body attributes generate references to the
22660       --  implicit elaboration procedures generated by the compiler for
22661       --  each unit that requires elaboration.
22663       if not E040 then
22664          Interfaces.C_Streams'Elab_Spec;
22665       end if;
22666       E040 := True;
22667       if not E008 then
22668          Ada.Exceptions'Elab_Spec;
22669       end if;
22670       if not E014 then
22671          System.Exception_Table'Elab_Body;
22672          E014 := True;
22673       end if;
22674       if not E053 then
22675          Ada.Io_Exceptions'Elab_Spec;
22676          E053 := True;
22677       end if;
22678       if not E017 then
22679          System.Exceptions'Elab_Spec;
22680          E017 := True;
22681       end if;
22682       if not E030 then
22683          System.Stack_Checking'Elab_Spec;
22684       end if;
22685       if not E028 then
22686          System.Soft_Links'Elab_Body;
22687          E028 := True;
22688       end if;
22689       E030 := True;
22690       if not E024 then
22691          System.Secondary_Stack'Elab_Body;
22692          E024 := True;
22693       end if;
22694       if not E035 then
22695          Ada.Tags'Elab_Spec;
22696       end if;
22697       if not E035 then
22698          Ada.Tags'Elab_Body;
22699          E035 := True;
22700       end if;
22701       if not E033 then
22702          Ada.Streams'Elab_Spec;
22703          E033 := True;
22704       end if;
22705       if not E046 then
22706          System.Finalization_Root'Elab_Spec;
22707       end if;
22708       E046 := True;
22709       if not E008 then
22710          Ada.Exceptions'Elab_Body;
22711          E008 := True;
22712       end if;
22713       if not E048 then
22714          System.Finalization_Implementation'Elab_Spec;
22715       end if;
22716       if not E048 then
22717          System.Finalization_Implementation'Elab_Body;
22718          E048 := True;
22719       end if;
22720       if not E044 then
22721          Ada.Finalization'Elab_Spec;
22722       end if;
22723       E044 := True;
22724       if not E057 then
22725          Ada.Finalization.List_Controller'Elab_Spec;
22726       end if;
22727       E057 := True;
22728       if not E055 then
22729          System.File_Control_Block'Elab_Spec;
22730          E055 := True;
22731       end if;
22732       if not E042 then
22733          System.File_Io'Elab_Body;
22734          E042 := True;
22735       end if;
22736       if not E006 then
22737          Ada.Text_Io'Elab_Spec;
22738       end if;
22739       if not E006 then
22740          Ada.Text_Io'Elab_Body;
22741          E006 := True;
22742       end if;
22744       Elab_Final_Code := 0;
22745    end adainit;
22747    --------------
22748    -- adafinal --
22749    --------------
22751 @findex adafinal
22752    procedure adafinal is
22753    begin
22754       Do_Finalize;
22755    end adafinal;
22757    ----------
22758    -- main --
22759    ----------
22761    --  main is actually a function, as in the ANSI C standard,
22762    --  defined to return the exit status. The three parameters
22763    --  are the argument count, argument values and environment
22764    --  pointer.
22766 @findex Main Program
22767    function main
22768      (argc : Integer;
22769       argv : System.Address;
22770       envp : System.Address)
22771       return Integer
22772    is
22773       --  The initialize routine performs low level system
22774       --  initialization using a standard library routine which
22775       --  sets up signal handling and performs any other
22776       --  required setup. The routine can be found in file
22777       --  a-init.c.
22779 @findex __gnat_initialize
22780       procedure initialize;
22781       pragma Import (C, initialize, "__gnat_initialize");
22783       --  The finalize routine performs low level system
22784       --  finalization using a standard library routine. The
22785       --  routine is found in file a-final.c and in the standard
22786       --  distribution is a dummy routine that does nothing, so
22787       --  really this is a hook for special user finalization.
22789 @findex __gnat_finalize
22790       procedure finalize;
22791       pragma Import (C, finalize, "__gnat_finalize");
22793       --  We get to the main program of the partition by using
22794       --  pragma Import because if we try to with the unit and
22795       --  call it Ada style, then not only do we waste time
22796       --  recompiling it, but also, we don't really know the right
22797       --  switches (e.g.@: identifier character set) to be used
22798       --  to compile it.
22800       procedure Ada_Main_Program;
22801       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22803    --  Start of processing for main
22805    begin
22806       --  Save global variables
22808       gnat_argc := argc;
22809       gnat_argv := argv;
22810       gnat_envp := envp;
22812       --  Call low level system initialization
22814       Initialize;
22816       --  Call our generated Ada initialization routine
22818       adainit;
22820       --  This is the point at which we want the debugger to get
22821       --  control
22823       Break_Start;
22825       --  Now we call the main program of the partition
22827       Ada_Main_Program;
22829       --  Perform Ada finalization
22831       adafinal;
22833       --  Perform low level system finalization
22835       Finalize;
22837       --  Return the proper exit status
22838       return (gnat_exit_status);
22839    end;
22841 --  This section is entirely comments, so it has no effect on the
22842 --  compilation of the Ada_Main package. It provides the list of
22843 --  object files and linker options, as well as some standard
22844 --  libraries needed for the link. The gnatlink utility parses
22845 --  this b~hello.adb file to read these comment lines to generate
22846 --  the appropriate command line arguments for the call to the
22847 --  system linker. The BEGIN/END lines are used for sentinels for
22848 --  this parsing operation.
22850 --  The exact file names will of course depend on the environment,
22851 --  host/target and location of files on the host system.
22853 @findex Object file list
22854 -- BEGIN Object file/option list
22855    --   ./hello.o
22856    --   -L./
22857    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22858    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22859 -- END Object file/option list
22861 end ada_main;
22862 @end smallexample
22864 @noindent
22865 The Ada code in the above example is exactly what is generated by the
22866 binder. We have added comments to more clearly indicate the function
22867 of each part of the generated @code{Ada_Main} package.
22869 The code is standard Ada in all respects, and can be processed by any
22870 tools that handle Ada. In particular, it is possible to use the debugger
22871 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22872 suppose that for reasons that you do not understand, your program is crashing
22873 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22874 you can place a breakpoint on the call:
22876 @smallexample @c ada
22877 Ada.Text_Io'Elab_Body;
22878 @end smallexample
22880 @noindent
22881 and trace the elaboration routine for this package to find out where
22882 the problem might be (more usually of course you would be debugging
22883 elaboration code in your own application).
22885 @node Elaboration Order Handling in GNAT
22886 @appendix Elaboration Order Handling in GNAT
22887 @cindex Order of elaboration
22888 @cindex Elaboration control
22890 @menu
22891 * Elaboration Code::
22892 * Checking the Elaboration Order::
22893 * Controlling the Elaboration Order::
22894 * Controlling Elaboration in GNAT - Internal Calls::
22895 * Controlling Elaboration in GNAT - External Calls::
22896 * Default Behavior in GNAT - Ensuring Safety::
22897 * Treatment of Pragma Elaborate::
22898 * Elaboration Issues for Library Tasks::
22899 * Mixing Elaboration Models::
22900 * What to Do If the Default Elaboration Behavior Fails::
22901 * Elaboration for Access-to-Subprogram Values::
22902 * Summary of Procedures for Elaboration Control::
22903 * Other Elaboration Order Considerations::
22904 @end menu
22906 @noindent
22907 This chapter describes the handling of elaboration code in Ada and
22908 in GNAT, and discusses how the order of elaboration of program units can
22909 be controlled in GNAT, either automatically or with explicit programming
22910 features.
22912 @node Elaboration Code
22913 @section Elaboration Code
22915 @noindent
22916 Ada provides rather general mechanisms for executing code at elaboration
22917 time, that is to say before the main program starts executing. Such code arises
22918 in three contexts:
22920 @table @asis
22921 @item Initializers for variables.
22922 Variables declared at the library level, in package specs or bodies, can
22923 require initialization that is performed at elaboration time, as in:
22924 @smallexample @c ada
22925 @cartouche
22926 Sqrt_Half : Float := Sqrt (0.5);
22927 @end cartouche
22928 @end smallexample
22930 @item Package initialization code
22931 Code in a @code{BEGIN-END} section at the outer level of a package body is
22932 executed as part of the package body elaboration code.
22934 @item Library level task allocators
22935 Tasks that are declared using task allocators at the library level
22936 start executing immediately and hence can execute at elaboration time.
22937 @end table
22939 @noindent
22940 Subprogram calls are possible in any of these contexts, which means that
22941 any arbitrary part of the program may be executed as part of the elaboration
22942 code. It is even possible to write a program which does all its work at
22943 elaboration time, with a null main program, although stylistically this
22944 would usually be considered an inappropriate way to structure
22945 a program.
22947 An important concern arises in the context of elaboration code:
22948 we have to be sure that it is executed in an appropriate order. What we
22949 have is a series of elaboration code sections, potentially one section
22950 for each unit in the program. It is important that these execute
22951 in the correct order. Correctness here means that, taking the above
22952 example of the declaration of @code{Sqrt_Half},
22953 if some other piece of
22954 elaboration code references @code{Sqrt_Half},
22955 then it must run after the
22956 section of elaboration code that contains the declaration of
22957 @code{Sqrt_Half}.
22959 There would never be any order of elaboration problem if we made a rule
22960 that whenever you @code{with} a unit, you must elaborate both the spec and body
22961 of that unit before elaborating the unit doing the @code{with}'ing:
22963 @smallexample @c ada
22964 @group
22965 @cartouche
22966 with Unit_1;
22967 package Unit_2 is @dots{}
22968 @end cartouche
22969 @end group
22970 @end smallexample
22972 @noindent
22973 would require that both the body and spec of @code{Unit_1} be elaborated
22974 before the spec of @code{Unit_2}. However, a rule like that would be far too
22975 restrictive. In particular, it would make it impossible to have routines
22976 in separate packages that were mutually recursive.
22978 You might think that a clever enough compiler could look at the actual
22979 elaboration code and determine an appropriate correct order of elaboration,
22980 but in the general case, this is not possible. Consider the following
22981 example.
22983 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22984 that references
22985 the variable @code{Sqrt_1}, which is declared in the elaboration code
22986 of the body of @code{Unit_1}:
22988 @smallexample @c ada
22989 @cartouche
22990 Sqrt_1 : Float := Sqrt (0.1);
22991 @end cartouche
22992 @end smallexample
22994 @noindent
22995 The elaboration code of the body of @code{Unit_1} also contains:
22997 @smallexample @c ada
22998 @group
22999 @cartouche
23000 if expression_1 = 1 then
23001    Q := Unit_2.Func_2;
23002 end if;
23003 @end cartouche
23004 @end group
23005 @end smallexample
23007 @noindent
23008 @code{Unit_2} is exactly parallel,
23009 it has a procedure @code{Func_2} that references
23010 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23011 the body @code{Unit_2}:
23013 @smallexample @c ada
23014 @cartouche
23015 Sqrt_2 : Float := Sqrt (0.1);
23016 @end cartouche
23017 @end smallexample
23019 @noindent
23020 The elaboration code of the body of @code{Unit_2} also contains:
23022 @smallexample @c ada
23023 @group
23024 @cartouche
23025 if expression_2 = 2 then
23026    Q := Unit_1.Func_1;
23027 end if;
23028 @end cartouche
23029 @end group
23030 @end smallexample
23032 @noindent
23033 Now the question is, which of the following orders of elaboration is
23034 acceptable:
23036 @smallexample
23037 @group
23038 Spec of Unit_1
23039 Spec of Unit_2
23040 Body of Unit_1
23041 Body of Unit_2
23042 @end group
23043 @end smallexample
23045 @noindent
23048 @smallexample
23049 @group
23050 Spec of Unit_2
23051 Spec of Unit_1
23052 Body of Unit_2
23053 Body of Unit_1
23054 @end group
23055 @end smallexample
23057 @noindent
23058 If you carefully analyze the flow here, you will see that you cannot tell
23059 at compile time the answer to this question.
23060 If @code{expression_1} is not equal to 1,
23061 and @code{expression_2} is not equal to 2,
23062 then either order is acceptable, because neither of the function calls is
23063 executed. If both tests evaluate to true, then neither order is acceptable
23064 and in fact there is no correct order.
23066 If one of the two expressions is true, and the other is false, then one
23067 of the above orders is correct, and the other is incorrect. For example,
23068 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23069 then the call to @code{Func_1}
23070 will occur, but not the call to @code{Func_2.}
23071 This means that it is essential
23072 to elaborate the body of @code{Unit_1} before
23073 the body of @code{Unit_2}, so the first
23074 order of elaboration is correct and the second is wrong.
23076 By making @code{expression_1} and @code{expression_2}
23077 depend on input data, or perhaps
23078 the time of day, we can make it impossible for the compiler or binder
23079 to figure out which of these expressions will be true, and hence it
23080 is impossible to guarantee a safe order of elaboration at run time.
23082 @node Checking the Elaboration Order
23083 @section Checking the Elaboration Order
23085 @noindent
23086 In some languages that involve the same kind of elaboration problems,
23087 e.g.@: Java and C++, the programmer is expected to worry about these
23088 ordering problems himself, and it is common to
23089 write a program in which an incorrect elaboration order  gives
23090 surprising results, because it references variables before they
23091 are initialized.
23092 Ada is designed to be a safe language, and a programmer-beware approach is
23093 clearly not sufficient. Consequently, the language provides three lines
23094 of defense:
23096 @table @asis
23097 @item Standard rules
23098 Some standard rules restrict the possible choice of elaboration
23099 order. In particular, if you @code{with} a unit, then its spec is always
23100 elaborated before the unit doing the @code{with}. Similarly, a parent
23101 spec is always elaborated before the child spec, and finally
23102 a spec is always elaborated before its corresponding body.
23104 @item Dynamic elaboration checks
23105 @cindex Elaboration checks
23106 @cindex Checks, elaboration
23107 Dynamic checks are made at run time, so that if some entity is accessed
23108 before it is elaborated (typically  by means of a subprogram call)
23109 then the exception (@code{Program_Error}) is raised.
23111 @item Elaboration control
23112 Facilities are provided for the programmer to specify the desired order
23113 of elaboration.
23114 @end table
23116 Let's look at these facilities in more detail. First, the rules for
23117 dynamic checking. One possible rule would be simply to say that the
23118 exception is raised if you access a variable which has not yet been
23119 elaborated. The trouble with this approach is that it could require
23120 expensive checks on every variable reference. Instead Ada has two
23121 rules which are a little more restrictive, but easier to check, and
23122 easier to state:
23124 @table @asis
23125 @item Restrictions on calls
23126 A subprogram can only be called at elaboration time if its body
23127 has been elaborated. The rules for elaboration given above guarantee
23128 that the spec of the subprogram has been elaborated before the
23129 call, but not the body. If this rule is violated, then the
23130 exception @code{Program_Error} is raised.
23132 @item Restrictions on instantiations
23133 A generic unit can only be instantiated if the body of the generic
23134 unit has been elaborated. Again, the rules for elaboration given above
23135 guarantee that the spec of the generic unit has been elaborated
23136 before the instantiation, but not the body. If this rule is
23137 violated, then the exception @code{Program_Error} is raised.
23138 @end table
23140 @noindent
23141 The idea is that if the body has been elaborated, then any variables
23142 it references must have been elaborated; by checking for the body being
23143 elaborated we guarantee that none of its references causes any
23144 trouble. As we noted above, this is a little too restrictive, because a
23145 subprogram that has no non-local references in its body may in fact be safe
23146 to call. However, it really would be unsafe to rely on this, because
23147 it would mean that the caller was aware of details of the implementation
23148 in the body. This goes against the basic tenets of Ada.
23150 A plausible implementation can be described as follows.
23151 A Boolean variable is associated with each subprogram
23152 and each generic unit. This variable is initialized to False, and is set to
23153 True at the point body is elaborated. Every call or instantiation checks the
23154 variable, and raises @code{Program_Error} if the variable is False.
23156 Note that one might think that it would be good enough to have one Boolean
23157 variable for each package, but that would not deal with cases of trying
23158 to call a body in the same package as the call
23159 that has not been elaborated yet.
23160 Of course a compiler may be able to do enough analysis to optimize away
23161 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23162 does such optimizations, but still the easiest conceptual model is to
23163 think of there being one variable per subprogram.
23165 @node Controlling the Elaboration Order
23166 @section Controlling the Elaboration Order
23168 @noindent
23169 In the previous section we discussed the rules in Ada which ensure
23170 that @code{Program_Error} is raised if an incorrect elaboration order is
23171 chosen. This prevents erroneous executions, but we need mechanisms to
23172 specify a correct execution and avoid the exception altogether.
23173 To achieve this, Ada provides a number of features for controlling
23174 the order of elaboration. We discuss these features in this section.
23176 First, there are several ways of indicating to the compiler that a given
23177 unit has no elaboration problems:
23179 @table @asis
23180 @item packages that do not require a body
23181 A library package that does not require a body does not permit
23182 a body (this rule was introduced in Ada 95).
23183 Thus if we have a such a package, as in:
23185 @smallexample @c ada
23186 @group
23187 @cartouche
23188 package Definitions is
23189    generic
23190       type m is new integer;
23191    package Subp is
23192       type a is array (1 .. 10) of m;
23193       type b is array (1 .. 20) of m;
23194    end Subp;
23195 end Definitions;
23196 @end cartouche
23197 @end group
23198 @end smallexample
23200 @noindent
23201 A package that @code{with}'s @code{Definitions} may safely instantiate
23202 @code{Definitions.Subp} because the compiler can determine that there
23203 definitely is no package body to worry about in this case
23205 @item pragma Pure
23206 @cindex pragma Pure
23207 @findex Pure
23208 Places sufficient restrictions on a unit to guarantee that
23209 no call to any subprogram in the unit can result in an
23210 elaboration problem. This means that the compiler does not need
23211 to worry about the point of elaboration of such units, and in
23212 particular, does not need to check any calls to any subprograms
23213 in this unit.
23215 @item pragma Preelaborate
23216 @findex Preelaborate
23217 @cindex pragma Preelaborate
23218 This pragma places slightly less stringent restrictions on a unit than
23219 does pragma Pure,
23220 but these restrictions are still sufficient to ensure that there
23221 are no elaboration problems with any calls to the unit.
23223 @item pragma Elaborate_Body
23224 @findex Elaborate_Body
23225 @cindex pragma Elaborate_Body
23226 This pragma requires that the body of a unit be elaborated immediately
23227 after its spec. Suppose a unit @code{A} has such a pragma,
23228 and unit @code{B} does
23229 a @code{with} of unit @code{A}. Recall that the standard rules require
23230 the spec of unit @code{A}
23231 to be elaborated before the @code{with}'ing unit; given the pragma in
23232 @code{A}, we also know that the body of @code{A}
23233 will be elaborated before @code{B}, so
23234 that calls to @code{A} are safe and do not need a check.
23235 @end table
23237 @noindent
23238 Note that,
23239 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23240 the use of
23241 @code{Elaborate_Body} does not guarantee that the program is
23242 free of elaboration problems, because it may not be possible
23243 to satisfy the requested elaboration order.
23244 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23245 If a programmer
23246 marks @code{Unit_1} as @code{Elaborate_Body},
23247 and not @code{Unit_2,} then the order of
23248 elaboration will be:
23250 @smallexample
23251 @group
23252 Spec of Unit_2
23253 Spec of Unit_1
23254 Body of Unit_1
23255 Body of Unit_2
23256 @end group
23257 @end smallexample
23259 @noindent
23260 Now that means that the call to @code{Func_1} in @code{Unit_2}
23261 need not be checked,
23262 it must be safe. But the call to @code{Func_2} in
23263 @code{Unit_1} may still fail if
23264 @code{Expression_1} is equal to 1,
23265 and the programmer must still take
23266 responsibility for this not being the case.
23268 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23269 eliminated, except for calls entirely within a body, which are
23270 in any case fully under programmer control. However, using the pragma
23271 everywhere is not always possible.
23272 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23273 we marked both of them as having pragma @code{Elaborate_Body}, then
23274 clearly there would be no possible elaboration order.
23276 The above pragmas allow a server to guarantee safe use by clients, and
23277 clearly this is the preferable approach. Consequently a good rule
23278 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23279 and if this is not possible,
23280 mark them as @code{Elaborate_Body} if possible.
23281 As we have seen, there are situations where neither of these
23282 three pragmas can be used.
23283 So we also provide methods for clients to control the
23284 order of elaboration of the servers on which they depend:
23286 @table @asis
23287 @item pragma Elaborate (unit)
23288 @findex Elaborate
23289 @cindex pragma Elaborate
23290 This pragma is placed in the context clause, after a @code{with} clause,
23291 and it requires that the body of the named unit be elaborated before
23292 the unit in which the pragma occurs. The idea is to use this pragma
23293 if the current unit calls at elaboration time, directly or indirectly,
23294 some subprogram in the named unit.
23296 @item pragma Elaborate_All (unit)
23297 @findex Elaborate_All
23298 @cindex pragma Elaborate_All
23299 This is a stronger version of the Elaborate pragma. Consider the
23300 following example:
23302 @smallexample
23303 Unit A @code{with}'s unit B and calls B.Func in elab code
23304 Unit B @code{with}'s unit C, and B.Func calls C.Func
23305 @end smallexample
23307 @noindent
23308 Now if we put a pragma @code{Elaborate (B)}
23309 in unit @code{A}, this ensures that the
23310 body of @code{B} is elaborated before the call, but not the
23311 body of @code{C}, so
23312 the call to @code{C.Func} could still cause @code{Program_Error} to
23313 be raised.
23315 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23316 not only that the body of the named unit be elaborated before the
23317 unit doing the @code{with}, but also the bodies of all units that the
23318 named unit uses, following @code{with} links transitively. For example,
23319 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23320 then it requires
23321 not only that the body of @code{B} be elaborated before @code{A},
23322 but also the
23323 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23324 @end table
23326 @noindent
23327 We are now in a position to give a usage rule in Ada for avoiding
23328 elaboration problems, at least if dynamic dispatching and access to
23329 subprogram values are not used. We will handle these cases separately
23330 later.
23332 The rule is simple. If a unit has elaboration code that can directly or
23333 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23334 a generic package in a @code{with}'ed unit,
23335 then if the @code{with}'ed unit does not have
23336 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23337 a pragma @code{Elaborate_All}
23338 for the @code{with}'ed unit. By following this rule a client is
23339 assured that calls can be made without risk of an exception.
23341 For generic subprogram instantiations, the rule can be relaxed to
23342 require only a pragma @code{Elaborate} since elaborating the body
23343 of a subprogram cannot cause any transitive elaboration (we are
23344 not calling the subprogram in this case, just elaborating its
23345 declaration).
23347 If this rule is not followed, then a program may be in one of four
23348 states:
23350 @table @asis
23351 @item No order exists
23352 No order of elaboration exists which follows the rules, taking into
23353 account any @code{Elaborate}, @code{Elaborate_All},
23354 or @code{Elaborate_Body} pragmas. In
23355 this case, an Ada compiler must diagnose the situation at bind
23356 time, and refuse to build an executable program.
23358 @item One or more orders exist, all incorrect
23359 One or more acceptable elaboration orders exist, and all of them
23360 generate an elaboration order problem. In this case, the binder
23361 can build an executable program, but @code{Program_Error} will be raised
23362 when the program is run.
23364 @item Several orders exist, some right, some incorrect
23365 One or more acceptable elaboration orders exists, and some of them
23366 work, and some do not. The programmer has not controlled
23367 the order of elaboration, so the binder may or may not pick one of
23368 the correct orders, and the program may or may not raise an
23369 exception when it is run. This is the worst case, because it means
23370 that the program may fail when moved to another compiler, or even
23371 another version of the same compiler.
23373 @item One or more orders exists, all correct
23374 One ore more acceptable elaboration orders exist, and all of them
23375 work. In this case the program runs successfully. This state of
23376 affairs can be guaranteed by following the rule we gave above, but
23377 may be true even if the rule is not followed.
23378 @end table
23380 @noindent
23381 Note that one additional advantage of following our rules on the use
23382 of @code{Elaborate} and @code{Elaborate_All}
23383 is that the program continues to stay in the ideal (all orders OK) state
23384 even if maintenance
23385 changes some bodies of some units. Conversely, if a program that does
23386 not follow this rule happens to be safe at some point, this state of affairs
23387 may deteriorate silently as a result of maintenance changes.
23389 You may have noticed that the above discussion did not mention
23390 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23391 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23392 code in the body makes calls to some other unit, so it is still necessary
23393 to use @code{Elaborate_All} on such units.
23395 @node Controlling Elaboration in GNAT - Internal Calls
23396 @section Controlling Elaboration in GNAT - Internal Calls
23398 @noindent
23399 In the case of internal calls, i.e., calls within a single package, the
23400 programmer has full control over the order of elaboration, and it is up
23401 to the programmer to elaborate declarations in an appropriate order. For
23402 example writing:
23404 @smallexample @c ada
23405 @group
23406 @cartouche
23407 function One return Float;
23409 Q : Float := One;
23411 function One return Float is
23412 begin
23413      return 1.0;
23414 end One;
23415 @end cartouche
23416 @end group
23417 @end smallexample
23419 @noindent
23420 will obviously raise @code{Program_Error} at run time, because function
23421 One will be called before its body is elaborated. In this case GNAT will
23422 generate a warning that the call will raise @code{Program_Error}:
23424 @smallexample
23425 @group
23426 @cartouche
23427  1. procedure y is
23428  2.    function One return Float;
23429  3.
23430  4.    Q : Float := One;
23431                     |
23432     >>> warning: cannot call "One" before body is elaborated
23433     >>> warning: Program_Error will be raised at run time
23435  5.
23436  6.    function One return Float is
23437  7.    begin
23438  8.         return 1.0;
23439  9.    end One;
23441 11. begin
23442 12.    null;
23443 13. end;
23444 @end cartouche
23445 @end group
23446 @end smallexample
23448 @noindent
23449 Note that in this particular case, it is likely that the call is safe, because
23450 the function @code{One} does not access any global variables.
23451 Nevertheless in Ada, we do not want the validity of the check to depend on
23452 the contents of the body (think about the separate compilation case), so this
23453 is still wrong, as we discussed in the previous sections.
23455 The error is easily corrected by rearranging the declarations so that the
23456 body of @code{One} appears before the declaration containing the call
23457 (note that in Ada 95 and Ada 2005,
23458 declarations can appear in any order, so there is no restriction that
23459 would prevent this reordering, and if we write:
23461 @smallexample @c ada
23462 @group
23463 @cartouche
23464 function One return Float;
23466 function One return Float is
23467 begin
23468      return 1.0;
23469 end One;
23471 Q : Float := One;
23472 @end cartouche
23473 @end group
23474 @end smallexample
23476 @noindent
23477 then all is well, no warning is generated, and no
23478 @code{Program_Error} exception
23479 will be raised.
23480 Things are more complicated when a chain of subprograms is executed:
23482 @smallexample @c ada
23483 @group
23484 @cartouche
23485 function A return Integer;
23486 function B return Integer;
23487 function C return Integer;
23489 function B return Integer is begin return A; end;
23490 function C return Integer is begin return B; end;
23492 X : Integer := C;
23494 function A return Integer is begin return 1; end;
23495 @end cartouche
23496 @end group
23497 @end smallexample
23499 @noindent
23500 Now the call to @code{C}
23501 at elaboration time in the declaration of @code{X} is correct, because
23502 the body of @code{C} is already elaborated,
23503 and the call to @code{B} within the body of
23504 @code{C} is correct, but the call
23505 to @code{A} within the body of @code{B} is incorrect, because the body
23506 of @code{A} has not been elaborated, so @code{Program_Error}
23507 will be raised on the call to @code{A}.
23508 In this case GNAT will generate a
23509 warning that @code{Program_Error} may be
23510 raised at the point of the call. Let's look at the warning:
23512 @smallexample
23513 @group
23514 @cartouche
23515  1. procedure x is
23516  2.    function A return Integer;
23517  3.    function B return Integer;
23518  4.    function C return Integer;
23519  5.
23520  6.    function B return Integer is begin return A; end;
23521                                                     |
23522     >>> warning: call to "A" before body is elaborated may
23523                  raise Program_Error
23524     >>> warning: "B" called at line 7
23525     >>> warning: "C" called at line 9
23527  7.    function C return Integer is begin return B; end;
23528  8.
23529  9.    X : Integer := C;
23531 11.    function A return Integer is begin return 1; end;
23533 13. begin
23534 14.    null;
23535 15. end;
23536 @end cartouche
23537 @end group
23538 @end smallexample
23540 @noindent
23541 Note that the message here says ``may raise'', instead of the direct case,
23542 where the message says ``will be raised''. That's because whether
23543 @code{A} is
23544 actually called depends in general on run-time flow of control.
23545 For example, if the body of @code{B} said
23547 @smallexample @c ada
23548 @group
23549 @cartouche
23550 function B return Integer is
23551 begin
23552    if some-condition-depending-on-input-data then
23553       return A;
23554    else
23555       return 1;
23556    end if;
23557 end B;
23558 @end cartouche
23559 @end group
23560 @end smallexample
23562 @noindent
23563 then we could not know until run time whether the incorrect call to A would
23564 actually occur, so @code{Program_Error} might
23565 or might not be raised. It is possible for a compiler to
23566 do a better job of analyzing bodies, to
23567 determine whether or not @code{Program_Error}
23568 might be raised, but it certainly
23569 couldn't do a perfect job (that would require solving the halting problem
23570 and is provably impossible), and because this is a warning anyway, it does
23571 not seem worth the effort to do the analysis. Cases in which it
23572 would be relevant are rare.
23574 In practice, warnings of either of the forms given
23575 above will usually correspond to
23576 real errors, and should be examined carefully and eliminated.
23577 In the rare case where a warning is bogus, it can be suppressed by any of
23578 the following methods:
23580 @itemize @bullet
23581 @item
23582 Compile with the @option{-gnatws} switch set
23584 @item
23585 Suppress @code{Elaboration_Check} for the called subprogram
23587 @item
23588 Use pragma @code{Warnings_Off} to turn warnings off for the call
23589 @end itemize
23591 @noindent
23592 For the internal elaboration check case,
23593 GNAT by default generates the
23594 necessary run-time checks to ensure
23595 that @code{Program_Error} is raised if any
23596 call fails an elaboration check. Of course this can only happen if a
23597 warning has been issued as described above. The use of pragma
23598 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23599 some of these checks, meaning that it may be possible (but is not
23600 guaranteed) for a program to be able to call a subprogram whose body
23601 is not yet elaborated, without raising a @code{Program_Error} exception.
23603 @node Controlling Elaboration in GNAT - External Calls
23604 @section Controlling Elaboration in GNAT - External Calls
23606 @noindent
23607 The previous section discussed the case in which the execution of a
23608 particular thread of elaboration code occurred entirely within a
23609 single unit. This is the easy case to handle, because a programmer
23610 has direct and total control over the order of elaboration, and
23611 furthermore, checks need only be generated in cases which are rare
23612 and which the compiler can easily detect.
23613 The situation is more complex when separate compilation is taken into account.
23614 Consider the following:
23616 @smallexample @c ada
23617 @cartouche
23618 @group
23619 package Math is
23620    function Sqrt (Arg : Float) return Float;
23621 end Math;
23623 package body Math is
23624    function Sqrt (Arg : Float) return Float is
23625    begin
23626          @dots{}
23627    end Sqrt;
23628 end Math;
23629 @end group
23630 @group
23631 with Math;
23632 package Stuff is
23633    X : Float := Math.Sqrt (0.5);
23634 end Stuff;
23636 with Stuff;
23637 procedure Main is
23638 begin
23639    @dots{}
23640 end Main;
23641 @end group
23642 @end cartouche
23643 @end smallexample
23645 @noindent
23646 where @code{Main} is the main program. When this program is executed, the
23647 elaboration code must first be executed, and one of the jobs of the
23648 binder is to determine the order in which the units of a program are
23649 to be elaborated. In this case we have four units: the spec and body
23650 of @code{Math},
23651 the spec of @code{Stuff} and the body of @code{Main}).
23652 In what order should the four separate sections of elaboration code
23653 be executed?
23655 There are some restrictions in the order of elaboration that the binder
23656 can choose. In particular, if unit U has a @code{with}
23657 for a package @code{X}, then you
23658 are assured that the spec of @code{X}
23659 is elaborated before U , but you are
23660 not assured that the body of @code{X}
23661 is elaborated before U.
23662 This means that in the above case, the binder is allowed to choose the
23663 order:
23665 @smallexample
23666 spec of Math
23667 spec of Stuff
23668 body of Math
23669 body of Main
23670 @end smallexample
23672 @noindent
23673 but that's not good, because now the call to @code{Math.Sqrt}
23674 that happens during
23675 the elaboration of the @code{Stuff}
23676 spec happens before the body of @code{Math.Sqrt} is
23677 elaborated, and hence causes @code{Program_Error} exception to be raised.
23678 At first glance, one might say that the binder is misbehaving, because
23679 obviously you want to elaborate the body of something you @code{with}
23680 first, but
23681 that is not a general rule that can be followed in all cases. Consider
23683 @smallexample @c ada
23684 @group
23685 @cartouche
23686 package X is @dots{}
23688 package Y is @dots{}
23690 with X;
23691 package body Y is @dots{}
23693 with Y;
23694 package body X is @dots{}
23695 @end cartouche
23696 @end group
23697 @end smallexample
23699 @noindent
23700 This is a common arrangement, and, apart from the order of elaboration
23701 problems that might arise in connection with elaboration code, this works fine.
23702 A rule that says that you must first elaborate the body of anything you
23703 @code{with} cannot work in this case:
23704 the body of @code{X} @code{with}'s @code{Y},
23705 which means you would have to
23706 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23707 which means
23708 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23709 loop that cannot be broken.
23711 It is true that the binder can in many cases guess an order of elaboration
23712 that is unlikely to cause a @code{Program_Error}
23713 exception to be raised, and it tries to do so (in the
23714 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23715 by default
23716 elaborate the body of @code{Math} right after its spec, so all will be well).
23718 However, a program that blindly relies on the binder to be helpful can
23719 get into trouble, as we discussed in the previous sections, so
23720 GNAT
23721 provides a number of facilities for assisting the programmer in
23722 developing programs that are robust with respect to elaboration order.
23724 @node Default Behavior in GNAT - Ensuring Safety
23725 @section Default Behavior in GNAT - Ensuring Safety
23727 @noindent
23728 The default behavior in GNAT ensures elaboration safety. In its
23729 default mode GNAT implements the
23730 rule we previously described as the right approach. Let's restate it:
23732 @itemize
23733 @item
23734 @emph{If a unit has elaboration code that can directly or indirectly make a
23735 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23736 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23737 does not have pragma @code{Pure} or
23738 @code{Preelaborate}, then the client should have an
23739 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23741 @emph{In the case of instantiating a generic subprogram, it is always
23742 sufficient to have only an @code{Elaborate} pragma for the
23743 @code{with}'ed unit.}
23744 @end itemize
23746 @noindent
23747 By following this rule a client is assured that calls and instantiations
23748 can be made without risk of an exception.
23750 In this mode GNAT traces all calls that are potentially made from
23751 elaboration code, and puts in any missing implicit @code{Elaborate}
23752 and @code{Elaborate_All} pragmas.
23753 The advantage of this approach is that no elaboration problems
23754 are possible if the binder can find an elaboration order that is
23755 consistent with these implicit @code{Elaborate} and
23756 @code{Elaborate_All} pragmas. The
23757 disadvantage of this approach is that no such order may exist.
23759 If the binder does not generate any diagnostics, then it means that it has
23760 found an elaboration order that is guaranteed to be safe. However, the binder
23761 may still be relying on implicitly generated @code{Elaborate} and
23762 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23763 guaranteed.
23765 If it is important to guarantee portability, then the compilations should
23766 use the
23767 @option{-gnatwl}
23768 (warn on elaboration problems) switch. This will cause warning messages
23769 to be generated indicating the missing @code{Elaborate} and
23770 @code{Elaborate_All} pragmas.
23771 Consider the following source program:
23773 @smallexample @c ada
23774 @group
23775 @cartouche
23776 with k;
23777 package j is
23778   m : integer := k.r;
23779 end;
23780 @end cartouche
23781 @end group
23782 @end smallexample
23784 @noindent
23785 where it is clear that there
23786 should be a pragma @code{Elaborate_All}
23787 for unit @code{k}. An implicit pragma will be generated, and it is
23788 likely that the binder will be able to honor it. However, if you want
23789 to port this program to some other Ada compiler than GNAT.
23790 it is safer to include the pragma explicitly in the source. If this
23791 unit is compiled with the
23792 @option{-gnatwl}
23793 switch, then the compiler outputs a warning:
23795 @smallexample
23796 @group
23797 @cartouche
23798 1. with k;
23799 2. package j is
23800 3.   m : integer := k.r;
23801                      |
23802    >>> warning: call to "r" may raise Program_Error
23803    >>> warning: missing pragma Elaborate_All for "k"
23805 4. end;
23806 @end cartouche
23807 @end group
23808 @end smallexample
23810 @noindent
23811 and these warnings can be used as a guide for supplying manually
23812 the missing pragmas. It is usually a bad idea to use this warning
23813 option during development. That's because it will warn you when
23814 you need to put in a pragma, but cannot warn you when it is time
23815 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23816 unnecessary dependencies and even false circularities.
23818 This default mode is more restrictive than the Ada Reference
23819 Manual, and it is possible to construct programs which will compile
23820 using the dynamic model described there, but will run into a
23821 circularity using the safer static model we have described.
23823 Of course any Ada compiler must be able to operate in a mode
23824 consistent with the requirements of the Ada Reference Manual,
23825 and in particular must have the capability of implementing the
23826 standard dynamic model of elaboration with run-time checks.
23828 In GNAT, this standard mode can be achieved either by the use of
23829 the @option{-gnatE} switch on the compiler (@command{gcc} or
23830 @command{gnatmake}) command, or by the use of the configuration pragma:
23832 @smallexample @c ada
23833 pragma Elaboration_Checks (DYNAMIC);
23834 @end smallexample
23836 @noindent
23837 Either approach will cause the unit affected to be compiled using the
23838 standard dynamic run-time elaboration checks described in the Ada
23839 Reference Manual. The static model is generally preferable, since it
23840 is clearly safer to rely on compile and link time checks rather than
23841 run-time checks. However, in the case of legacy code, it may be
23842 difficult to meet the requirements of the static model. This
23843 issue is further discussed in
23844 @ref{What to Do If the Default Elaboration Behavior Fails}.
23846 Note that the static model provides a strict subset of the allowed
23847 behavior and programs of the Ada Reference Manual, so if you do
23848 adhere to the static model and no circularities exist,
23849 then you are assured that your program will
23850 work using the dynamic model, providing that you remove any
23851 pragma Elaborate statements from the source.
23853 @node Treatment of Pragma Elaborate
23854 @section Treatment of Pragma Elaborate
23855 @cindex Pragma Elaborate
23857 @noindent
23858 The use of @code{pragma Elaborate}
23859 should generally be avoided in Ada 95 and Ada 2005 programs,
23860 since there is no guarantee that transitive calls
23861 will be properly handled. Indeed at one point, this pragma was placed
23862 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23864 Now that's a bit restrictive. In practice, the case in which
23865 @code{pragma Elaborate} is useful is when the caller knows that there
23866 are no transitive calls, or that the called unit contains all necessary
23867 transitive @code{pragma Elaborate} statements, and legacy code often
23868 contains such uses.
23870 Strictly speaking the static mode in GNAT should ignore such pragmas,
23871 since there is no assurance at compile time that the necessary safety
23872 conditions are met. In practice, this would cause GNAT to be incompatible
23873 with correctly written Ada 83 code that had all necessary
23874 @code{pragma Elaborate} statements in place. Consequently, we made the
23875 decision that GNAT in its default mode will believe that if it encounters
23876 a @code{pragma Elaborate} then the programmer knows what they are doing,
23877 and it will trust that no elaboration errors can occur.
23879 The result of this decision is two-fold. First to be safe using the
23880 static mode, you should remove all @code{pragma Elaborate} statements.
23881 Second, when fixing circularities in existing code, you can selectively
23882 use @code{pragma Elaborate} statements to convince the static mode of
23883 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23884 statement.
23886 When using the static mode with @option{-gnatwl}, any use of
23887 @code{pragma Elaborate} will generate a warning about possible
23888 problems.
23890 @node Elaboration Issues for Library Tasks
23891 @section Elaboration Issues for Library Tasks
23892 @cindex Library tasks, elaboration issues
23893 @cindex Elaboration of library tasks
23895 @noindent
23896 In this section we examine special elaboration issues that arise for
23897 programs that declare library level tasks.
23899 Generally the model of execution of an Ada program is that all units are
23900 elaborated, and then execution of the program starts. However, the
23901 declaration of library tasks definitely does not fit this model. The
23902 reason for this is that library tasks start as soon as they are declared
23903 (more precisely, as soon as the statement part of the enclosing package
23904 body is reached), that is to say before elaboration
23905 of the program is complete. This means that if such a task calls a
23906 subprogram, or an entry in another task, the callee may or may not be
23907 elaborated yet, and in the standard
23908 Reference Manual model of dynamic elaboration checks, you can even
23909 get timing dependent Program_Error exceptions, since there can be
23910 a race between the elaboration code and the task code.
23912 The static model of elaboration in GNAT seeks to avoid all such
23913 dynamic behavior, by being conservative, and the conservative
23914 approach in this particular case is to assume that all the code
23915 in a task body is potentially executed at elaboration time if
23916 a task is declared at the library level.
23918 This can definitely result in unexpected circularities. Consider
23919 the following example
23921 @smallexample @c ada
23922 package Decls is
23923   task Lib_Task is
23924      entry Start;
23925   end Lib_Task;
23927   type My_Int is new Integer;
23929   function Ident (M : My_Int) return My_Int;
23930 end Decls;
23932 with Utils;
23933 package body Decls is
23934   task body Lib_Task is
23935   begin
23936      accept Start;
23937      Utils.Put_Val (2);
23938   end Lib_Task;
23940   function Ident (M : My_Int) return My_Int is
23941   begin
23942      return M;
23943   end Ident;
23944 end Decls;
23946 with Decls;
23947 package Utils is
23948   procedure Put_Val (Arg : Decls.My_Int);
23949 end Utils;
23951 with Text_IO;
23952 package body Utils is
23953   procedure Put_Val (Arg : Decls.My_Int) is
23954   begin
23955      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23956   end Put_Val;
23957 end Utils;
23959 with Decls;
23960 procedure Main is
23961 begin
23962    Decls.Lib_Task.Start;
23963 end;
23964 @end smallexample
23966 @noindent
23967 If the above example is compiled in the default static elaboration
23968 mode, then a circularity occurs. The circularity comes from the call
23969 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23970 this call occurs in elaboration code, we need an implicit pragma
23971 @code{Elaborate_All} for @code{Utils}. This means that not only must
23972 the spec and body of @code{Utils} be elaborated before the body
23973 of @code{Decls}, but also the spec and body of any unit that is
23974 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23975 the body of @code{Decls}. This is the transitive implication of
23976 pragma @code{Elaborate_All} and it makes sense, because in general
23977 the body of @code{Put_Val} might have a call to something in a
23978 @code{with'ed} unit.
23980 In this case, the body of Utils (actually its spec) @code{with's}
23981 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23982 must be elaborated before itself, in case there is a call from the
23983 body of @code{Utils}.
23985 Here is the exact chain of events we are worrying about:
23987 @enumerate
23988 @item
23989 In the body of @code{Decls} a call is made from within the body of a library
23990 task to a subprogram in the package @code{Utils}. Since this call may
23991 occur at elaboration time (given that the task is activated at elaboration
23992 time), we have to assume the worst, i.e., that the
23993 call does happen at elaboration time.
23995 @item
23996 This means that the body and spec of @code{Util} must be elaborated before
23997 the body of @code{Decls} so that this call does not cause an access before
23998 elaboration.
24000 @item
24001 Within the body of @code{Util}, specifically within the body of
24002 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24003 by this package.
24005 @item
24006 One such @code{with}'ed package is package @code{Decls}, so there
24007 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24008 In fact there is such a call in this example, but we would have to
24009 assume that there was such a call even if it were not there, since
24010 we are not supposed to write the body of @code{Decls} knowing what
24011 is in the body of @code{Utils}; certainly in the case of the
24012 static elaboration model, the compiler does not know what is in
24013 other bodies and must assume the worst.
24015 @item
24016 This means that the spec and body of @code{Decls} must also be
24017 elaborated before we elaborate the unit containing the call, but
24018 that unit is @code{Decls}! This means that the body of @code{Decls}
24019 must be elaborated before itself, and that's a circularity.
24020 @end enumerate
24022 @noindent
24023 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24024 the body of @code{Decls} you will get a true Ada Reference Manual
24025 circularity that makes the program illegal.
24027 In practice, we have found that problems with the static model of
24028 elaboration in existing code often arise from library tasks, so
24029 we must address this particular situation.
24031 Note that if we compile and run the program above, using the dynamic model of
24032 elaboration (that is to say use the @option{-gnatE} switch),
24033 then it compiles, binds,
24034 links, and runs, printing the expected result of 2. Therefore in some sense
24035 the circularity here is only apparent, and we need to capture
24036 the properties of this program that  distinguish it from other library-level
24037 tasks that have real elaboration problems.
24039 We have four possible answers to this question:
24041 @itemize @bullet
24043 @item
24044 Use the dynamic model of elaboration.
24046 If we use the @option{-gnatE} switch, then as noted above, the program works.
24047 Why is this? If we examine the task body, it is apparent that the task cannot
24048 proceed past the
24049 @code{accept} statement until after elaboration has been completed, because
24050 the corresponding entry call comes from the main program, not earlier.
24051 This is why the dynamic model works here. But that's really giving
24052 up on a precise analysis, and we prefer to take this approach only if we cannot
24053 solve the
24054 problem in any other manner. So let us examine two ways to reorganize
24055 the program to avoid the potential elaboration problem.
24057 @item
24058 Split library tasks into separate packages.
24060 Write separate packages, so that library tasks are isolated from
24061 other declarations as much as possible. Let us look at a variation on
24062 the above program.
24064 @smallexample @c ada
24065 package Decls1 is
24066   task Lib_Task is
24067      entry Start;
24068   end Lib_Task;
24069 end Decls1;
24071 with Utils;
24072 package body Decls1 is
24073   task body Lib_Task is
24074   begin
24075      accept Start;
24076      Utils.Put_Val (2);
24077   end Lib_Task;
24078 end Decls1;
24080 package Decls2 is
24081   type My_Int is new Integer;
24082   function Ident (M : My_Int) return My_Int;
24083 end Decls2;
24085 with Utils;
24086 package body Decls2 is
24087   function Ident (M : My_Int) return My_Int is
24088   begin
24089      return M;
24090   end Ident;
24091 end Decls2;
24093 with Decls2;
24094 package Utils is
24095   procedure Put_Val (Arg : Decls2.My_Int);
24096 end Utils;
24098 with Text_IO;
24099 package body Utils is
24100   procedure Put_Val (Arg : Decls2.My_Int) is
24101   begin
24102      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24103   end Put_Val;
24104 end Utils;
24106 with Decls1;
24107 procedure Main is
24108 begin
24109    Decls1.Lib_Task.Start;
24110 end;
24111 @end smallexample
24113 @noindent
24114 All we have done is to split @code{Decls} into two packages, one
24115 containing the library task, and one containing everything else. Now
24116 there is no cycle, and the program compiles, binds, links and executes
24117 using the default static model of elaboration.
24119 @item
24120 Declare separate task types.
24122 A significant part of the problem arises because of the use of the
24123 single task declaration form. This means that the elaboration of
24124 the task type, and the elaboration of the task itself (i.e.@: the
24125 creation of the task) happen at the same time. A good rule
24126 of style in Ada is to always create explicit task types. By
24127 following the additional step of placing task objects in separate
24128 packages from the task type declaration, many elaboration problems
24129 are avoided. Here is another modified example of the example program:
24131 @smallexample @c ada
24132 package Decls is
24133   task type Lib_Task_Type is
24134      entry Start;
24135   end Lib_Task_Type;
24137   type My_Int is new Integer;
24139   function Ident (M : My_Int) return My_Int;
24140 end Decls;
24142 with Utils;
24143 package body Decls is
24144   task body Lib_Task_Type is
24145   begin
24146      accept Start;
24147      Utils.Put_Val (2);
24148   end Lib_Task_Type;
24150   function Ident (M : My_Int) return My_Int is
24151   begin
24152      return M;
24153   end Ident;
24154 end Decls;
24156 with Decls;
24157 package Utils is
24158   procedure Put_Val (Arg : Decls.My_Int);
24159 end Utils;
24161 with Text_IO;
24162 package body Utils is
24163   procedure Put_Val (Arg : Decls.My_Int) is
24164   begin
24165      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24166   end Put_Val;
24167 end Utils;
24169 with Decls;
24170 package Declst is
24171    Lib_Task : Decls.Lib_Task_Type;
24172 end Declst;
24174 with Declst;
24175 procedure Main is
24176 begin
24177    Declst.Lib_Task.Start;
24178 end;
24179 @end smallexample
24181 @noindent
24182 What we have done here is to replace the @code{task} declaration in
24183 package @code{Decls} with a @code{task type} declaration. Then we
24184 introduce a separate package @code{Declst} to contain the actual
24185 task object. This separates the elaboration issues for
24186 the @code{task type}
24187 declaration, which causes no trouble, from the elaboration issues
24188 of the task object, which is also unproblematic, since it is now independent
24189 of the elaboration of  @code{Utils}.
24190 This separation of concerns also corresponds to
24191 a generally sound engineering principle of separating declarations
24192 from instances. This version of the program also compiles, binds, links,
24193 and executes, generating the expected output.
24195 @item
24196 Use No_Entry_Calls_In_Elaboration_Code restriction.
24197 @cindex No_Entry_Calls_In_Elaboration_Code
24199 The previous two approaches described how a program can be restructured
24200 to avoid the special problems caused by library task bodies. in practice,
24201 however, such restructuring may be difficult to apply to existing legacy code,
24202 so we must consider solutions that do not require massive rewriting.
24204 Let us consider more carefully why our original sample program works
24205 under the dynamic model of elaboration. The reason is that the code
24206 in the task body blocks immediately on the @code{accept}
24207 statement. Now of course there is nothing to prohibit elaboration
24208 code from making entry calls (for example from another library level task),
24209 so we cannot tell in isolation that
24210 the task will not execute the accept statement  during elaboration.
24212 However, in practice it is very unusual to see elaboration code
24213 make any entry calls, and the pattern of tasks starting
24214 at elaboration time and then immediately blocking on @code{accept} or
24215 @code{select} statements is very common. What this means is that
24216 the compiler is being too pessimistic when it analyzes the
24217 whole package body as though it might be executed at elaboration
24218 time.
24220 If we know that the elaboration code contains no entry calls, (a very safe
24221 assumption most of the time, that could almost be made the default
24222 behavior), then we can compile all units of the program under control
24223 of the following configuration pragma:
24225 @smallexample
24226 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24227 @end smallexample
24229 @noindent
24230 This pragma can be placed in the @file{gnat.adc} file in the usual
24231 manner. If we take our original unmodified program and compile it
24232 in the presence of a @file{gnat.adc} containing the above pragma,
24233 then once again, we can compile, bind, link, and execute, obtaining
24234 the expected result. In the presence of this pragma, the compiler does
24235 not trace calls in a task body, that appear after the first @code{accept}
24236 or @code{select} statement, and therefore does not report a potential
24237 circularity in the original program.
24239 The compiler will check to the extent it can that the above
24240 restriction is not violated, but it is not always possible to do a
24241 complete check at compile time, so it is important to use this
24242 pragma only if the stated restriction is in fact met, that is to say
24243 no task receives an entry call before elaboration of all units is completed.
24245 @end itemize
24247 @node Mixing Elaboration Models
24248 @section Mixing Elaboration Models
24249 @noindent
24250 So far, we have assumed that the entire program is either compiled
24251 using the dynamic model or static model, ensuring consistency. It
24252 is possible to mix the two models, but rules have to be followed
24253 if this mixing is done to ensure that elaboration checks are not
24254 omitted.
24256 The basic rule is that @emph{a unit compiled with the static model cannot
24257 be @code{with'ed} by a unit compiled with the dynamic model}. The
24258 reason for this is that in the static model, a unit assumes that
24259 its clients guarantee to use (the equivalent of) pragma
24260 @code{Elaborate_All} so that no elaboration checks are required
24261 in inner subprograms, and this assumption is violated if the
24262 client is compiled with dynamic checks.
24264 The precise rule is as follows. A unit that is compiled with dynamic
24265 checks can only @code{with} a unit that meets at least one of the
24266 following criteria:
24268 @itemize @bullet
24270 @item
24271 The @code{with'ed} unit is itself compiled with dynamic elaboration
24272 checks (that is with the @option{-gnatE} switch.
24274 @item
24275 The @code{with'ed} unit is an internal GNAT implementation unit from
24276 the System, Interfaces, Ada, or GNAT hierarchies.
24278 @item
24279 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24281 @item
24282 The @code{with'ing} unit (that is the client) has an explicit pragma
24283 @code{Elaborate_All} for the @code{with'ed} unit.
24285 @end itemize
24287 @noindent
24288 If this rule is violated, that is if a unit with dynamic elaboration
24289 checks @code{with's} a unit that does not meet one of the above four
24290 criteria, then the binder (@code{gnatbind}) will issue a warning
24291 similar to that in the following example:
24293 @smallexample
24294 warning: "x.ads" has dynamic elaboration checks and with's
24295 warning:   "y.ads" which has static elaboration checks
24296 @end smallexample
24298 @noindent
24299 These warnings indicate that the rule has been violated, and that as a result
24300 elaboration checks may be missed in the resulting executable file.
24301 This warning may be suppressed using the @option{-ws} binder switch
24302 in the usual manner.
24304 One useful application of this mixing rule is in the case of a subsystem
24305 which does not itself @code{with} units from the remainder of the
24306 application. In this case, the entire subsystem can be compiled with
24307 dynamic checks to resolve a circularity in the subsystem, while
24308 allowing the main application that uses this subsystem to be compiled
24309 using the more reliable default static model.
24311 @node What to Do If the Default Elaboration Behavior Fails
24312 @section What to Do If the Default Elaboration Behavior Fails
24314 @noindent
24315 If the binder cannot find an acceptable order, it outputs detailed
24316 diagnostics. For example:
24317 @smallexample
24318 @group
24319 @iftex
24320 @leftskip=0cm
24321 @end iftex
24322 error: elaboration circularity detected
24323 info:   "proc (body)" must be elaborated before "pack (body)"
24324 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24325 info:     recompile "pack (body)" with -gnatwl
24326 info:                             for full details
24327 info:       "proc (body)"
24328 info:         is needed by its spec:
24329 info:       "proc (spec)"
24330 info:         which is withed by:
24331 info:       "pack (body)"
24332 info:  "pack (body)" must be elaborated before "proc (body)"
24333 info:     reason: pragma Elaborate in unit "proc (body)"
24334 @end group
24336 @end smallexample
24338 @noindent
24339 In this case we have a cycle that the binder cannot break. On the one
24340 hand, there is an explicit pragma Elaborate in @code{proc} for
24341 @code{pack}. This means that the body of @code{pack} must be elaborated
24342 before the body of @code{proc}. On the other hand, there is elaboration
24343 code in @code{pack} that calls a subprogram in @code{proc}. This means
24344 that for maximum safety, there should really be a pragma
24345 Elaborate_All in @code{pack} for @code{proc} which would require that
24346 the body of @code{proc} be elaborated before the body of
24347 @code{pack}. Clearly both requirements cannot be satisfied.
24348 Faced with a circularity of this kind, you have three different options.
24350 @table @asis
24351 @item Fix the program
24352 The most desirable option from the point of view of long-term maintenance
24353 is to rearrange the program so that the elaboration problems are avoided.
24354 One useful technique is to place the elaboration code into separate
24355 child packages. Another is to move some of the initialization code to
24356 explicitly called subprograms, where the program controls the order
24357 of initialization explicitly. Although this is the most desirable option,
24358 it may be impractical and involve too much modification, especially in
24359 the case of complex legacy code.
24361 @item Perform dynamic checks
24362 If the compilations are done using the
24363 @option{-gnatE}
24364 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24365 manner. Dynamic checks are generated for all calls that could possibly result
24366 in raising an exception. With this switch, the compiler does not generate
24367 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24368 exactly as specified in the @cite{Ada Reference Manual}.
24369 The binder will generate
24370 an executable program that may or may not raise @code{Program_Error}, and then
24371 it is the programmer's job to ensure that it does not raise an exception. Note
24372 that it is important to compile all units with the switch, it cannot be used
24373 selectively.
24375 @item Suppress checks
24376 The drawback of dynamic checks is that they generate a
24377 significant overhead at run time, both in space and time. If you
24378 are absolutely sure that your program cannot raise any elaboration
24379 exceptions, and you still want to use the dynamic elaboration model,
24380 then you can use the configuration pragma
24381 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24382 example this pragma could be placed in the @file{gnat.adc} file.
24384 @item Suppress checks selectively
24385 When you know that certain calls or instantiations in elaboration code cannot
24386 possibly lead to an elaboration error, and the binder nevertheless complains
24387 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24388 elaboration circularities, it is possible to remove those warnings locally and
24389 obtain a program that will bind. Clearly this can be unsafe, and it is the
24390 responsibility of the programmer to make sure that the resulting program has no
24391 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24392 used with different granularity to suppress warnings and break elaboration
24393 circularities:
24395 @itemize @bullet
24396 @item
24397 Place the pragma that names the called subprogram in the declarative part
24398 that contains the call.
24400 @item
24401 Place the pragma in the declarative part, without naming an entity. This
24402 disables warnings on all calls in the corresponding  declarative region.
24404 @item
24405 Place the pragma in the package spec that declares the called subprogram,
24406 and name the subprogram. This disables warnings on all elaboration calls to
24407 that subprogram.
24409 @item
24410 Place the pragma in the package spec that declares the called subprogram,
24411 without naming any entity. This disables warnings on all elaboration calls to
24412 all subprograms declared in this spec.
24414 @item Use Pragma Elaborate
24415 As previously described in section @xref{Treatment of Pragma Elaborate},
24416 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24417 that no elaboration checks are required on calls to the designated unit.
24418 There may be cases in which the caller knows that no transitive calls
24419 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24420 case where @code{pragma Elaborate_All} would cause a circularity.
24421 @end itemize
24423 @noindent
24424 These five cases are listed in order of decreasing safety, and therefore
24425 require increasing programmer care in their application. Consider the
24426 following program:
24428 @smallexample @c adanocomment
24429 package Pack1 is
24430   function F1 return Integer;
24431   X1 : Integer;
24432 end Pack1;
24434 package Pack2 is
24435   function F2 return Integer;
24436   function Pure (x : integer) return integer;
24437   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24438   --  pragma Suppress (Elaboration_Check);              -- (4)
24439 end Pack2;
24441 with Pack2;
24442 package body Pack1 is
24443   function F1 return Integer is
24444   begin
24445     return 100;
24446   end F1;
24447   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24448 begin
24449   declare
24450     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24451     --  pragma Suppress(Elaboration_Check);             -- (2)
24452   begin
24453     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24454   end;
24455 end Pack1;
24457 with Pack1;
24458 package body Pack2 is
24459   function F2 return Integer is
24460   begin
24461      return Pack1.F1;
24462   end F2;
24463   function Pure (x : integer) return integer is
24464   begin
24465      return x ** 3 - 3 * x;
24466   end;
24467 end Pack2;
24469 with Pack1, Ada.Text_IO;
24470 procedure Proc3 is
24471 begin
24472   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24473 end Proc3;
24474 @end smallexample
24475 In the absence of any pragmas, an attempt to bind this program produces
24476 the following diagnostics:
24477 @smallexample
24478 @group
24479 @iftex
24480 @leftskip=.5cm
24481 @end iftex
24482 error: elaboration circularity detected
24483 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24484 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24485 info:       recompile "pack1 (body)" with -gnatwl for full details
24486 info:          "pack1 (body)"
24487 info:             must be elaborated along with its spec:
24488 info:          "pack1 (spec)"
24489 info:             which is withed by:
24490 info:          "pack2 (body)"
24491 info:             which must be elaborated along with its spec:
24492 info:          "pack2 (spec)"
24493 info:             which is withed by:
24494 info:          "pack1 (body)"
24495 @end group
24496 @end smallexample
24497 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24498 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24499 F2 is safe, even though F2 calls F1, because the call appears after the
24500 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24501 remove the warning on the call. It is also possible to use pragma (2)
24502 because there are no other potentially unsafe calls in the block.
24504 @noindent
24505 The call to @code{Pure} is safe because this function does not depend on the
24506 state of @code{Pack2}. Therefore any call to this function is safe, and it
24507 is correct to place pragma (3) in the corresponding package spec.
24509 @noindent
24510 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24511 warnings on all calls to functions declared therein. Note that this is not
24512 necessarily safe, and requires more detailed examination of the subprogram
24513 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24514 be already elaborated.
24515 @end table
24517 @noindent
24518 It is hard to generalize on which of these four approaches should be
24519 taken. Obviously if it is possible to fix the program so that the default
24520 treatment works, this is preferable, but this may not always be practical.
24521 It is certainly simple enough to use
24522 @option{-gnatE}
24523 but the danger in this case is that, even if the GNAT binder
24524 finds a correct elaboration order, it may not always do so,
24525 and certainly a binder from another Ada compiler might not. A
24526 combination of testing and analysis (for which the warnings generated
24527 with the
24528 @option{-gnatwl}
24529 switch can be useful) must be used to ensure that the program is free
24530 of errors. One switch that is useful in this testing is the
24531 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24532 switch for
24533 @code{gnatbind}.
24534 Normally the binder tries to find an order that has the best chance
24535 of avoiding elaboration problems. However, if this switch is used, the binder
24536 plays a devil's advocate role, and tries to choose the order that
24537 has the best chance of failing. If your program works even with this
24538 switch, then it has a better chance of being error free, but this is still
24539 not a guarantee.
24541 For an example of this approach in action, consider the C-tests (executable
24542 tests) from the ACVC suite. If these are compiled and run with the default
24543 treatment, then all but one of them succeed without generating any error
24544 diagnostics from the binder. However, there is one test that fails, and
24545 this is not surprising, because the whole point of this test is to ensure
24546 that the compiler can handle cases where it is impossible to determine
24547 a correct order statically, and it checks that an exception is indeed
24548 raised at run time.
24550 This one test must be compiled and run using the
24551 @option{-gnatE}
24552 switch, and then it passes. Alternatively, the entire suite can
24553 be run using this switch. It is never wrong to run with the dynamic
24554 elaboration switch if your code is correct, and we assume that the
24555 C-tests are indeed correct (it is less efficient, but efficiency is
24556 not a factor in running the ACVC tests.)
24558 @node Elaboration for Access-to-Subprogram Values
24559 @section Elaboration for Access-to-Subprogram Values
24560 @cindex Access-to-subprogram
24562 @noindent
24563 Access-to-subprogram types (introduced in Ada 95) complicate
24564 the handling of elaboration. The trouble is that it becomes
24565 impossible to tell at compile time which procedure
24566 is being called. This means that it is not possible for the binder
24567 to analyze the elaboration requirements in this case.
24569 If at the point at which the access value is created
24570 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24571 the body of the subprogram is
24572 known to have been elaborated, then the access value is safe, and its use
24573 does not require a check. This may be achieved by appropriate arrangement
24574 of the order of declarations if the subprogram is in the current unit,
24575 or, if the subprogram is in another unit, by using pragma
24576 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24577 on the referenced unit.
24579 If the referenced body is not known to have been elaborated at the point
24580 the access value is created, then any use of the access value must do a
24581 dynamic check, and this dynamic check will fail and raise a
24582 @code{Program_Error} exception if the body has not been elaborated yet.
24583 GNAT will generate the necessary checks, and in addition, if the
24584 @option{-gnatwl}
24585 switch is set, will generate warnings that such checks are required.
24587 The use of dynamic dispatching for tagged types similarly generates
24588 a requirement for dynamic checks, and premature calls to any primitive
24589 operation of a tagged type before the body of the operation has been
24590 elaborated, will result in the raising of @code{Program_Error}.
24592 @node Summary of Procedures for Elaboration Control
24593 @section Summary of Procedures for Elaboration Control
24594 @cindex Elaboration control
24596 @noindent
24597 First, compile your program with the default options, using none of
24598 the special elaboration control switches. If the binder successfully
24599 binds your program, then you can be confident that, apart from issues
24600 raised by the use of access-to-subprogram types and dynamic dispatching,
24601 the program is free of elaboration errors. If it is important that the
24602 program be portable, then use the
24603 @option{-gnatwl}
24604 switch to generate warnings about missing @code{Elaborate} or
24605 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24607 If the program fails to bind using the default static elaboration
24608 handling, then you can fix the program to eliminate the binder
24609 message, or recompile the entire program with the
24610 @option{-gnatE} switch to generate dynamic elaboration checks,
24611 and, if you are sure there really are no elaboration problems,
24612 use a global pragma @code{Suppress (Elaboration_Check)}.
24614 @node Other Elaboration Order Considerations
24615 @section Other Elaboration Order Considerations
24616 @noindent
24617 This section has been entirely concerned with the issue of finding a valid
24618 elaboration order, as defined by the Ada Reference Manual. In a case
24619 where several elaboration orders are valid, the task is to find one
24620 of the possible valid elaboration orders (and the static model in GNAT
24621 will ensure that this is achieved).
24623 The purpose of the elaboration rules in the Ada Reference Manual is to
24624 make sure that no entity is accessed before it has been elaborated. For
24625 a subprogram, this means that the spec and body must have been elaborated
24626 before the subprogram is called. For an object, this means that the object
24627 must have been elaborated before its value is read or written. A violation
24628 of either of these two requirements is an access before elaboration order,
24629 and this section has been all about avoiding such errors.
24631 In the case where more than one order of elaboration is possible, in the
24632 sense that access before elaboration errors are avoided, then any one of
24633 the orders is ``correct'' in the sense that it meets the requirements of
24634 the Ada Reference Manual, and no such error occurs.
24636 However, it may be the case for a given program, that there are
24637 constraints on the order of elaboration that come not from consideration
24638 of avoiding elaboration errors, but rather from extra-lingual logic
24639 requirements. Consider this example:
24641 @smallexample @c ada
24642 with Init_Constants;
24643 package Constants is
24644    X : Integer := 0;
24645    Y : Integer := 0;
24646 end Constants;
24648 package Init_Constants is
24649    procedure P; -- require a body
24650 end Init_Constants;
24652 with Constants;
24653 package body Init_Constants is
24654    procedure P is begin null; end;
24655 begin
24656    Constants.X := 3;
24657    Constants.Y := 4;
24658 end Init_Constants;
24660 with Constants;
24661 package Calc is
24662    Z : Integer := Constants.X + Constants.Y;
24663 end Calc;
24665 with Calc;
24666 with Text_IO; use Text_IO;
24667 procedure Main is
24668 begin
24669    Put_Line (Calc.Z'Img);
24670 end Main;
24671 @end smallexample
24673 @noindent
24674 In this example, there is more than one valid order of elaboration. For
24675 example both the following are correct orders:
24677 @smallexample
24678 Init_Constants spec
24679 Constants spec
24680 Calc spec
24681 Init_Constants body
24682 Main body
24684   and
24686 Init_Constants spec
24687 Init_Constants body
24688 Constants spec
24689 Calc spec
24690 Main body
24691 @end smallexample
24693 @noindent
24694 There is no language rule to prefer one or the other, both are correct
24695 from an order of elaboration point of view. But the programmatic effects
24696 of the two orders are very different. In the first, the elaboration routine
24697 of @code{Calc} initializes @code{Z} to zero, and then the main program
24698 runs with this value of zero. But in the second order, the elaboration
24699 routine of @code{Calc} runs after the body of Init_Constants has set
24700 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24701 runs.
24703 One could perhaps by applying pretty clever non-artificial intelligence
24704 to the situation guess that it is more likely that the second order of
24705 elaboration is the one desired, but there is no formal linguistic reason
24706 to prefer one over the other. In fact in this particular case, GNAT will
24707 prefer the second order, because of the rule that bodies are elaborated
24708 as soon as possible, but it's just luck that this is what was wanted
24709 (if indeed the second order was preferred).
24711 If the program cares about the order of elaboration routines in a case like
24712 this, it is important to specify the order required. In this particular
24713 case, that could have been achieved by adding to the spec of Calc:
24715 @smallexample @c ada
24716 pragma Elaborate_All (Constants);
24717 @end smallexample
24719 @noindent
24720 which requires that the body (if any) and spec of @code{Constants},
24721 as well as the body and spec of any unit @code{with}'ed by
24722 @code{Constants} be elaborated before @code{Calc} is elaborated.
24724 Clearly no automatic method can always guess which alternative you require,
24725 and if you are working with legacy code that had constraints of this kind
24726 which were not properly specified by adding @code{Elaborate} or
24727 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24728 compilers can choose different orders.
24730 However, GNAT does attempt to diagnose the common situation where there
24731 are uninitialized variables in the visible part of a package spec, and the
24732 corresponding package body has an elaboration block that directly or
24733 indirectly initialized one or more of these variables. This is the situation
24734 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24735 a warning that suggests this addition if it detects this situation.
24737 The @code{gnatbind}
24738 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24739 out problems. This switch causes bodies to be elaborated as late as possible
24740 instead of as early as possible. In the example above, it would have forced
24741 the choice of the first elaboration order. If you get different results
24742 when using this switch, and particularly if one set of results is right,
24743 and one is wrong as far as you are concerned, it shows that you have some
24744 missing @code{Elaborate} pragmas. For the example above, we have the
24745 following output:
24747 @smallexample
24748 gnatmake -f -q main
24749 main
24751 gnatmake -f -q main -bargs -p
24752 main
24754 @end smallexample
24756 @noindent
24757 It is of course quite unlikely that both these results are correct, so
24758 it is up to you in a case like this to investigate the source of the
24759 difference, by looking at the two elaboration orders that are chosen,
24760 and figuring out which is correct, and then adding the necessary
24761 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24765 @c *******************************
24766 @node Conditional Compilation
24767 @appendix Conditional Compilation
24768 @c *******************************
24769 @cindex Conditional compilation
24771 @noindent
24772 It is often necessary to arrange for a single source program
24773 to serve multiple purposes, where it is compiled in different
24774 ways to achieve these different goals. Some examples of the
24775 need for this feature are
24777 @itemize @bullet
24778 @item  Adapting a program to a different hardware environment
24779 @item  Adapting a program to a different target architecture
24780 @item  Turning debugging features on and off
24781 @item  Arranging for a program to compile with different compilers
24782 @end itemize
24784 @noindent
24785 In C, or C++, the typical approach would be to use the preprocessor
24786 that is defined as part of the language. The Ada language does not
24787 contain such a feature. This is not an oversight, but rather a very
24788 deliberate design decision, based on the experience that overuse of
24789 the preprocessing features in C and C++ can result in programs that
24790 are extremely difficult to maintain. For example, if we have ten
24791 switches that can be on or off, this means that there are a thousand
24792 separate programs, any one of which might not even be syntactically
24793 correct, and even if syntactically correct, the resulting program
24794 might not work correctly. Testing all combinations can quickly become
24795 impossible.
24797 Nevertheless, the need to tailor programs certainly exists, and in
24798 this Appendix we will discuss how this can
24799 be achieved using Ada in general, and GNAT in particular.
24801 @menu
24802 * Use of Boolean Constants::
24803 * Debugging - A Special Case::
24804 * Conditionalizing Declarations::
24805 * Use of Alternative Implementations::
24806 * Preprocessing::
24807 @end menu
24809 @node Use of Boolean Constants
24810 @section Use of Boolean Constants
24812 @noindent
24813 In the case where the difference is simply which code
24814 sequence is executed, the cleanest solution is to use Boolean
24815 constants to control which code is executed.
24817 @smallexample @c ada
24818 @group
24819 FP_Initialize_Required : constant Boolean := True;
24820 @dots{}
24821 if FP_Initialize_Required then
24822 @dots{}
24823 end if;
24824 @end group
24825 @end smallexample
24827 @noindent
24828 Not only will the code inside the @code{if} statement not be executed if
24829 the constant Boolean is @code{False}, but it will also be completely
24830 deleted from the program.
24831 However, the code is only deleted after the @code{if} statement
24832 has been checked for syntactic and semantic correctness.
24833 (In contrast, with preprocessors the code is deleted before the
24834 compiler ever gets to see it, so it is not checked until the switch
24835 is turned on.)
24836 @cindex Preprocessors (contrasted with conditional compilation)
24838 Typically the Boolean constants will be in a separate package,
24839 something like:
24841 @smallexample @c ada
24842 @group
24843 package Config is
24844    FP_Initialize_Required : constant Boolean := True;
24845    Reset_Available        : constant Boolean := False;
24846    @dots{}
24847 end Config;
24848 @end group
24849 @end smallexample
24851 @noindent
24852 The @code{Config} package exists in multiple forms for the various targets,
24853 with an appropriate script selecting the version of @code{Config} needed.
24854 Then any other unit requiring conditional compilation can do a @code{with}
24855 of @code{Config} to make the constants visible.
24858 @node Debugging - A Special Case
24859 @section Debugging - A Special Case
24861 @noindent
24862 A common use of conditional code is to execute statements (for example
24863 dynamic checks, or output of intermediate results) under control of a
24864 debug switch, so that the debugging behavior can be turned on and off.
24865 This can be done using a Boolean constant to control whether the code
24866 is active:
24868 @smallexample @c ada
24869 @group
24870 if Debugging then
24871    Put_Line ("got to the first stage!");
24872 end if;
24873 @end group
24874 @end smallexample
24876 @noindent
24879 @smallexample @c ada
24880 @group
24881 if Debugging and then Temperature > 999.0 then
24882    raise Temperature_Crazy;
24883 end if;
24884 @end group
24885 @end smallexample
24887 @noindent
24888 Since this is a common case, there are special features to deal with
24889 this in a convenient manner. For the case of tests, Ada 2005 has added
24890 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24891 @cindex pragma @code{Assert}
24892 on the @code{Assert} pragma that has always been available in GNAT, so this
24893 feature may be used with GNAT even if you are not using Ada 2005 features.
24894 The use of pragma @code{Assert} is described in
24895 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24896 example, the last test could be written:
24898 @smallexample @c ada
24899 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24900 @end smallexample
24902 @noindent
24903 or simply
24905 @smallexample @c ada
24906 pragma Assert (Temperature <= 999.0);
24907 @end smallexample
24909 @noindent
24910 In both cases, if assertions are active and the temperature is excessive,
24911 the exception @code{Assert_Failure} will be raised, with the given string in
24912 the first case or a string indicating the location of the pragma in the second
24913 case used as the exception message.
24915 You can turn assertions on and off by using the @code{Assertion_Policy}
24916 pragma.
24917 @cindex pragma @code{Assertion_Policy}
24918 This is an Ada 2005 pragma which is implemented in all modes by
24919 GNAT, but only in the latest versions of GNAT which include Ada 2005
24920 capability. Alternatively, you can use the @option{-gnata} switch
24921 @cindex @option{-gnata} switch
24922 to enable assertions from the command line (this is recognized by all versions
24923 of GNAT).
24925 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24926 @code{Debug} can be used:
24927 @cindex pragma @code{Debug}
24929 @smallexample @c ada
24930 pragma Debug (Put_Line ("got to the first stage!"));
24931 @end smallexample
24933 @noindent
24934 If debug pragmas are enabled, the argument, which must be of the form of
24935 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24936 Only one call can be present, but of course a special debugging procedure
24937 containing any code you like can be included in the program and then
24938 called in a pragma @code{Debug} argument as needed.
24940 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24941 construct is that pragma @code{Debug} can appear in declarative contexts,
24942 such as at the very beginning of a procedure, before local declarations have
24943 been elaborated.
24945 Debug pragmas are enabled using either the @option{-gnata} switch that also
24946 controls assertions, or with a separate Debug_Policy pragma.
24947 @cindex pragma @code{Debug_Policy}
24948 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24949 in Ada 95 and Ada 83 programs as well), and is analogous to
24950 pragma @code{Assertion_Policy} to control assertions.
24952 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24953 and thus they can appear in @file{gnat.adc} if you are not using a
24954 project file, or in the file designated to contain configuration pragmas
24955 in a project file.
24956 They then apply to all subsequent compilations. In practice the use of
24957 the @option{-gnata} switch is often the most convenient method of controlling
24958 the status of these pragmas.
24960 Note that a pragma is not a statement, so in contexts where a statement
24961 sequence is required, you can't just write a pragma on its own. You have
24962 to add a @code{null} statement.
24964 @smallexample @c ada
24965 @group
24966 if @dots{} then
24967    @dots{} -- some statements
24968 else
24969    pragma Assert (Num_Cases < 10);
24970    null;
24971 end if;
24972 @end group
24973 @end smallexample
24976 @node Conditionalizing Declarations
24977 @section Conditionalizing Declarations
24979 @noindent
24980 In some cases, it may be necessary to conditionalize declarations to meet
24981 different requirements. For example we might want a bit string whose length
24982 is set to meet some hardware message requirement.
24984 In some cases, it may be possible to do this using declare blocks controlled
24985 by conditional constants:
24987 @smallexample @c ada
24988 @group
24989 if Small_Machine then
24990    declare
24991       X : Bit_String (1 .. 10);
24992    begin
24993       @dots{}
24994    end;
24995 else
24996    declare
24997       X : Large_Bit_String (1 .. 1000);
24998    begin
24999       @dots{}
25000    end;
25001 end if;
25002 @end group
25003 @end smallexample
25005 @noindent
25006 Note that in this approach, both declarations are analyzed by the
25007 compiler so this can only be used where both declarations are legal,
25008 even though one of them will not be used.
25010 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25011 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25012 that are parameterized by these constants. For example
25014 @smallexample @c ada
25015 @group
25016 for Rec use
25017   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25018 end record;
25019 @end group
25020 @end smallexample
25022 @noindent
25023 If @code{Bits_Per_Word} is set to 32, this generates either
25025 @smallexample @c ada
25026 @group
25027 for Rec use
25028   Field1 at 0 range 0 .. 32;
25029 end record;
25030 @end group
25031 @end smallexample
25033 @noindent
25034 for the big endian case, or
25036 @smallexample @c ada
25037 @group
25038 for Rec use record
25039   Field1 at 0 range 10 .. 32;
25040 end record;
25041 @end group
25042 @end smallexample
25044 @noindent
25045 for the little endian case. Since a powerful subset of Ada expression
25046 notation is usable for creating static constants, clever use of this
25047 feature can often solve quite difficult problems in conditionalizing
25048 compilation (note incidentally that in Ada 95, the little endian
25049 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25050 need to define this one yourself).
25053 @node Use of Alternative Implementations
25054 @section Use of Alternative Implementations
25056 @noindent
25057 In some cases, none of the approaches described above are adequate. This
25058 can occur for example if the set of declarations required is radically
25059 different for two different configurations.
25061 In this situation, the official Ada way of dealing with conditionalizing
25062 such code is to write separate units for the different cases. As long as
25063 this does not result in excessive duplication of code, this can be done
25064 without creating maintenance problems. The approach is to share common
25065 code as far as possible, and then isolate the code and declarations
25066 that are different. Subunits are often a convenient method for breaking
25067 out a piece of a unit that is to be conditionalized, with separate files
25068 for different versions of the subunit for different targets, where the
25069 build script selects the right one to give to the compiler.
25070 @cindex Subunits (and conditional compilation)
25072 As an example, consider a situation where a new feature in Ada 2005
25073 allows something to be done in a really nice way. But your code must be able
25074 to compile with an Ada 95 compiler. Conceptually you want to say:
25076 @smallexample @c ada
25077 @group
25078 if Ada_2005 then
25079    @dots{} neat Ada 2005 code
25080 else
25081    @dots{} not quite as neat Ada 95 code
25082 end if;
25083 @end group
25084 @end smallexample
25086 @noindent
25087 where @code{Ada_2005} is a Boolean constant.
25089 But this won't work when @code{Ada_2005} is set to @code{False},
25090 since the @code{then} clause will be illegal for an Ada 95 compiler.
25091 (Recall that although such unreachable code would eventually be deleted
25092 by the compiler, it still needs to be legal.  If it uses features
25093 introduced in Ada 2005, it will be illegal in Ada 95.)
25095 So instead we write
25097 @smallexample @c ada
25098 procedure Insert is separate;
25099 @end smallexample
25101 @noindent
25102 Then we have two files for the subunit @code{Insert}, with the two sets of
25103 code.
25104 If the package containing this is called @code{File_Queries}, then we might
25105 have two files
25107 @itemize @bullet
25108 @item    @file{file_queries-insert-2005.adb}
25109 @item    @file{file_queries-insert-95.adb}
25110 @end itemize
25112 @noindent
25113 and the build script renames the appropriate file to
25115 @smallexample
25116 file_queries-insert.adb
25117 @end smallexample
25119 @noindent
25120 and then carries out the compilation.
25122 This can also be done with project files' naming schemes. For example:
25124 @smallexample @c project
25125 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25126 @end smallexample
25128 @noindent
25129 Note also that with project files it is desirable to use a different extension
25130 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25131 conflict may arise through another commonly used feature: to declare as part
25132 of the project a set of directories containing all the sources obeying the
25133 default naming scheme.
25135 The use of alternative units is certainly feasible in all situations,
25136 and for example the Ada part of the GNAT run-time is conditionalized
25137 based on the target architecture using this approach. As a specific example,
25138 consider the implementation of the AST feature in VMS. There is one
25139 spec:
25141 @smallexample
25142 s-asthan.ads
25143 @end smallexample
25145 @noindent
25146 which is the same for all architectures, and three bodies:
25148 @table @file
25149 @item    s-asthan.adb
25150 used for all non-VMS operating systems
25151 @item    s-asthan-vms-alpha.adb
25152 used for VMS on the Alpha
25153 @item    s-asthan-vms-ia64.adb
25154 used for VMS on the ia64
25155 @end table
25157 @noindent
25158 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25159 this operating system feature is not available, and the two remaining
25160 versions interface with the corresponding versions of VMS to provide
25161 VMS-compatible AST handling. The GNAT build script knows the architecture
25162 and operating system, and automatically selects the right version,
25163 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25165 Another style for arranging alternative implementations is through Ada's
25166 access-to-subprogram facility.
25167 In case some functionality is to be conditionally included,
25168 you can declare an access-to-procedure variable @code{Ref} that is initialized
25169 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25170 when appropriate.
25171 In some library package, set @code{Ref} to @code{Proc'Access} for some
25172 procedure @code{Proc} that performs the relevant processing.
25173 The initialization only occurs if the library package is included in the
25174 program.
25175 The same idea can also be implemented using tagged types and dispatching
25176 calls.
25179 @node Preprocessing
25180 @section Preprocessing
25181 @cindex Preprocessing
25183 @noindent
25184 Although it is quite possible to conditionalize code without the use of
25185 C-style preprocessing, as described earlier in this section, it is
25186 nevertheless convenient in some cases to use the C approach. Moreover,
25187 older Ada compilers have often provided some preprocessing capability,
25188 so legacy code may depend on this approach, even though it is not
25189 standard.
25191 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25192 extent on the various preprocessors that have been used
25193 with legacy code on other compilers, to enable easier transition).
25195 The preprocessor may be used in two separate modes. It can be used quite
25196 separately from the compiler, to generate a separate output source file
25197 that is then fed to the compiler as a separate step. This is the
25198 @code{gnatprep} utility, whose use is fully described in
25199 @ref{Preprocessing Using gnatprep}.
25200 @cindex @code{gnatprep}
25202 The preprocessing language allows such constructs as
25204 @smallexample
25205 @group
25206 #if DEBUG or PRIORITY > 4 then
25207    bunch of declarations
25208 #else
25209    completely different bunch of declarations
25210 #end if;
25211 @end group
25212 @end smallexample
25214 @noindent
25215 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25216 defined either on the command line or in a separate file.
25218 The other way of running the preprocessor is even closer to the C style and
25219 often more convenient. In this approach the preprocessing is integrated into
25220 the compilation process. The compiler is fed the preprocessor input which
25221 includes @code{#if} lines etc, and then the compiler carries out the
25222 preprocessing internally and processes the resulting output.
25223 For more details on this approach, see @ref{Integrated Preprocessing}.
25226 @c *******************************
25227 @node Inline Assembler
25228 @appendix Inline Assembler
25229 @c *******************************
25231 @noindent
25232 If you need to write low-level software that interacts directly
25233 with the hardware, Ada provides two ways to incorporate assembly
25234 language code into your program.  First, you can import and invoke
25235 external routines written in assembly language, an Ada feature fully
25236 supported by GNAT@.  However, for small sections of code it may be simpler
25237 or more efficient to include assembly language statements directly
25238 in your Ada source program, using the facilities of the implementation-defined
25239 package @code{System.Machine_Code}, which incorporates the gcc
25240 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25241 including the following:
25243 @itemize @bullet
25244 @item No need to use non-Ada tools
25245 @item Consistent interface over different targets
25246 @item Automatic usage of the proper calling conventions
25247 @item Access to Ada constants and variables
25248 @item Definition of intrinsic routines
25249 @item Possibility of inlining a subprogram comprising assembler code
25250 @item Code optimizer can take Inline Assembler code into account
25251 @end itemize
25253 This chapter presents a series of examples to show you how to use
25254 the Inline Assembler.  Although it focuses on the Intel x86,
25255 the general approach applies also to other processors.
25256 It is assumed that you are familiar with Ada
25257 and with assembly language programming.
25259 @menu
25260 * Basic Assembler Syntax::
25261 * A Simple Example of Inline Assembler::
25262 * Output Variables in Inline Assembler::
25263 * Input Variables in Inline Assembler::
25264 * Inlining Inline Assembler Code::
25265 * Other Asm Functionality::
25266 @end menu
25268 @c ---------------------------------------------------------------------------
25269 @node Basic Assembler Syntax
25270 @section Basic Assembler Syntax
25272 @noindent
25273 The assembler used by GNAT and gcc is based not on the Intel assembly
25274 language, but rather on a language that descends from the AT&T Unix
25275 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25276 The following table summarizes the main features of @emph{as} syntax
25277 and points out the differences from the Intel conventions.
25278 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25279 pre-processor) documentation for further information.
25281 @table @asis
25282 @item Register names
25283 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25285 Intel: No extra punctuation; for example @code{eax}
25287 @item Immediate operand
25288 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25290 Intel: No extra punctuation; for example @code{4}
25292 @item Address
25293 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25295 Intel: No extra punctuation; for example @code{loc}
25297 @item Memory contents
25298 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25300 Intel: Square brackets; for example @code{[loc]}
25302 @item Register contents
25303 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25305 Intel: Square brackets; for example @code{[eax]}
25307 @item Hexadecimal numbers
25308 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25310 Intel: Trailing ``h''; for example @code{A0h}
25312 @item Operand size
25313 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25314 a 16-bit word
25316 Intel: Implicit, deduced by assembler; for example @code{mov}
25318 @item Instruction repetition
25319 gcc / @emph{as}: Split into two lines; for example
25321 @code{rep}
25323 @code{stosl}
25325 Intel: Keep on one line; for example @code{rep stosl}
25327 @item Order of operands
25328 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25330 Intel: Destination first; for example @code{mov eax, 4}
25331 @end table
25333 @c ---------------------------------------------------------------------------
25334 @node A Simple Example of Inline Assembler
25335 @section A Simple Example of Inline Assembler
25337 @noindent
25338 The following example will generate a single assembly language statement,
25339 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25340 the example will be useful in illustrating the basics of
25341 the Inline Assembler facility.
25343 @smallexample @c ada
25344 @group
25345 with System.Machine_Code; use System.Machine_Code;
25346 procedure Nothing is
25347 begin
25348    Asm ("nop");
25349 end Nothing;
25350 @end group
25351 @end smallexample
25353 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25354 here it takes one parameter, a @emph{template string} that must be a static
25355 expression and that will form the generated instruction.
25356 @code{Asm} may be regarded as a compile-time procedure that parses
25357 the template string and additional parameters (none here),
25358 from which it generates a sequence of assembly language instructions.
25360 The examples in this chapter will illustrate several of the forms
25361 for invoking @code{Asm}; a complete specification of the syntax
25362 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25363 Manual}.
25365 Under the standard GNAT conventions, the @code{Nothing} procedure
25366 should be in a file named @file{nothing.adb}.
25367 You can build the executable in the usual way:
25368 @smallexample
25369 gnatmake nothing
25370 @end smallexample
25371 However, the interesting aspect of this example is not its run-time behavior
25372 but rather the generated assembly code.
25373 To see this output, invoke the compiler as follows:
25374 @smallexample
25375    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25376 @end smallexample
25377 where the options are:
25379 @table @code
25380 @item -c
25381 compile only (no bind or link)
25382 @item -S
25383 generate assembler listing
25384 @item -fomit-frame-pointer
25385 do not set up separate stack frames
25386 @item -gnatp
25387 do not add runtime checks
25388 @end table
25390 This gives a human-readable assembler version of the code. The resulting
25391 file will have the same name as the Ada source file, but with a @code{.s}
25392 extension. In our example, the file @file{nothing.s} has the following
25393 contents:
25395 @smallexample
25396 @group
25397 .file "nothing.adb"
25398 gcc2_compiled.:
25399 ___gnu_compiled_ada:
25400 .text
25401    .align 4
25402 .globl __ada_nothing
25403 __ada_nothing:
25404 #APP
25405    nop
25406 #NO_APP
25407    jmp L1
25408    .align 2,0x90
25410    ret
25411 @end group
25412 @end smallexample
25414 The assembly code you included is clearly indicated by
25415 the compiler, between the @code{#APP} and @code{#NO_APP}
25416 delimiters. The character before the 'APP' and 'NOAPP'
25417 can differ on different targets. For example, GNU/Linux uses '#APP' while
25418 on NT you will see '/APP'.
25420 If you make a mistake in your assembler code (such as using the
25421 wrong size modifier, or using a wrong operand for the instruction) GNAT
25422 will report this error in a temporary file, which will be deleted when
25423 the compilation is finished.  Generating an assembler file will help
25424 in such cases, since you can assemble this file separately using the
25425 @emph{as} assembler that comes with gcc.
25427 Assembling the file using the command
25429 @smallexample
25430 as @file{nothing.s}
25431 @end smallexample
25432 @noindent
25433 will give you error messages whose lines correspond to the assembler
25434 input file, so you can easily find and correct any mistakes you made.
25435 If there are no errors, @emph{as} will generate an object file
25436 @file{nothing.out}.
25438 @c ---------------------------------------------------------------------------
25439 @node Output Variables in Inline Assembler
25440 @section Output Variables in Inline Assembler
25442 @noindent
25443 The examples in this section, showing how to access the processor flags,
25444 illustrate how to specify the destination operands for assembly language
25445 statements.
25447 @smallexample @c ada
25448 @group
25449 with Interfaces; use Interfaces;
25450 with Ada.Text_IO; use Ada.Text_IO;
25451 with System.Machine_Code; use System.Machine_Code;
25452 procedure Get_Flags is
25453    Flags : Unsigned_32;
25454    use ASCII;
25455 begin
25456    Asm ("pushfl"          & LF & HT & -- push flags on stack
25457         "popl %%eax"      & LF & HT & -- load eax with flags
25458         "movl %%eax, %0",             -- store flags in variable
25459         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25460    Put_Line ("Flags register:" & Flags'Img);
25461 end Get_Flags;
25462 @end group
25463 @end smallexample
25465 In order to have a nicely aligned assembly listing, we have separated
25466 multiple assembler statements in the Asm template string with linefeed
25467 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25468 The resulting section of the assembly output file is:
25470 @smallexample
25471 @group
25472 #APP
25473    pushfl
25474    popl %eax
25475    movl %eax, -40(%ebp)
25476 #NO_APP
25477 @end group
25478 @end smallexample
25480 It would have been legal to write the Asm invocation as:
25482 @smallexample
25483 Asm ("pushfl popl %%eax movl %%eax, %0")
25484 @end smallexample
25486 but in the generated assembler file, this would come out as:
25488 @smallexample
25489 #APP
25490    pushfl popl %eax movl %eax, -40(%ebp)
25491 #NO_APP
25492 @end smallexample
25494 which is not so convenient for the human reader.
25496 We use Ada comments
25497 at the end of each line to explain what the assembler instructions
25498 actually do.  This is a useful convention.
25500 When writing Inline Assembler instructions, you need to precede each register
25501 and variable name with a percent sign.  Since the assembler already requires
25502 a percent sign at the beginning of a register name, you need two consecutive
25503 percent signs for such names in the Asm template string, thus @code{%%eax}.
25504 In the generated assembly code, one of the percent signs will be stripped off.
25506 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25507 variables: operands you later define using @code{Input} or @code{Output}
25508 parameters to @code{Asm}.
25509 An output variable is illustrated in
25510 the third statement in the Asm template string:
25511 @smallexample
25512 movl %%eax, %0
25513 @end smallexample
25514 The intent is to store the contents of the eax register in a variable that can
25515 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25516 necessarily work, since the compiler might optimize by using a register
25517 to hold Flags, and the expansion of the @code{movl} instruction would not be
25518 aware of this optimization.  The solution is not to store the result directly
25519 but rather to advise the compiler to choose the correct operand form;
25520 that is the purpose of the @code{%0} output variable.
25522 Information about the output variable is supplied in the @code{Outputs}
25523 parameter to @code{Asm}:
25524 @smallexample
25525 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25526 @end smallexample
25528 The output is defined by the @code{Asm_Output} attribute of the target type;
25529 the general format is
25530 @smallexample
25531 Type'Asm_Output (constraint_string, variable_name)
25532 @end smallexample
25534 The constraint string directs the compiler how
25535 to store/access the associated variable.  In the example
25536 @smallexample
25537 Unsigned_32'Asm_Output ("=m", Flags);
25538 @end smallexample
25539 the @code{"m"} (memory) constraint tells the compiler that the variable
25540 @code{Flags} should be stored in a memory variable, thus preventing
25541 the optimizer from keeping it in a register.  In contrast,
25542 @smallexample
25543 Unsigned_32'Asm_Output ("=r", Flags);
25544 @end smallexample
25545 uses the @code{"r"} (register) constraint, telling the compiler to
25546 store the variable in a register.
25548 If the constraint is preceded by the equal character (@strong{=}), it tells
25549 the compiler that the variable will be used to store data into it.
25551 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25552 allowing the optimizer to choose whatever it deems best.
25554 There are a fairly large number of constraints, but the ones that are
25555 most useful (for the Intel x86 processor) are the following:
25557 @table @code
25558 @item =
25559 output constraint
25560 @item g
25561 global (i.e.@: can be stored anywhere)
25562 @item m
25563 in memory
25564 @item I
25565 a constant
25566 @item a
25567 use eax
25568 @item b
25569 use ebx
25570 @item c
25571 use ecx
25572 @item d
25573 use edx
25574 @item S
25575 use esi
25576 @item D
25577 use edi
25578 @item r
25579 use one of eax, ebx, ecx or edx
25580 @item q
25581 use one of eax, ebx, ecx, edx, esi or edi
25582 @end table
25584 The full set of constraints is described in the gcc and @emph{as}
25585 documentation; note that it is possible to combine certain constraints
25586 in one constraint string.
25588 You specify the association of an output variable with an assembler operand
25589 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25590 integer.  Thus in
25591 @smallexample @c ada
25592 @group
25593 Asm ("pushfl"          & LF & HT & -- push flags on stack
25594      "popl %%eax"      & LF & HT & -- load eax with flags
25595      "movl %%eax, %0",             -- store flags in variable
25596      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25597 @end group
25598 @end smallexample
25599 @noindent
25600 @code{%0} will be replaced in the expanded code by the appropriate operand,
25601 whatever
25602 the compiler decided for the @code{Flags} variable.
25604 In general, you may have any number of output variables:
25605 @itemize @bullet
25606 @item
25607 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25608 @item
25609 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25610 of @code{Asm_Output} attributes
25611 @end itemize
25613 For example:
25614 @smallexample @c ada
25615 @group
25616 Asm ("movl %%eax, %0" & LF & HT &
25617      "movl %%ebx, %1" & LF & HT &
25618      "movl %%ecx, %2",
25619      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25620                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25621                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25622 @end group
25623 @end smallexample
25624 @noindent
25625 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25626 in the Ada program.
25628 As a variation on the @code{Get_Flags} example, we can use the constraints
25629 string to direct the compiler to store the eax register into the @code{Flags}
25630 variable, instead of including the store instruction explicitly in the
25631 @code{Asm} template string:
25633 @smallexample @c ada
25634 @group
25635 with Interfaces; use Interfaces;
25636 with Ada.Text_IO; use Ada.Text_IO;
25637 with System.Machine_Code; use System.Machine_Code;
25638 procedure Get_Flags_2 is
25639    Flags : Unsigned_32;
25640    use ASCII;
25641 begin
25642    Asm ("pushfl"      & LF & HT & -- push flags on stack
25643         "popl %%eax",             -- save flags in eax
25644         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25645    Put_Line ("Flags register:" & Flags'Img);
25646 end Get_Flags_2;
25647 @end group
25648 @end smallexample
25650 @noindent
25651 The @code{"a"} constraint tells the compiler that the @code{Flags}
25652 variable will come from the eax register. Here is the resulting code:
25654 @smallexample
25655 @group
25656 #APP
25657    pushfl
25658    popl %eax
25659 #NO_APP
25660    movl %eax,-40(%ebp)
25661 @end group
25662 @end smallexample
25664 @noindent
25665 The compiler generated the store of eax into Flags after
25666 expanding the assembler code.
25668 Actually, there was no need to pop the flags into the eax register;
25669 more simply, we could just pop the flags directly into the program variable:
25671 @smallexample @c ada
25672 @group
25673 with Interfaces; use Interfaces;
25674 with Ada.Text_IO; use Ada.Text_IO;
25675 with System.Machine_Code; use System.Machine_Code;
25676 procedure Get_Flags_3 is
25677    Flags : Unsigned_32;
25678    use ASCII;
25679 begin
25680    Asm ("pushfl"  & LF & HT & -- push flags on stack
25681         "pop %0",             -- save flags in Flags
25682         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25683    Put_Line ("Flags register:" & Flags'Img);
25684 end Get_Flags_3;
25685 @end group
25686 @end smallexample
25688 @c ---------------------------------------------------------------------------
25689 @node Input Variables in Inline Assembler
25690 @section Input Variables in Inline Assembler
25692 @noindent
25693 The example in this section illustrates how to specify the source operands
25694 for assembly language statements.
25695 The program simply increments its input value by 1:
25697 @smallexample @c ada
25698 @group
25699 with Interfaces; use Interfaces;
25700 with Ada.Text_IO; use Ada.Text_IO;
25701 with System.Machine_Code; use System.Machine_Code;
25702 procedure Increment is
25704    function Incr (Value : Unsigned_32) return Unsigned_32 is
25705       Result : Unsigned_32;
25706    begin
25707       Asm ("incl %0",
25708            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25709            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25710       return Result;
25711    end Incr;
25713    Value : Unsigned_32;
25715 begin
25716    Value := 5;
25717    Put_Line ("Value before is" & Value'Img);
25718    Value := Incr (Value);
25719    Put_Line ("Value after is" & Value'Img);
25720 end Increment;
25721 @end group
25722 @end smallexample
25724 The @code{Outputs} parameter to @code{Asm} specifies
25725 that the result will be in the eax register and that it is to be stored
25726 in the @code{Result} variable.
25728 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25729 but with an @code{Asm_Input} attribute.
25730 The @code{"="} constraint, indicating an output value, is not present.
25732 You can have multiple input variables, in the same way that you can have more
25733 than one output variable.
25735 The parameter count (%0, %1) etc, now starts at the first input
25736 statement, and continues with the output statements.
25737 When both parameters use the same variable, the
25738 compiler will treat them as the same %n operand, which is the case here.
25740 Just as the @code{Outputs} parameter causes the register to be stored into the
25741 target variable after execution of the assembler statements, so does the
25742 @code{Inputs} parameter cause its variable to be loaded into the register
25743 before execution of the assembler statements.
25745 Thus the effect of the @code{Asm} invocation is:
25746 @enumerate
25747 @item load the 32-bit value of @code{Value} into eax
25748 @item execute the @code{incl %eax} instruction
25749 @item store the contents of eax into the @code{Result} variable
25750 @end enumerate
25752 The resulting assembler file (with @option{-O2} optimization) contains:
25753 @smallexample
25754 @group
25755 _increment__incr.1:
25756    subl $4,%esp
25757    movl 8(%esp),%eax
25758 #APP
25759    incl %eax
25760 #NO_APP
25761    movl %eax,%edx
25762    movl %ecx,(%esp)
25763    addl $4,%esp
25764    ret
25765 @end group
25766 @end smallexample
25768 @c ---------------------------------------------------------------------------
25769 @node Inlining Inline Assembler Code
25770 @section Inlining Inline Assembler Code
25772 @noindent
25773 For a short subprogram such as the @code{Incr} function in the previous
25774 section, the overhead of the call and return (creating / deleting the stack
25775 frame) can be significant, compared to the amount of code in the subprogram
25776 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25777 which directs the compiler to expand invocations of the subprogram at the
25778 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25779 Here is the resulting program:
25781 @smallexample @c ada
25782 @group
25783 with Interfaces; use Interfaces;
25784 with Ada.Text_IO; use Ada.Text_IO;
25785 with System.Machine_Code; use System.Machine_Code;
25786 procedure Increment_2 is
25788    function Incr (Value : Unsigned_32) return Unsigned_32 is
25789       Result : Unsigned_32;
25790    begin
25791       Asm ("incl %0",
25792            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25793            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25794       return Result;
25795    end Incr;
25796    pragma Inline (Increment);
25798    Value : Unsigned_32;
25800 begin
25801    Value := 5;
25802    Put_Line ("Value before is" & Value'Img);
25803    Value := Increment (Value);
25804    Put_Line ("Value after is" & Value'Img);
25805 end Increment_2;
25806 @end group
25807 @end smallexample
25809 Compile the program with both optimization (@option{-O2}) and inlining
25810 (@option{-gnatn}) enabled.
25812 The @code{Incr} function is still compiled as usual, but at the
25813 point in @code{Increment} where our function used to be called:
25815 @smallexample
25816 @group
25817 pushl %edi
25818 call _increment__incr.1
25819 @end group
25820 @end smallexample
25822 @noindent
25823 the code for the function body directly appears:
25825 @smallexample
25826 @group
25827 movl %esi,%eax
25828 #APP
25829    incl %eax
25830 #NO_APP
25831    movl %eax,%edx
25832 @end group
25833 @end smallexample
25835 @noindent
25836 thus saving the overhead of stack frame setup and an out-of-line call.
25838 @c ---------------------------------------------------------------------------
25839 @node Other Asm Functionality
25840 @section Other @code{Asm} Functionality
25842 @noindent
25843 This section describes two important parameters to the @code{Asm}
25844 procedure: @code{Clobber}, which identifies register usage;
25845 and @code{Volatile}, which inhibits unwanted optimizations.
25847 @menu
25848 * The Clobber Parameter::
25849 * The Volatile Parameter::
25850 @end menu
25852 @c ---------------------------------------------------------------------------
25853 @node The Clobber Parameter
25854 @subsection The @code{Clobber} Parameter
25856 @noindent
25857 One of the dangers of intermixing assembly language and a compiled language
25858 such as Ada is that the compiler needs to be aware of which registers are
25859 being used by the assembly code.  In some cases, such as the earlier examples,
25860 the constraint string is sufficient to indicate register usage (e.g.,
25861 @code{"a"} for
25862 the eax register).  But more generally, the compiler needs an explicit
25863 identification of the registers that are used by the Inline Assembly
25864 statements.
25866 Using a register that the compiler doesn't know about
25867 could be a side effect of an instruction (like @code{mull}
25868 storing its result in both eax and edx).
25869 It can also arise from explicit register usage in your
25870 assembly code; for example:
25871 @smallexample
25872 @group
25873 Asm ("movl %0, %%ebx" & LF & HT &
25874      "movl %%ebx, %1",
25875      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25876      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25877 @end group
25878 @end smallexample
25879 @noindent
25880 where the compiler (since it does not analyze the @code{Asm} template string)
25881 does not know you are using the ebx register.
25883 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25884 to identify the registers that will be used by your assembly code:
25886 @smallexample
25887 @group
25888 Asm ("movl %0, %%ebx" & LF & HT &
25889      "movl %%ebx, %1",
25890      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25891      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25892      Clobber => "ebx");
25893 @end group
25894 @end smallexample
25896 The Clobber parameter is a static string expression specifying the
25897 register(s) you are using.  Note that register names are @emph{not} prefixed
25898 by a percent sign. Also, if more than one register is used then their names
25899 are separated by commas; e.g., @code{"eax, ebx"}
25901 The @code{Clobber} parameter has several additional uses:
25902 @enumerate
25903 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25904 @item Use ``register'' name @code{memory} if you changed a memory location
25905 @end enumerate
25907 @c ---------------------------------------------------------------------------
25908 @node The Volatile Parameter
25909 @subsection The @code{Volatile} Parameter
25910 @cindex Volatile parameter
25912 @noindent
25913 Compiler optimizations in the presence of Inline Assembler may sometimes have
25914 unwanted effects.  For example, when an @code{Asm} invocation with an input
25915 variable is inside a loop, the compiler might move the loading of the input
25916 variable outside the loop, regarding it as a one-time initialization.
25918 If this effect is not desired, you can disable such optimizations by setting
25919 the @code{Volatile} parameter to @code{True}; for example:
25921 @smallexample @c ada
25922 @group
25923 Asm ("movl %0, %%ebx" & LF & HT &
25924      "movl %%ebx, %1",
25925      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25926      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25927      Clobber  => "ebx",
25928      Volatile => True);
25929 @end group
25930 @end smallexample
25932 By default, @code{Volatile} is set to @code{False} unless there is no
25933 @code{Outputs} parameter.
25935 Although setting @code{Volatile} to @code{True} prevents unwanted
25936 optimizations, it will also disable other optimizations that might be
25937 important for efficiency. In general, you should set @code{Volatile}
25938 to @code{True} only if the compiler's optimizations have created
25939 problems.
25940 @c END OF INLINE ASSEMBLER CHAPTER
25941 @c ===============================
25943 @c ***********************************
25944 @c * Compatibility and Porting Guide *
25945 @c ***********************************
25946 @node Compatibility and Porting Guide
25947 @appendix Compatibility and Porting Guide
25949 @noindent
25950 This chapter describes the compatibility issues that may arise between
25951 GNAT and other Ada compilation systems (including those for Ada 83),
25952 and shows how GNAT can expedite porting
25953 applications developed in other Ada environments.
25955 @menu
25956 * Compatibility with Ada 83::
25957 * Compatibility between Ada 95 and Ada 2005::
25958 * Implementation-dependent characteristics::
25959 * Compatibility with Other Ada Systems::
25960 * Representation Clauses::
25961 @ifclear vms
25962 @c Brief section is only in non-VMS version
25963 @c Full chapter is in VMS version
25964 * Compatibility with HP Ada 83::
25965 @end ifclear
25966 @ifset vms
25967 * Transitioning to 64-Bit GNAT for OpenVMS::
25968 @end ifset
25969 @end menu
25971 @node Compatibility with Ada 83
25972 @section Compatibility with Ada 83
25973 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25975 @noindent
25976 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
25977 particular, the design intention was that the difficulties associated
25978 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25979 that occur when moving from one Ada 83 system to another.
25981 However, there are a number of points at which there are minor
25982 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25983 full details of these issues,
25984 and should be consulted for a complete treatment.
25985 In practice the
25986 following subsections treat the most likely issues to be encountered.
25988 @menu
25989 * Legal Ada 83 programs that are illegal in Ada 95::
25990 * More deterministic semantics::
25991 * Changed semantics::
25992 * Other language compatibility issues::
25993 @end menu
25995 @node Legal Ada 83 programs that are illegal in Ada 95
25996 @subsection Legal Ada 83 programs that are illegal in Ada 95
25998 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25999 Ada 95 and thus also in Ada 2005:
26001 @table @emph
26002 @item Character literals
26003 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26004 @code{Wide_Character} as a new predefined character type, some uses of
26005 character literals that were legal in Ada 83 are illegal in Ada 95.
26006 For example:
26007 @smallexample @c ada
26008    for Char in 'A' .. 'Z' loop @dots{} end loop;
26009 @end smallexample
26011 @noindent
26012 The problem is that @code{'A'} and @code{'Z'} could be from either
26013 @code{Character} or @code{Wide_Character}.  The simplest correction
26014 is to make the type explicit; e.g.:
26015 @smallexample @c ada
26016    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
26017 @end smallexample
26019 @item New reserved words
26020 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26021 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26022 Existing Ada 83 code using any of these identifiers must be edited to
26023 use some alternative name.
26025 @item Freezing rules
26026 The rules in Ada 95 are slightly different with regard to the point at
26027 which entities are frozen, and representation pragmas and clauses are
26028 not permitted past the freeze point.  This shows up most typically in
26029 the form of an error message complaining that a representation item
26030 appears too late, and the appropriate corrective action is to move
26031 the item nearer to the declaration of the entity to which it refers.
26033 A particular case is that representation pragmas
26034 @ifset vms
26035 (including the
26036 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26037 @end ifset
26038 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26039 declaration must be introduced to which the pragma can be applied.
26041 @item Optional bodies for library packages
26042 In Ada 83, a package that did not require a package body was nevertheless
26043 allowed to have one.  This lead to certain surprises in compiling large
26044 systems (situations in which the body could be unexpectedly ignored by the
26045 binder).  In Ada 95, if a package does not require a body then it is not
26046 permitted to have a body.  To fix this problem, simply remove a redundant
26047 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26048 into the spec that makes the body required.  One approach is to add a private
26049 part to the package declaration (if necessary), and define a parameterless
26050 procedure called @code{Requires_Body}, which must then be given a dummy
26051 procedure body in the package body, which then becomes required.
26052 Another approach (assuming that this does not introduce elaboration
26053 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26054 since one effect of this pragma is to require the presence of a package body.
26056 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26057 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26058 @code{Constraint_Error}.
26059 This means that it is illegal to have separate exception handlers for
26060 the two exceptions.  The fix is simply to remove the handler for the
26061 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26062 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26064 @item Indefinite subtypes in generics
26065 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26066 as the actual for a generic formal private type, but then the instantiation
26067 would be illegal if there were any instances of declarations of variables
26068 of this type in the generic body.  In Ada 95, to avoid this clear violation
26069 of the methodological principle known as the ``contract model'',
26070 the generic declaration explicitly indicates whether
26071 or not such instantiations are permitted.  If a generic formal parameter
26072 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26073 type name, then it can be instantiated with indefinite types, but no
26074 stand-alone variables can be declared of this type.  Any attempt to declare
26075 such a variable will result in an illegality at the time the generic is
26076 declared.  If the @code{(<>)} notation is not used, then it is illegal
26077 to instantiate the generic with an indefinite type.
26078 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26079 It will show up as a compile time error, and
26080 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26081 @end table
26083 @node More deterministic semantics
26084 @subsection More deterministic semantics
26086 @table @emph
26087 @item Conversions
26088 Conversions from real types to integer types round away from 0.  In Ada 83
26089 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26090 implementation freedom was intended to support unbiased rounding in
26091 statistical applications, but in practice it interfered with portability.
26092 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26093 is required.  Numeric code may be affected by this change in semantics.
26094 Note, though, that this issue is no worse than already existed in Ada 83
26095 when porting code from one vendor to another.
26097 @item Tasking
26098 The Real-Time Annex introduces a set of policies that define the behavior of
26099 features that were implementation dependent in Ada 83, such as the order in
26100 which open select branches are executed.
26101 @end table
26103 @node Changed semantics
26104 @subsection Changed semantics
26106 @noindent
26107 The worst kind of incompatibility is one where a program that is legal in
26108 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26109 possible in Ada 83.  Fortunately this is extremely rare, but the one
26110 situation that you should be alert to is the change in the predefined type
26111 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26113 @table @emph
26114 @item Range of type @code{Character}
26115 The range of @code{Standard.Character} is now the full 256 characters
26116 of Latin-1, whereas in most Ada 83 implementations it was restricted
26117 to 128 characters. Although some of the effects of
26118 this change will be manifest in compile-time rejection of legal
26119 Ada 83 programs it is possible for a working Ada 83 program to have
26120 a different effect in Ada 95, one that was not permitted in Ada 83.
26121 As an example, the expression
26122 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26123 delivers @code{255} as its value.
26124 In general, you should look at the logic of any
26125 character-processing Ada 83 program and see whether it needs to be adapted
26126 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26127 character handling package that may be relevant if code needs to be adapted
26128 to account for the additional Latin-1 elements.
26129 The desirable fix is to
26130 modify the program to accommodate the full character set, but in some cases
26131 it may be convenient to define a subtype or derived type of Character that
26132 covers only the restricted range.
26133 @cindex Latin-1
26134 @end table
26136 @node Other language compatibility issues
26137 @subsection Other language compatibility issues
26139 @table @emph
26140 @item @option{-gnat83} switch
26141 All implementations of GNAT provide a switch that causes GNAT to operate
26142 in Ada 83 mode.  In this mode, some but not all compatibility problems
26143 of the type described above are handled automatically.  For example, the
26144 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26145 as identifiers as in Ada 83.
26146 However,
26147 in practice, it is usually advisable to make the necessary modifications
26148 to the program to remove the need for using this switch.
26149 See @ref{Compiling Different Versions of Ada}.
26151 @item Support for removed Ada 83 pragmas and attributes
26152 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26153 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26154 compilers are allowed, but not required, to implement these missing
26155 elements.  In contrast with some other compilers, GNAT implements all
26156 such pragmas and attributes, eliminating this compatibility concern.  These
26157 include @code{pragma Interface} and the floating point type attributes
26158 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26159 @end table
26162 @node Compatibility between Ada 95 and Ada 2005
26163 @section Compatibility between Ada 95 and Ada 2005
26164 @cindex Compatibility between Ada 95 and Ada 2005
26166 @noindent
26167 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26168 a number of incompatibilities. Several are enumerated below;
26169 for a complete description please see the
26170 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26171 @cite{Rationale for Ada 2005}.
26173 @table @emph
26174 @item New reserved words.
26175 The words @code{interface}, @code{overriding} and @code{synchronized} are
26176 reserved in Ada 2005.
26177 A pre-Ada 2005 program that uses any of these as an identifier will be
26178 illegal.
26180 @item New declarations in predefined packages.
26181 A number of packages in the predefined environment contain new declarations:
26182 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26183 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26184 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26185 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26186 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26187 If an Ada 95 program does a @code{with} and @code{use} of any of these
26188 packages, the new declarations may cause name clashes.
26190 @item Access parameters.
26191 A nondispatching subprogram with an access parameter cannot be renamed
26192 as a dispatching operation.  This was permitted in Ada 95.
26194 @item Access types, discriminants, and constraints.
26195 Rule changes in this area have led to some incompatibilities; for example,
26196 constrained subtypes of some access types are not permitted in Ada 2005.
26198 @item Aggregates for limited types.
26199 The allowance of aggregates for limited types in Ada 2005 raises the
26200 possibility of ambiguities in legal Ada 95 programs, since additional types
26201 now need to be considered in expression resolution.
26203 @item Fixed-point multiplication and division.
26204 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26205 were legal in Ada 95 and invoked the predefined versions of these operations,
26206 are now ambiguous.
26207 The ambiguity may be resolved either by applying a type conversion to the
26208 expression, or by explicitly invoking the operation from package
26209 @code{Standard}.
26211 @item Return-by-reference types.
26212 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26213 can declare a function returning a value from an anonymous access type.
26214 @end table
26217 @node Implementation-dependent characteristics
26218 @section Implementation-dependent characteristics
26219 @noindent
26220 Although the Ada language defines the semantics of each construct as
26221 precisely as practical, in some situations (for example for reasons of
26222 efficiency, or where the effect is heavily dependent on the host or target
26223 platform) the implementation is allowed some freedom.  In porting Ada 83
26224 code to GNAT, you need to be aware of whether / how the existing code
26225 exercised such implementation dependencies.  Such characteristics fall into
26226 several categories, and GNAT offers specific support in assisting the
26227 transition from certain Ada 83 compilers.
26229 @menu
26230 * Implementation-defined pragmas::
26231 * Implementation-defined attributes::
26232 * Libraries::
26233 * Elaboration order::
26234 * Target-specific aspects::
26235 @end menu
26237 @node Implementation-defined pragmas
26238 @subsection Implementation-defined pragmas
26240 @noindent
26241 Ada compilers are allowed to supplement the language-defined pragmas, and
26242 these are a potential source of non-portability.  All GNAT-defined pragmas
26243 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26244 Reference Manual}, and these include several that are specifically
26245 intended to correspond to other vendors' Ada 83 pragmas.
26246 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26247 For compatibility with HP Ada 83, GNAT supplies the pragmas
26248 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26249 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26250 and @code{Volatile}.
26251 Other relevant pragmas include @code{External} and @code{Link_With}.
26252 Some vendor-specific
26253 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26254 recognized, thus
26255 avoiding compiler rejection of units that contain such pragmas; they are not
26256 relevant in a GNAT context and hence are not otherwise implemented.
26258 @node Implementation-defined attributes
26259 @subsection Implementation-defined attributes
26261 Analogous to pragmas, the set of attributes may be extended by an
26262 implementation.  All GNAT-defined attributes are described in
26263 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26264 Manual}, and these include several that are specifically intended
26265 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26266 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26267 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26268 @code{Type_Class}.
26270 @node Libraries
26271 @subsection Libraries
26272 @noindent
26273 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26274 code uses vendor-specific libraries then there are several ways to manage
26275 this in Ada 95 or Ada 2005:
26276 @enumerate
26277 @item
26278 If the source code for the libraries (specs and bodies) are
26279 available, then the libraries can be migrated in the same way as the
26280 application.
26281 @item
26282 If the source code for the specs but not the bodies are
26283 available, then you can reimplement the bodies.
26284 @item
26285 Some features introduced by Ada 95 obviate the need for library support.  For
26286 example most Ada 83 vendors supplied a package for unsigned integers.  The
26287 Ada 95 modular type feature is the preferred way to handle this need, so
26288 instead of migrating or reimplementing the unsigned integer package it may
26289 be preferable to retrofit the application using modular types.
26290 @end enumerate
26292 @node Elaboration order
26293 @subsection Elaboration order
26294 @noindent
26295 The implementation can choose any elaboration order consistent with the unit
26296 dependency relationship.  This freedom means that some orders can result in
26297 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26298 to invoke a subprogram its body has been elaborated, or to instantiate a
26299 generic before the generic body has been elaborated.  By default GNAT
26300 attempts to choose a safe order (one that will not encounter access before
26301 elaboration problems) by implicitly inserting @code{Elaborate} or
26302 @code{Elaborate_All} pragmas where
26303 needed.  However, this can lead to the creation of elaboration circularities
26304 and a resulting rejection of the program by gnatbind.  This issue is
26305 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26306 In brief, there are several
26307 ways to deal with this situation:
26309 @itemize @bullet
26310 @item
26311 Modify the program to eliminate the circularities, e.g.@: by moving
26312 elaboration-time code into explicitly-invoked procedures
26313 @item
26314 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26315 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26316 @code{Elaborate_All}
26317 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26318 (by selectively suppressing elaboration checks via pragma
26319 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26320 @end itemize
26322 @node Target-specific aspects
26323 @subsection Target-specific aspects
26324 @noindent
26325 Low-level applications need to deal with machine addresses, data
26326 representations, interfacing with assembler code, and similar issues.  If
26327 such an Ada 83 application is being ported to different target hardware (for
26328 example where the byte endianness has changed) then you will need to
26329 carefully examine the program logic; the porting effort will heavily depend
26330 on the robustness of the original design.  Moreover, Ada 95 (and thus
26331 Ada 2005) are sometimes
26332 incompatible with typical Ada 83 compiler practices regarding implicit
26333 packing, the meaning of the Size attribute, and the size of access values.
26334 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26336 @node Compatibility with Other Ada Systems
26337 @section Compatibility with Other Ada Systems
26339 @noindent
26340 If programs avoid the use of implementation dependent and
26341 implementation defined features, as documented in the @cite{Ada
26342 Reference Manual}, there should be a high degree of portability between
26343 GNAT and other Ada systems.  The following are specific items which
26344 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26345 compilers, but do not affect porting code to GNAT@.
26346 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26347 the following issues may or may not arise for Ada 2005 programs
26348 when other compilers appear.)
26350 @table @emph
26351 @item Ada 83 Pragmas and Attributes
26352 Ada 95 compilers are allowed, but not required, to implement the missing
26353 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26354 GNAT implements all such pragmas and attributes, eliminating this as
26355 a compatibility concern, but some other Ada 95 compilers reject these
26356 pragmas and attributes.
26358 @item Specialized Needs Annexes
26359 GNAT implements the full set of special needs annexes.  At the
26360 current time, it is the only Ada 95 compiler to do so.  This means that
26361 programs making use of these features may not be portable to other Ada
26362 95 compilation systems.
26364 @item Representation Clauses
26365 Some other Ada 95 compilers implement only the minimal set of
26366 representation clauses required by the Ada 95 reference manual.  GNAT goes
26367 far beyond this minimal set, as described in the next section.
26368 @end table
26370 @node Representation Clauses
26371 @section Representation Clauses
26373 @noindent
26374 The Ada 83 reference manual was quite vague in describing both the minimal
26375 required implementation of representation clauses, and also their precise
26376 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26377 minimal set of capabilities required is still quite limited.
26379 GNAT implements the full required set of capabilities in
26380 Ada 95 and Ada 2005, but also goes much further, and in particular
26381 an effort has been made to be compatible with existing Ada 83 usage to the
26382 greatest extent possible.
26384 A few cases exist in which Ada 83 compiler behavior is incompatible with
26385 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26386 intentional or accidental dependence on specific implementation dependent
26387 characteristics of these Ada 83 compilers.  The following is a list of
26388 the cases most likely to arise in existing Ada 83 code.
26390 @table @emph
26391 @item Implicit Packing
26392 Some Ada 83 compilers allowed a Size specification to cause implicit
26393 packing of an array or record.  This could cause expensive implicit
26394 conversions for change of representation in the presence of derived
26395 types, and the Ada design intends to avoid this possibility.
26396 Subsequent AI's were issued to make it clear that such implicit
26397 change of representation in response to a Size clause is inadvisable,
26398 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26399 Reference Manuals as implementation advice that is followed by GNAT@.
26400 The problem will show up as an error
26401 message rejecting the size clause.  The fix is simply to provide
26402 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26403 a Component_Size clause.
26405 @item Meaning of Size Attribute
26406 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26407 the minimal number of bits required to hold values of the type.  For example,
26408 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26409 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26410 some 32 in this situation.  This problem will usually show up as a compile
26411 time error, but not always.  It is a good idea to check all uses of the
26412 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26413 Object_Size can provide a useful way of duplicating the behavior of
26414 some Ada 83 compiler systems.
26416 @item Size of Access Types
26417 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26418 and that therefore it will be the same size as a System.Address value.  This
26419 assumption is true for GNAT in most cases with one exception.  For the case of
26420 a pointer to an unconstrained array type (where the bounds may vary from one
26421 value of the access type to another), the default is to use a ``fat pointer'',
26422 which is represented as two separate pointers, one to the bounds, and one to
26423 the array.  This representation has a number of advantages, including improved
26424 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26425 code which makes the assumption that, for example, pointers fit in 32 bits on
26426 a machine with 32-bit addressing.
26428 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26429 access types in this case (where the designated type is an unconstrained array
26430 type).  These thin pointers are indeed the same size as a System.Address value.
26431 To specify a thin pointer, use a size clause for the type, for example:
26433 @smallexample @c ada
26434 type X is access all String;
26435 for X'Size use Standard'Address_Size;
26436 @end smallexample
26438 @noindent
26439 which will cause the type X to be represented using a single pointer.
26440 When using this representation, the bounds are right behind the array.
26441 This representation is slightly less efficient, and does not allow quite
26442 such flexibility in the use of foreign pointers or in using the
26443 Unrestricted_Access attribute to create pointers to non-aliased objects.
26444 But for any standard portable use of the access type it will work in
26445 a functionally correct manner and allow porting of existing code.
26446 Note that another way of forcing a thin pointer representation
26447 is to use a component size clause for the element size in an array,
26448 or a record representation clause for an access field in a record.
26449 @end table
26451 @ifclear vms
26452 @c This brief section is only in the non-VMS version
26453 @c The complete chapter on HP Ada is in the VMS version
26454 @node Compatibility with HP Ada 83
26455 @section Compatibility with HP Ada 83
26457 @noindent
26458 The VMS version of GNAT fully implements all the pragmas and attributes
26459 provided by HP Ada 83, as well as providing the standard HP Ada 83
26460 libraries, including Starlet.  In addition, data layouts and parameter
26461 passing conventions are highly compatible.  This means that porting
26462 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26463 most other porting efforts.  The following are some of the most
26464 significant differences between GNAT and HP Ada 83.
26466 @table @emph
26467 @item Default floating-point representation
26468 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26469 it is VMS format.  GNAT does implement the necessary pragmas
26470 (Long_Float, Float_Representation) for changing this default.
26472 @item System
26473 The package System in GNAT exactly corresponds to the definition in the
26474 Ada 95 reference manual, which means that it excludes many of the
26475 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26476 that contains the additional definitions, and a special pragma,
26477 Extend_System allows this package to be treated transparently as an
26478 extension of package System.
26480 @item To_Address
26481 The definitions provided by Aux_DEC are exactly compatible with those
26482 in the HP Ada 83 version of System, with one exception.
26483 HP Ada provides the following declarations:
26485 @smallexample @c ada
26486 TO_ADDRESS (INTEGER)
26487 TO_ADDRESS (UNSIGNED_LONGWORD)
26488 TO_ADDRESS (@i{universal_integer})
26489 @end smallexample
26491 @noindent
26492 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26493 an extension to Ada 83 not strictly compatible with the reference manual.
26494 In GNAT, we are constrained to be exactly compatible with the standard,
26495 and this means we cannot provide this capability.  In HP Ada 83, the
26496 point of this definition is to deal with a call like:
26498 @smallexample @c ada
26499 TO_ADDRESS (16#12777#);
26500 @end smallexample
26502 @noindent
26503 Normally, according to the Ada 83 standard, one would expect this to be
26504 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26505 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26506 definition using @i{universal_integer} takes precedence.
26508 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26509 is not possible to be 100% compatible.  Since there are many programs using
26510 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26511 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26512 declarations provided in the GNAT version of AUX_Dec are:
26514 @smallexample @c ada
26515 function To_Address (X : Integer) return Address;
26516 pragma Pure_Function (To_Address);
26518 function To_Address_Long (X : Unsigned_Longword)
26519  return Address;
26520 pragma Pure_Function (To_Address_Long);
26521 @end smallexample
26523 @noindent
26524 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26525 change the name to TO_ADDRESS_LONG@.
26527 @item Task_Id values
26528 The Task_Id values assigned will be different in the two systems, and GNAT
26529 does not provide a specified value for the Task_Id of the environment task,
26530 which in GNAT is treated like any other declared task.
26531 @end table
26533 @noindent
26534 For full details on these and other less significant compatibility issues,
26535 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26536 Overview and Comparison on HP Platforms}.
26538 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26539 attributes are recognized, although only a subset of them can sensibly
26540 be implemented.  The description of pragmas in @ref{Implementation
26541 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26542 indicates whether or not they are applicable to non-VMS systems.
26543 @end ifclear
26545 @ifset vms
26546 @node Transitioning to 64-Bit GNAT for OpenVMS
26547 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26549 @noindent
26550 This section is meant to assist users of pre-2006 @value{EDITION}
26551 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26552 the version of the GNAT technology supplied in 2006 and later for
26553 OpenVMS on both Alpha and I64.
26555 @menu
26556 * Introduction to transitioning::
26557 * Migration of 32 bit code::
26558 * Taking advantage of 64 bit addressing::
26559 * Technical details::
26560 @end menu
26562 @node Introduction to transitioning
26563 @subsection Introduction
26565 @noindent
26566 64-bit @value{EDITION} for Open VMS has been designed to meet
26567 three main goals:
26569 @enumerate
26570 @item
26571 Providing a full conforming implementation of Ada 95 and Ada 2005
26573 @item
26574 Allowing maximum backward compatibility, thus easing migration of existing
26575 Ada source code
26577 @item
26578 Supplying a path for exploiting the full 64-bit address range
26579 @end enumerate
26581 @noindent
26582 Ada's strong typing semantics has made it
26583 impractical to have different 32-bit and 64-bit modes. As soon as
26584 one object could possibly be outside the 32-bit address space, this
26585 would make it necessary for the @code{System.Address} type to be 64 bits.
26586 In particular, this would cause inconsistencies if 32-bit code is
26587 called from 64-bit code that raises an exception.
26589 This issue has been resolved by always using 64-bit addressing
26590 at the system level, but allowing for automatic conversions between
26591 32-bit and 64-bit addresses where required. Thus users who
26592 do not currently require 64-bit addressing capabilities, can
26593 recompile their code with only minimal changes (and indeed
26594 if the code is written in portable Ada, with no assumptions about
26595 the size of the @code{Address} type, then no changes at all are necessary).
26596 At the same time,
26597 this approach provides a simple, gradual upgrade path to future
26598 use of larger memories than available for 32-bit systems.
26599 Also, newly written applications or libraries will by default
26600 be fully compatible with future systems exploiting 64-bit
26601 addressing capabilities.
26603 @ref{Migration of 32 bit code}, will focus on porting applications
26604 that do not require more than 2 GB of
26605 addressable memory. This code will be referred to as
26606 @emph{32-bit code}.
26607 For applications intending to exploit the full 64-bit address space,
26608 @ref{Taking advantage of 64 bit addressing},
26609 will consider further changes that may be required.
26610 Such code will be referred to below as @emph{64-bit code}.
26612 @node Migration of 32 bit code
26613 @subsection Migration of 32-bit code
26615 @menu
26616 * Address types::
26617 * Access types and 32/64-bit allocation::
26618 * Unchecked conversions::
26619 * Predefined constants::
26620 * Interfacing with C::
26621 * 32/64-bit descriptors::
26622 * Experience with source compatibility::
26623 @end menu
26625 @node Address types
26626 @subsubsection Address types
26628 @noindent
26629 To solve the problem of mixing 64-bit and 32-bit addressing,
26630 while maintaining maximum backward compatibility, the following
26631 approach has been taken:
26633 @itemize @bullet
26634 @item
26635 @code{System.Address} always has a size of 64 bits
26636 @cindex @code{System.Address} size
26637 @cindex @code{Address} size
26639 @item
26640 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26641 @cindex @code{System.Short_Address} size
26642 @cindex @code{Short_Address} size
26643 @end itemize
26645 @noindent
26646 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26647 a @code{Short_Address}
26648 may be used where an @code{Address} is required, and vice versa, without
26649 needing explicit type conversions.
26650 By virtue of the Open VMS parameter passing conventions,
26651 even imported
26652 and exported subprograms that have 32-bit address parameters are
26653 compatible with those that have 64-bit address parameters.
26654 (See @ref{Making code 64 bit clean} for details.)
26656 The areas that may need attention are those where record types have
26657 been defined that contain components of the type @code{System.Address}, and
26658 where objects of this type are passed to code expecting a record layout with
26659 32-bit addresses.
26661 Different compilers on different platforms cannot be
26662 expected to represent the same type in the same way,
26663 since alignment constraints
26664 and other system-dependent properties affect the compiler's decision.
26665 For that reason, Ada code
26666 generally uses representation clauses to specify the expected
26667 layout where required.
26669 If such a representation clause uses 32 bits for a component having
26670 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26671 will detect that error and produce a specific diagnostic message.
26672 The developer should then determine whether the representation
26673 should be 64 bits or not and make either of two changes:
26674 change the size to 64 bits and leave the type as @code{System.Address}, or
26675 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26676 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26677 required in any code setting or accessing the field; the compiler will
26678 automatically perform any needed conversions between address
26679 formats.
26681 @node Access types and 32/64-bit allocation
26682 @subsubsection Access types and 32/64-bit allocation
26683 @cindex 32-bit allocation
26684 @cindex 64-bit allocation
26686 @noindent
26687 By default, objects designated by access values are always allocated in
26688 the 64-bit address space, and access values themselves are represented
26689 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
26690 is required (for example if the address of an allocated object is assigned
26691 to a @code{Short_Address} variable), then several alternatives are available:
26693 @itemize @bullet
26694 @item
26695 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26696 definition is @code{access T} versus @code{access all T} or
26697 @code{access constant T}), may be declared with a @code{'Size} representation
26698 clause that establishes the size as 32 bits.
26699 In such circumstances allocations for that type will
26700 be from the 32-bit heap.  Such a clause is not permitted
26701 for a general access type (declared with @code{access all} or
26702 @code{access constant}) as values of such types must be able to refer
26703 to any object of the designated type, including objects residing outside
26704 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
26705 type definitions, however, since general access types were introduced
26706 in @w{Ada 95}.
26708 @item
26709 Switches for @command{GNAT BIND} control whether the internal GNAT
26710 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26711 @cindex @code{__gnat_malloc}
26712 The switches are respectively @option{-H64} (the default) and
26713 @option{-H32}.
26714 @cindex @option{-H32} (@command{gnatbind})
26715 @cindex @option{-H64} (@command{gnatbind})
26717 @item
26718 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26719 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26720 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26721 If this variable is left
26722 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26723 then the default (64-bit) allocation is used.
26724 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26725 then 32-bit allocation is used.  The gnatbind qualifiers described above
26726 override this logical name.
26728 @item
26729 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26730 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26731 at a low level to convert explicit calls to @code{malloc} and related
26732 functions from the C run-time library so that they perform allocations
26733 in the 32-bit heap.
26734 Since all internal allocations from GNAT use @code{__gnat_malloc},
26735 this switch is not required unless the program makes explicit calls on
26736 @code{malloc} (or related functions) from interfaced C code.
26737 @end itemize
26740 @node Unchecked conversions
26741 @subsubsection Unchecked conversions
26743 @noindent
26744 In the case of an @code{Unchecked_Conversion} where the source type is a
26745 64-bit access type or the type @code{System.Address}, and the target
26746 type is a 32-bit type, the compiler will generate a warning.
26747 Even though the generated code will still perform the required
26748 conversions, it is highly recommended in these cases to use
26749 respectively a 32-bit access type or @code{System.Short_Address}
26750 as the source type.
26752 @node Predefined constants
26753 @subsubsection Predefined constants
26755 @noindent
26756 The following table shows the correspondence between pre-2006 versions of
26757 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26758 (``New''):
26760 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26761 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26762 @item   @code{System.Word_Size}          @tab 32      @tab 64
26763 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26764 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26765 @item   @code{System.Address_Size}       @tab 32      @tab 64
26766 @end multitable
26768 @noindent
26769 If you need to refer to the specific
26770 memory size of a 32-bit implementation, instead of the
26771 actual memory size, use @code{System.Short_Memory_Size}
26772 rather than @code{System.Memory_Size}.
26773 Similarly, references to @code{System.Address_Size} may need
26774 to be replaced by @code{System.Short_Address'Size}.
26775 The program @command{gnatfind} may be useful for locating
26776 references to the above constants, so that you can verify that they
26777 are still correct.
26779 @node Interfacing with C
26780 @subsubsection Interfacing with C
26782 @noindent
26783 In order to minimize the impact of the transition to 64-bit addresses on
26784 legacy programs, some fundamental types in the @code{Interfaces.C}
26785 package hierarchy continue to be represented in 32 bits.
26786 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26787 This eases integration with the default HP C layout choices, for example
26788 as found in the system routines in @code{DECC$SHR.EXE}.
26789 Because of this implementation choice, the type fully compatible with
26790 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26791 Depending on the context the compiler will issue a
26792 warning or an error when type @code{Address} is used, alerting the user to a
26793 potential problem. Otherwise 32-bit programs that use
26794 @code{Interfaces.C} should normally not require code modifications
26796 The other issue arising with C interfacing concerns pragma @code{Convention}.
26797 For VMS 64-bit systems, there is an issue of the appropriate default size
26798 of C convention pointers in the absence of an explicit size clause. The HP
26799 C compiler can choose either 32 or 64 bits depending on compiler options.
26800 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26801 clause is given. This proves a better choice for porting 32-bit legacy
26802 applications. In order to have a 64-bit representation, it is necessary to
26803 specify a size representation clause. For example:
26805 @smallexample @c ada
26806 type int_star is access Interfaces.C.int;
26807 pragma Convention(C, int_star);
26808 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
26809 @end smallexample
26811 @node 32/64-bit descriptors
26812 @subsubsection 32/64-bit descriptors
26814 @noindent
26815 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
26816 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26817 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26818 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26819 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26821 If the configuration pragma @code{Short_Descriptors} is supplied, then
26822 all descriptors will be 32 bits.
26823 @cindex pragma @code{Short_Descriptors}
26825 @node Experience with source compatibility
26826 @subsubsection Experience with source compatibility
26828 @noindent
26829 The Security Server and STARLET on I64 provide an interesting ``test case''
26830 for source compatibility issues, since it is in such system code
26831 where assumptions about @code{Address} size might be expected to occur.
26832 Indeed, there were a small number of occasions in the Security Server
26833 file @file{jibdef.ads}
26834 where a representation clause for a record type specified
26835 32 bits for a component of type @code{Address}.
26836 All of these errors were detected by the compiler.
26837 The repair was obvious and immediate; to simply replace @code{Address} by
26838 @code{Short_Address}.
26840 In the case of STARLET, there were several record types that should
26841 have had representation clauses but did not.  In these record types
26842 there was an implicit assumption that an @code{Address} value occupied
26843 32 bits.
26844 These compiled without error, but their usage resulted in run-time error
26845 returns from STARLET system calls.
26846 Future GNAT technology enhancements may include a tool that detects and flags
26847 these sorts of potential source code porting problems.
26849 @c ****************************************
26850 @node Taking advantage of 64 bit addressing
26851 @subsection Taking advantage of 64-bit addressing
26853 @menu
26854 * Making code 64 bit clean::
26855 * Allocating memory from the 64 bit storage pool::
26856 * Restrictions on use of 64 bit objects::
26857 * STARLET and other predefined libraries::
26858 @end menu
26860 @node Making code 64 bit clean
26861 @subsubsection Making code 64-bit clean
26863 @noindent
26864 In order to prevent problems that may occur when (parts of) a
26865 system start using memory outside the 32-bit address range,
26866 we recommend some additional guidelines:
26868 @itemize @bullet
26869 @item
26870 For imported subprograms that take parameters of the
26871 type @code{System.Address}, ensure that these subprograms can
26872 indeed handle 64-bit addresses. If not, or when in doubt,
26873 change the subprogram declaration to specify
26874 @code{System.Short_Address} instead.
26876 @item
26877 Resolve all warnings related to size mismatches in
26878 unchecked conversions. Failing to do so causes
26879 erroneous execution if the source object is outside
26880 the 32-bit address space.
26882 @item
26883 (optional) Explicitly use the 32-bit storage pool
26884 for access types used in a 32-bit context, or use
26885 generic access types where possible
26886 (@pxref{Restrictions on use of 64 bit objects}).
26887 @end itemize
26889 @noindent
26890 If these rules are followed, the compiler will automatically insert
26891 any necessary checks to ensure that no addresses or access values
26892 passed to 32-bit code ever refer to objects outside the 32-bit
26893 address range.
26894 Any attempt to do this will raise @code{Constraint_Error}.
26896 @node Allocating memory from the 64 bit storage pool
26897 @subsubsection Allocating memory from the 64-bit storage pool
26899 @noindent
26900 By default, all allocations -- for both pool-specific and general
26901 access types -- use the 64-bit storage pool.  To override
26902 this default, for an individual access type or globally, see
26903 @ref{Access types and 32/64-bit allocation}.
26905 @node Restrictions on use of 64 bit objects
26906 @subsubsection Restrictions on use of 64-bit objects
26908 @noindent
26909 Taking the address of an object allocated from a 64-bit storage pool,
26910 and then passing this address to a subprogram expecting
26911 @code{System.Short_Address},
26912 or assigning it to a variable of type @code{Short_Address}, will cause
26913 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26914 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26915 no exception is raised and execution
26916 will become erroneous.
26918 @node STARLET and other predefined libraries
26919 @subsubsection STARLET and other predefined libraries
26921 @noindent
26922 All code that comes as part of GNAT is 64-bit clean, but the
26923 restrictions given in @ref{Restrictions on use of 64 bit objects},
26924 still apply. Look at the package
26925 specs to see in which contexts objects allocated
26926 in 64-bit address space are acceptable.
26928 @node Technical details
26929 @subsection Technical details
26931 @noindent
26932 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26933 Ada standard with respect to the type of @code{System.Address}. Previous
26934 versions of GNAT Pro have defined this type as private and implemented it as a
26935 modular type.
26937 In order to allow defining @code{System.Short_Address} as a proper subtype,
26938 and to match the implicit sign extension in parameter passing,
26939 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26940 visible (i.e., non-private) integer type.
26941 Standard operations on the type, such as the binary operators ``+'', ``-'',
26942 etc., that take @code{Address} operands and return an @code{Address} result,
26943 have been hidden by declaring these
26944 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26945 ambiguities that would otherwise result from overloading.
26946 (Note that, although @code{Address} is a visible integer type,
26947 good programming practice dictates against exploiting the type's
26948 integer properties such as literals, since this will compromise
26949 code portability.)
26951 Defining @code{Address} as a visible integer type helps achieve
26952 maximum compatibility for existing Ada code,
26953 without sacrificing the capabilities of the 64-bit architecture.
26954 @end ifset
26956 @c ************************************************
26957 @ifset unw
26958 @node Microsoft Windows Topics
26959 @appendix Microsoft Windows Topics
26960 @cindex Windows NT
26961 @cindex Windows 95
26962 @cindex Windows 98
26964 @noindent
26965 This chapter describes topics that are specific to the Microsoft Windows
26966 platforms (NT, 2000, and XP Professional).
26968 @menu
26969 * Using GNAT on Windows::
26970 * Using a network installation of GNAT::
26971 * CONSOLE and WINDOWS subsystems::
26972 * Temporary Files::
26973 * Mixed-Language Programming on Windows::
26974 * Windows Calling Conventions::
26975 * Introduction to Dynamic Link Libraries (DLLs)::
26976 * Using DLLs with GNAT::
26977 * Building DLLs with GNAT Project files::
26978 * Building DLLs with GNAT::
26979 * Building DLLs with gnatdll::
26980 * GNAT and Windows Resources::
26981 * Debugging a DLL::
26982 * Setting Stack Size from gnatlink::
26983 * Setting Heap Size from gnatlink::
26984 @end menu
26986 @node Using GNAT on Windows
26987 @section Using GNAT on Windows
26989 @noindent
26990 One of the strengths of the GNAT technology is that its tool set
26991 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26992 @code{gdb} debugger, etc.) is used in the same way regardless of the
26993 platform.
26995 On Windows this tool set is complemented by a number of Microsoft-specific
26996 tools that have been provided to facilitate interoperability with Windows
26997 when this is required. With these tools:
26999 @itemize @bullet
27001 @item
27002 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27003 subsystems.
27005 @item
27006 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27007 relocatable and non-relocatable DLLs are supported).
27009 @item
27010 You can build Ada DLLs for use in other applications. These applications
27011 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27012 relocatable and non-relocatable Ada DLLs are supported.
27014 @item
27015 You can include Windows resources in your Ada application.
27017 @item
27018 You can use or create COM/DCOM objects.
27019 @end itemize
27021 @noindent
27022 Immediately below are listed all known general GNAT-for-Windows restrictions.
27023 Other restrictions about specific features like Windows Resources and DLLs
27024 are listed in separate sections below.
27026 @itemize @bullet
27028 @item
27029 It is not possible to use @code{GetLastError} and @code{SetLastError}
27030 when tasking, protected records, or exceptions are used. In these
27031 cases, in order to implement Ada semantics, the GNAT run-time system
27032 calls certain Win32 routines that set the last error variable to 0 upon
27033 success. It should be possible to use @code{GetLastError} and
27034 @code{SetLastError} when tasking, protected record, and exception
27035 features are not used, but it is not guaranteed to work.
27037 @item
27038 It is not possible to link against Microsoft libraries except for
27039 import libraries. Interfacing must be done by the mean of DLLs.
27041 @item
27042 When the compilation environment is located on FAT32 drives, users may
27043 experience recompilations of the source files that have not changed if
27044 Daylight Saving Time (DST) state has changed since the last time files
27045 were compiled. NTFS drives do not have this problem.
27047 @item
27048 No components of the GNAT toolset use any entries in the Windows
27049 registry. The only entries that can be created are file associations and
27050 PATH settings, provided the user has chosen to create them at installation
27051 time, as well as some minimal book-keeping information needed to correctly
27052 uninstall or integrate different GNAT products.
27053 @end itemize
27055 @node Using a network installation of GNAT
27056 @section Using a network installation of GNAT
27058 @noindent
27059 Make sure the system on which GNAT is installed is accessible from the
27060 current machine, i.e., the install location is shared over the network.
27061 Shared resources are accessed on Windows by means of UNC paths, which
27062 have the format @code{\\server\sharename\path}
27064 In order to use such a network installation, simply add the UNC path of the
27065 @file{bin} directory of your GNAT installation in front of your PATH. For
27066 example, if GNAT is installed in @file{\GNAT} directory of a share location
27067 called @file{c-drive} on a machine @file{LOKI}, the following command will
27068 make it available:
27070 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27072 Be aware that every compilation using the network installation results in the
27073 transfer of large amounts of data across the network and will likely cause
27074 serious performance penalty.
27076 @node CONSOLE and WINDOWS subsystems
27077 @section CONSOLE and WINDOWS subsystems
27078 @cindex CONSOLE Subsystem
27079 @cindex WINDOWS Subsystem
27080 @cindex -mwindows
27082 @noindent
27083 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27084 (which is the default subsystem) will always create a console when
27085 launching the application. This is not something desirable when the
27086 application has a Windows GUI. To get rid of this console the
27087 application must be using the @code{WINDOWS} subsystem. To do so
27088 the @option{-mwindows} linker option must be specified.
27090 @smallexample
27091 $ gnatmake winprog -largs -mwindows
27092 @end smallexample
27094 @node Temporary Files
27095 @section Temporary Files
27096 @cindex Temporary files
27098 @noindent
27099 It is possible to control where temporary files gets created by setting
27100 the @env{TMP} environment variable. The file will be created:
27102 @itemize
27103 @item Under the directory pointed to by the @env{TMP} environment variable if
27104 this directory exists.
27106 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27107 set (or not pointing to a directory) and if this directory exists.
27109 @item Under the current working directory otherwise.
27110 @end itemize
27112 @noindent
27113 This allows you to determine exactly where the temporary
27114 file will be created. This is particularly useful in networked
27115 environments where you may not have write access to some
27116 directories.
27118 @node Mixed-Language Programming on Windows
27119 @section Mixed-Language Programming on Windows
27121 @noindent
27122 Developing pure Ada applications on Windows is no different than on
27123 other GNAT-supported platforms. However, when developing or porting an
27124 application that contains a mix of Ada and C/C++, the choice of your
27125 Windows C/C++ development environment conditions your overall
27126 interoperability strategy.
27128 If you use @command{gcc} to compile the non-Ada part of your application,
27129 there are no Windows-specific restrictions that affect the overall
27130 interoperability with your Ada code. If you do want to use the
27131 Microsoft tools for your non-Ada code, you have two choices:
27133 @enumerate
27134 @item
27135 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27136 application. In this case, use the Microsoft or whatever environment to
27137 build the DLL and use GNAT to build your executable
27138 (@pxref{Using DLLs with GNAT}).
27140 @item
27141 Or you can encapsulate your Ada code in a DLL to be linked with the
27142 other part of your application. In this case, use GNAT to build the DLL
27143 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27144 or whatever environment to build your executable.
27145 @end enumerate
27147 @node Windows Calling Conventions
27148 @section Windows Calling Conventions
27149 @findex Stdcall
27150 @findex APIENTRY
27152 This section pertain only to Win32. On Win64 there is a single native
27153 calling convention. All convention specifiers are ignored on this
27154 platform.
27156 @menu
27157 * C Calling Convention::
27158 * Stdcall Calling Convention::
27159 * Win32 Calling Convention::
27160 * DLL Calling Convention::
27161 @end menu
27163 @noindent
27164 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27165 (callee), there are several ways to push @code{G}'s parameters on the
27166 stack and there are several possible scenarios to clean up the stack
27167 upon @code{G}'s return. A calling convention is an agreed upon software
27168 protocol whereby the responsibilities between the caller (@code{F}) and
27169 the callee (@code{G}) are clearly defined. Several calling conventions
27170 are available for Windows:
27172 @itemize @bullet
27173 @item
27174 @code{C} (Microsoft defined)
27176 @item
27177 @code{Stdcall} (Microsoft defined)
27179 @item
27180 @code{Win32} (GNAT specific)
27182 @item
27183 @code{DLL} (GNAT specific)
27184 @end itemize
27186 @node C Calling Convention
27187 @subsection @code{C} Calling Convention
27189 @noindent
27190 This is the default calling convention used when interfacing to C/C++
27191 routines compiled with either @command{gcc} or Microsoft Visual C++.
27193 In the @code{C} calling convention subprogram parameters are pushed on the
27194 stack by the caller from right to left. The caller itself is in charge of
27195 cleaning up the stack after the call. In addition, the name of a routine
27196 with @code{C} calling convention is mangled by adding a leading underscore.
27198 The name to use on the Ada side when importing (or exporting) a routine
27199 with @code{C} calling convention is the name of the routine. For
27200 instance the C function:
27202 @smallexample
27203 int get_val (long);
27204 @end smallexample
27206 @noindent
27207 should be imported from Ada as follows:
27209 @smallexample @c ada
27210 @group
27211 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27212 pragma Import (C, Get_Val, External_Name => "get_val");
27213 @end group
27214 @end smallexample
27216 @noindent
27217 Note that in this particular case the @code{External_Name} parameter could
27218 have been omitted since, when missing, this parameter is taken to be the
27219 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27220 is missing, as in the above example, this parameter is set to be the
27221 @code{External_Name} with a leading underscore.
27223 When importing a variable defined in C, you should always use the @code{C}
27224 calling convention unless the object containing the variable is part of a
27225 DLL (in which case you should use the @code{Stdcall} calling
27226 convention, @pxref{Stdcall Calling Convention}).
27228 @node Stdcall Calling Convention
27229 @subsection @code{Stdcall} Calling Convention
27231 @noindent
27232 This convention, which was the calling convention used for Pascal
27233 programs, is used by Microsoft for all the routines in the Win32 API for
27234 efficiency reasons. It must be used to import any routine for which this
27235 convention was specified.
27237 In the @code{Stdcall} calling convention subprogram parameters are pushed
27238 on the stack by the caller from right to left. The callee (and not the
27239 caller) is in charge of cleaning the stack on routine exit. In addition,
27240 the name of a routine with @code{Stdcall} calling convention is mangled by
27241 adding a leading underscore (as for the @code{C} calling convention) and a
27242 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27243 bytes) of the parameters passed to the routine.
27245 The name to use on the Ada side when importing a C routine with a
27246 @code{Stdcall} calling convention is the name of the C routine. The leading
27247 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27248 the compiler. For instance the Win32 function:
27250 @smallexample
27251 @b{APIENTRY} int get_val (long);
27252 @end smallexample
27254 @noindent
27255 should be imported from Ada as follows:
27257 @smallexample @c ada
27258 @group
27259 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27260 pragma Import (Stdcall, Get_Val);
27261 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27262 @end group
27263 @end smallexample
27265 @noindent
27266 As for the @code{C} calling convention, when the @code{External_Name}
27267 parameter is missing, it is taken to be the name of the Ada entity in lower
27268 case. If instead of writing the above import pragma you write:
27270 @smallexample @c ada
27271 @group
27272 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27273 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27274 @end group
27275 @end smallexample
27277 @noindent
27278 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27279 of specifying the @code{External_Name} parameter you specify the
27280 @code{Link_Name} as in the following example:
27282 @smallexample @c ada
27283 @group
27284 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27285 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27286 @end group
27287 @end smallexample
27289 @noindent
27290 then the imported routine is @code{retrieve_val}, that is, there is no
27291 decoration at all. No leading underscore and no Stdcall suffix
27292 @code{@@}@code{@var{nn}}.
27294 @noindent
27295 This is especially important as in some special cases a DLL's entry
27296 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27297 name generated for a call has it.
27299 @noindent
27300 It is also possible to import variables defined in a DLL by using an
27301 import pragma for a variable. As an example, if a DLL contains a
27302 variable defined as:
27304 @smallexample
27305 int my_var;
27306 @end smallexample
27308 @noindent
27309 then, to access this variable from Ada you should write:
27311 @smallexample @c ada
27312 @group
27313 My_Var : Interfaces.C.int;
27314 pragma Import (Stdcall, My_Var);
27315 @end group
27316 @end smallexample
27318 @noindent
27319 Note that to ease building cross-platform bindings this convention
27320 will be handled as a @code{C} calling convention on non-Windows platforms.
27322 @node Win32 Calling Convention
27323 @subsection @code{Win32} Calling Convention
27325 @noindent
27326 This convention, which is GNAT-specific is fully equivalent to the
27327 @code{Stdcall} calling convention described above.
27329 @node DLL Calling Convention
27330 @subsection @code{DLL} Calling Convention
27332 @noindent
27333 This convention, which is GNAT-specific is fully equivalent to the
27334 @code{Stdcall} calling convention described above.
27336 @node Introduction to Dynamic Link Libraries (DLLs)
27337 @section Introduction to Dynamic Link Libraries (DLLs)
27338 @findex DLL
27340 @noindent
27341 A Dynamically Linked Library (DLL) is a library that can be shared by
27342 several applications running under Windows. A DLL can contain any number of
27343 routines and variables.
27345 One advantage of DLLs is that you can change and enhance them without
27346 forcing all the applications that depend on them to be relinked or
27347 recompiled. However, you should be aware than all calls to DLL routines are
27348 slower since, as you will understand below, such calls are indirect.
27350 To illustrate the remainder of this section, suppose that an application
27351 wants to use the services of a DLL @file{API.dll}. To use the services
27352 provided by @file{API.dll} you must statically link against the DLL or
27353 an import library which contains a jump table with an entry for each
27354 routine and variable exported by the DLL. In the Microsoft world this
27355 import library is called @file{API.lib}. When using GNAT this import
27356 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27357 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27359 After you have linked your application with the DLL or the import library
27360 and you run your application, here is what happens:
27362 @enumerate
27363 @item
27364 Your application is loaded into memory.
27366 @item
27367 The DLL @file{API.dll} is mapped into the address space of your
27368 application. This means that:
27370 @itemize @bullet
27371 @item
27372 The DLL will use the stack of the calling thread.
27374 @item
27375 The DLL will use the virtual address space of the calling process.
27377 @item
27378 The DLL will allocate memory from the virtual address space of the calling
27379 process.
27381 @item
27382 Handles (pointers) can be safely exchanged between routines in the DLL
27383 routines and routines in the application using the DLL.
27384 @end itemize
27386 @item
27387 The entries in the jump table (from the import library @file{libAPI.dll.a}
27388 or @file{API.lib} or automatically created when linking against a DLL)
27389 which is part of your application are initialized with the addresses
27390 of the routines and variables in @file{API.dll}.
27392 @item
27393 If present in @file{API.dll}, routines @code{DllMain} or
27394 @code{DllMainCRTStartup} are invoked. These routines typically contain
27395 the initialization code needed for the well-being of the routines and
27396 variables exported by the DLL.
27397 @end enumerate
27399 @noindent
27400 There is an additional point which is worth mentioning. In the Windows
27401 world there are two kind of DLLs: relocatable and non-relocatable
27402 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27403 in the target application address space. If the addresses of two
27404 non-relocatable DLLs overlap and these happen to be used by the same
27405 application, a conflict will occur and the application will run
27406 incorrectly. Hence, when possible, it is always preferable to use and
27407 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27408 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27409 User's Guide) removes the debugging symbols from the DLL but the DLL can
27410 still be relocated.
27412 As a side note, an interesting difference between Microsoft DLLs and
27413 Unix shared libraries, is the fact that on most Unix systems all public
27414 routines are exported by default in a Unix shared library, while under
27415 Windows it is possible (but not required) to list exported routines in
27416 a definition file (@pxref{The Definition File}).
27418 @node Using DLLs with GNAT
27419 @section Using DLLs with GNAT
27421 @menu
27422 * Creating an Ada Spec for the DLL Services::
27423 * Creating an Import Library::
27424 @end menu
27426 @noindent
27427 To use the services of a DLL, say @file{API.dll}, in your Ada application
27428 you must have:
27430 @enumerate
27431 @item
27432 The Ada spec for the routines and/or variables you want to access in
27433 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27434 header files provided with the DLL.
27436 @item
27437 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27438 mentioned an import library is a statically linked library containing the
27439 import table which will be filled at load time to point to the actual
27440 @file{API.dll} routines. Sometimes you don't have an import library for the
27441 DLL you want to use. The following sections will explain how to build
27442 one. Note that this is optional.
27444 @item
27445 The actual DLL, @file{API.dll}.
27446 @end enumerate
27448 @noindent
27449 Once you have all the above, to compile an Ada application that uses the
27450 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27451 you simply issue the command
27453 @smallexample
27454 $ gnatmake my_ada_app -largs -lAPI
27455 @end smallexample
27457 @noindent
27458 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27459 tells the GNAT linker to look for an import library. The linker will
27460 look for a library name in this specific order:
27462 @enumerate
27463 @item @file{libAPI.dll.a}
27464 @item @file{API.dll.a}
27465 @item @file{libAPI.a}
27466 @item @file{API.lib}
27467 @item @file{libAPI.dll}
27468 @item @file{API.dll}
27469 @end enumerate
27471 The first three are the GNU style import libraries. The third is the
27472 Microsoft style import libraries. The last two are the DLL themself.
27474 Note that if the Ada package spec for @file{API.dll} contains the
27475 following pragma
27477 @smallexample @c ada
27478 pragma Linker_Options ("-lAPI");
27479 @end smallexample
27481 @noindent
27482 you do not have to add @option{-largs -lAPI} at the end of the
27483 @command{gnatmake} command.
27485 If any one of the items above is missing you will have to create it
27486 yourself. The following sections explain how to do so using as an
27487 example a fictitious DLL called @file{API.dll}.
27489 @node Creating an Ada Spec for the DLL Services
27490 @subsection Creating an Ada Spec for the DLL Services
27492 @noindent
27493 A DLL typically comes with a C/C++ header file which provides the
27494 definitions of the routines and variables exported by the DLL. The Ada
27495 equivalent of this header file is a package spec that contains definitions
27496 for the imported entities. If the DLL you intend to use does not come with
27497 an Ada spec you have to generate one such spec yourself. For example if
27498 the header file of @file{API.dll} is a file @file{api.h} containing the
27499 following two definitions:
27501 @smallexample
27502 @group
27503 @cartouche
27504 int some_var;
27505 int get (char *);
27506 @end cartouche
27507 @end group
27508 @end smallexample
27510 @noindent
27511 then the equivalent Ada spec could be:
27513 @smallexample @c ada
27514 @group
27515 @cartouche
27516 with Interfaces.C.Strings;
27517 package API is
27518    use Interfaces;
27520    Some_Var : C.int;
27521    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27523 private
27524    pragma Import (C, Get);
27525    pragma Import (DLL, Some_Var);
27526 end API;
27527 @end cartouche
27528 @end group
27529 @end smallexample
27531 @noindent
27532 Note that a variable is
27533 @strong{always imported with a DLL convention}. A function
27534 can have @code{C} or @code{Stdcall} convention.
27535 (@pxref{Windows Calling Conventions}).
27537 @node Creating an Import Library
27538 @subsection Creating an Import Library
27539 @cindex Import library
27541 @menu
27542 * The Definition File::
27543 * GNAT-Style Import Library::
27544 * Microsoft-Style Import Library::
27545 @end menu
27547 @noindent
27548 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27549 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27550 with @file{API.dll} you can skip this section. You can also skip this
27551 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27552 as in this case it is possible to link directly against the
27553 DLL. Otherwise read on.
27555 @node The Definition File
27556 @subsubsection The Definition File
27557 @cindex Definition file
27558 @findex .def
27560 @noindent
27561 As previously mentioned, and unlike Unix systems, the list of symbols
27562 that are exported from a DLL must be provided explicitly in Windows.
27563 The main goal of a definition file is precisely that: list the symbols
27564 exported by a DLL. A definition file (usually a file with a @code{.def}
27565 suffix) has the following structure:
27567 @smallexample
27568 @group
27569 @cartouche
27570 @r{[}LIBRARY @var{name}@r{]}
27571 @r{[}DESCRIPTION @var{string}@r{]}
27572 EXPORTS
27573    @var{symbol1}
27574    @var{symbol2}
27575    @dots{}
27576 @end cartouche
27577 @end group
27578 @end smallexample
27580 @table @code
27581 @item LIBRARY @var{name}
27582 This section, which is optional, gives the name of the DLL.
27584 @item DESCRIPTION @var{string}
27585 This section, which is optional, gives a description string that will be
27586 embedded in the import library.
27588 @item EXPORTS
27589 This section gives the list of exported symbols (procedures, functions or
27590 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27591 section of @file{API.def} looks like:
27593 @smallexample
27594 @group
27595 @cartouche
27596 EXPORTS
27597    some_var
27598    get
27599 @end cartouche
27600 @end group
27601 @end smallexample
27602 @end table
27604 @noindent
27605 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27606 (@pxref{Windows Calling Conventions}) for a Stdcall
27607 calling convention function in the exported symbols list.
27609 @noindent
27610 There can actually be other sections in a definition file, but these
27611 sections are not relevant to the discussion at hand.
27613 @node GNAT-Style Import Library
27614 @subsubsection GNAT-Style Import Library
27616 @noindent
27617 To create a static import library from @file{API.dll} with the GNAT tools
27618 you should proceed as follows:
27620 @enumerate
27621 @item
27622 Create the definition file @file{API.def} (@pxref{The Definition File}).
27623 For that use the @code{dll2def} tool as follows:
27625 @smallexample
27626 $ dll2def API.dll > API.def
27627 @end smallexample
27629 @noindent
27630 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27631 to standard output the list of entry points in the DLL. Note that if
27632 some routines in the DLL have the @code{Stdcall} convention
27633 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27634 suffix then you'll have to edit @file{api.def} to add it, and specify
27635 @option{-k} to @command{gnatdll} when creating the import library.
27637 @noindent
27638 Here are some hints to find the right @code{@@}@var{nn} suffix.
27640 @enumerate
27641 @item
27642 If you have the Microsoft import library (.lib), it is possible to get
27643 the right symbols by using Microsoft @code{dumpbin} tool (see the
27644 corresponding Microsoft documentation for further details).
27646 @smallexample
27647 $ dumpbin /exports api.lib
27648 @end smallexample
27650 @item
27651 If you have a message about a missing symbol at link time the compiler
27652 tells you what symbol is expected. You just have to go back to the
27653 definition file and add the right suffix.
27654 @end enumerate
27656 @item
27657 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27658 (@pxref{Using gnatdll}) as follows:
27660 @smallexample
27661 $ gnatdll -e API.def -d API.dll
27662 @end smallexample
27664 @noindent
27665 @code{gnatdll} takes as input a definition file @file{API.def} and the
27666 name of the DLL containing the services listed in the definition file
27667 @file{API.dll}. The name of the static import library generated is
27668 computed from the name of the definition file as follows: if the
27669 definition file name is @var{xyz}@code{.def}, the import library name will
27670 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27671 @option{-e} could have been removed because the name of the definition
27672 file (before the ``@code{.def}'' suffix) is the same as the name of the
27673 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27674 @end enumerate
27676 @node Microsoft-Style Import Library
27677 @subsubsection Microsoft-Style Import Library
27679 @noindent
27680 With GNAT you can either use a GNAT-style or Microsoft-style import
27681 library. A Microsoft import library is needed only if you plan to make an
27682 Ada DLL available to applications developed with Microsoft
27683 tools (@pxref{Mixed-Language Programming on Windows}).
27685 To create a Microsoft-style import library for @file{API.dll} you
27686 should proceed as follows:
27688 @enumerate
27689 @item
27690 Create the definition file @file{API.def} from the DLL. For this use either
27691 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27692 tool (see the corresponding Microsoft documentation for further details).
27694 @item
27695 Build the actual import library using Microsoft's @code{lib} utility:
27697 @smallexample
27698 $ lib -machine:IX86 -def:API.def -out:API.lib
27699 @end smallexample
27701 @noindent
27702 If you use the above command the definition file @file{API.def} must
27703 contain a line giving the name of the DLL:
27705 @smallexample
27706 LIBRARY      "API"
27707 @end smallexample
27709 @noindent
27710 See the Microsoft documentation for further details about the usage of
27711 @code{lib}.
27712 @end enumerate
27714 @node Building DLLs with GNAT Project files
27715 @section Building DLLs with GNAT Project files
27716 @cindex DLLs, building
27718 @noindent
27719 There is nothing specific to Windows in the build process.
27720 @pxref{Library Projects}.
27722 @noindent
27723 Due to a system limitation, it is not possible under Windows to create threads
27724 when inside the @code{DllMain} routine which is used for auto-initialization
27725 of shared libraries, so it is not possible to have library level tasks in SALs.
27727 @node Building DLLs with GNAT
27728 @section Building DLLs with GNAT
27729 @cindex DLLs, building
27731 @noindent
27732 This section explain how to build DLLs using the GNAT built-in DLL
27733 support. With the following procedure it is straight forward to build
27734 and use DLLs with GNAT.
27736 @enumerate
27738 @item building object files
27740 The first step is to build all objects files that are to be included
27741 into the DLL. This is done by using the standard @command{gnatmake} tool.
27743 @item building the DLL
27745 To build the DLL you must use @command{gcc}'s @option{-shared} and
27746 @option{-shared-libgcc} options. It is quite simple to use this method:
27748 @smallexample
27749 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
27750 @end smallexample
27752 It is important to note that in this case all symbols found in the
27753 object files are automatically exported. It is possible to restrict
27754 the set of symbols to export by passing to @command{gcc} a definition
27755 file, @pxref{The Definition File}. For example:
27757 @smallexample
27758 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
27759 @end smallexample
27761 If you use a definition file you must export the elaboration procedures
27762 for every package that required one. Elaboration procedures are named
27763 using the package name followed by "_E".
27765 @item preparing DLL to be used
27767 For the DLL to be used by client programs the bodies must be hidden
27768 from it and the .ali set with read-only attribute. This is very important
27769 otherwise GNAT will recompile all packages and will not actually use
27770 the code in the DLL. For example:
27772 @smallexample
27773 $ mkdir apilib
27774 $ copy *.ads *.ali api.dll apilib
27775 $ attrib +R apilib\*.ali
27776 @end smallexample
27778 @end enumerate
27780 At this point it is possible to use the DLL by directly linking
27781 against it. Note that you must use the GNAT shared runtime when using
27782 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27783 option.
27785 @smallexample
27786 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27787 @end smallexample
27789 @node Building DLLs with gnatdll
27790 @section Building DLLs with gnatdll
27791 @cindex DLLs, building
27793 @menu
27794 * Limitations When Using Ada DLLs from Ada::
27795 * Exporting Ada Entities::
27796 * Ada DLLs and Elaboration::
27797 * Ada DLLs and Finalization::
27798 * Creating a Spec for Ada DLLs::
27799 * Creating the Definition File::
27800 * Using gnatdll::
27801 @end menu
27803 @noindent
27804 Note that it is preferred to use GNAT Project files
27805 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27806 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27808 This section explains how to build DLLs containing Ada code using
27809 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27810 remainder of this section.
27812 The steps required to build an Ada DLL that is to be used by Ada as well as
27813 non-Ada applications are as follows:
27815 @enumerate
27816 @item
27817 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27818 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27819 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27820 skip this step if you plan to use the Ada DLL only from Ada applications.
27822 @item
27823 Your Ada code must export an initialization routine which calls the routine
27824 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27825 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27826 routine exported by the Ada DLL must be invoked by the clients of the DLL
27827 to initialize the DLL.
27829 @item
27830 When useful, the DLL should also export a finalization routine which calls
27831 routine @code{adafinal} generated by @command{gnatbind} to perform the
27832 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27833 The finalization routine exported by the Ada DLL must be invoked by the
27834 clients of the DLL when the DLL services are no further needed.
27836 @item
27837 You must provide a spec for the services exported by the Ada DLL in each
27838 of the programming languages to which you plan to make the DLL available.
27840 @item
27841 You must provide a definition file listing the exported entities
27842 (@pxref{The Definition File}).
27844 @item
27845 Finally you must use @code{gnatdll} to produce the DLL and the import
27846 library (@pxref{Using gnatdll}).
27847 @end enumerate
27849 @noindent
27850 Note that a relocatable DLL stripped using the @code{strip}
27851 binutils tool will not be relocatable anymore. To build a DLL without
27852 debug information pass @code{-largs -s} to @code{gnatdll}. This
27853 restriction does not apply to a DLL built using a Library Project.
27854 @pxref{Library Projects}.
27856 @node Limitations When Using Ada DLLs from Ada
27857 @subsection Limitations When Using Ada DLLs from Ada
27859 @noindent
27860 When using Ada DLLs from Ada applications there is a limitation users
27861 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27862 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27863 each Ada DLL includes the services of the GNAT run time that are necessary
27864 to the Ada code inside the DLL. As a result, when an Ada program uses an
27865 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27866 one in the main program.
27868 It is therefore not possible to exchange GNAT run-time objects between the
27869 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27870 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27871 types, etc.
27873 It is completely safe to exchange plain elementary, array or record types,
27874 Windows object handles, etc.
27876 @node Exporting Ada Entities
27877 @subsection Exporting Ada Entities
27878 @cindex Export table
27880 @noindent
27881 Building a DLL is a way to encapsulate a set of services usable from any
27882 application. As a result, the Ada entities exported by a DLL should be
27883 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27884 any Ada name mangling. As an example here is an Ada package
27885 @code{API}, spec and body, exporting two procedures, a function, and a
27886 variable:
27888 @smallexample @c ada
27889 @group
27890 @cartouche
27891 with Interfaces.C; use Interfaces;
27892 package API is
27893    Count : C.int := 0;
27894    function Factorial (Val : C.int) return C.int;
27896    procedure Initialize_API;
27897    procedure Finalize_API;
27898    --  Initialization & Finalization routines. More in the next section.
27899 private
27900    pragma Export (C, Initialize_API);
27901    pragma Export (C, Finalize_API);
27902    pragma Export (C, Count);
27903    pragma Export (C, Factorial);
27904 end API;
27905 @end cartouche
27906 @end group
27907 @end smallexample
27909 @smallexample @c ada
27910 @group
27911 @cartouche
27912 package body API is
27913    function Factorial (Val : C.int) return C.int is
27914       Fact : C.int := 1;
27915    begin
27916       Count := Count + 1;
27917       for K in 1 .. Val loop
27918          Fact := Fact * K;
27919       end loop;
27920       return Fact;
27921    end Factorial;
27923    procedure Initialize_API is
27924       procedure Adainit;
27925       pragma Import (C, Adainit);
27926    begin
27927       Adainit;
27928    end Initialize_API;
27930    procedure Finalize_API is
27931       procedure Adafinal;
27932       pragma Import (C, Adafinal);
27933    begin
27934       Adafinal;
27935    end Finalize_API;
27936 end API;
27937 @end cartouche
27938 @end group
27939 @end smallexample
27941 @noindent
27942 If the Ada DLL you are building will only be used by Ada applications
27943 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27944 convention. As an example, the previous package could be written as
27945 follows:
27947 @smallexample @c ada
27948 @group
27949 @cartouche
27950 package API is
27951    Count : Integer := 0;
27952    function Factorial (Val : Integer) return Integer;
27954    procedure Initialize_API;
27955    procedure Finalize_API;
27956    --  Initialization and Finalization routines.
27957 end API;
27958 @end cartouche
27959 @end group
27960 @end smallexample
27962 @smallexample @c ada
27963 @group
27964 @cartouche
27965 package body API is
27966    function Factorial (Val : Integer) return Integer is
27967       Fact : Integer := 1;
27968    begin
27969       Count := Count + 1;
27970       for K in 1 .. Val loop
27971          Fact := Fact * K;
27972       end loop;
27973       return Fact;
27974    end Factorial;
27976    @dots{}
27977    --  The remainder of this package body is unchanged.
27978 end API;
27979 @end cartouche
27980 @end group
27981 @end smallexample
27983 @noindent
27984 Note that if you do not export the Ada entities with a @code{C} or
27985 @code{Stdcall} convention you will have to provide the mangled Ada names
27986 in the definition file of the Ada DLL
27987 (@pxref{Creating the Definition File}).
27989 @node Ada DLLs and Elaboration
27990 @subsection Ada DLLs and Elaboration
27991 @cindex DLLs and elaboration
27993 @noindent
27994 The DLL that you are building contains your Ada code as well as all the
27995 routines in the Ada library that are needed by it. The first thing a
27996 user of your DLL must do is elaborate the Ada code
27997 (@pxref{Elaboration Order Handling in GNAT}).
27999 To achieve this you must export an initialization routine
28000 (@code{Initialize_API} in the previous example), which must be invoked
28001 before using any of the DLL services. This elaboration routine must call
28002 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28003 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28004 @code{Initialize_Api} for an example. Note that the GNAT binder is
28005 automatically invoked during the DLL build process by the @code{gnatdll}
28006 tool (@pxref{Using gnatdll}).
28008 When a DLL is loaded, Windows systematically invokes a routine called
28009 @code{DllMain}. It would therefore be possible to call @code{adainit}
28010 directly from @code{DllMain} without having to provide an explicit
28011 initialization routine. Unfortunately, it is not possible to call
28012 @code{adainit} from the @code{DllMain} if your program has library level
28013 tasks because access to the @code{DllMain} entry point is serialized by
28014 the system (that is, only a single thread can execute ``through'' it at a
28015 time), which means that the GNAT run time will deadlock waiting for the
28016 newly created task to complete its initialization.
28018 @node Ada DLLs and Finalization
28019 @subsection Ada DLLs and Finalization
28020 @cindex DLLs and finalization
28022 @noindent
28023 When the services of an Ada DLL are no longer needed, the client code should
28024 invoke the DLL finalization routine, if available. The DLL finalization
28025 routine is in charge of releasing all resources acquired by the DLL. In the
28026 case of the Ada code contained in the DLL, this is achieved by calling
28027 routine @code{adafinal} generated by the GNAT binder
28028 (@pxref{Binding with Non-Ada Main Programs}).
28029 See the body of @code{Finalize_Api} for an
28030 example. As already pointed out the GNAT binder is automatically invoked
28031 during the DLL build process by the @code{gnatdll} tool
28032 (@pxref{Using gnatdll}).
28034 @node Creating a Spec for Ada DLLs
28035 @subsection Creating a Spec for Ada DLLs
28037 @noindent
28038 To use the services exported by the Ada DLL from another programming
28039 language (e.g.@: C), you have to translate the specs of the exported Ada
28040 entities in that language. For instance in the case of @code{API.dll},
28041 the corresponding C header file could look like:
28043 @smallexample
28044 @group
28045 @cartouche
28046 extern int *_imp__count;
28047 #define count (*_imp__count)
28048 int factorial (int);
28049 @end cartouche
28050 @end group
28051 @end smallexample
28053 @noindent
28054 It is important to understand that when building an Ada DLL to be used by
28055 other Ada applications, you need two different specs for the packages
28056 contained in the DLL: one for building the DLL and the other for using
28057 the DLL. This is because the @code{DLL} calling convention is needed to
28058 use a variable defined in a DLL, but when building the DLL, the variable
28059 must have either the @code{Ada} or @code{C} calling convention. As an
28060 example consider a DLL comprising the following package @code{API}:
28062 @smallexample @c ada
28063 @group
28064 @cartouche
28065 package API is
28066    Count : Integer := 0;
28067    @dots{}
28068    --  Remainder of the package omitted.
28069 end API;
28070 @end cartouche
28071 @end group
28072 @end smallexample
28074 @noindent
28075 After producing a DLL containing package @code{API}, the spec that
28076 must be used to import @code{API.Count} from Ada code outside of the
28077 DLL is:
28079 @smallexample @c ada
28080 @group
28081 @cartouche
28082 package API is
28083    Count : Integer;
28084    pragma Import (DLL, Count);
28085 end API;
28086 @end cartouche
28087 @end group
28088 @end smallexample
28090 @node Creating the Definition File
28091 @subsection Creating the Definition File
28093 @noindent
28094 The definition file is the last file needed to build the DLL. It lists
28095 the exported symbols. As an example, the definition file for a DLL
28096 containing only package @code{API} (where all the entities are exported
28097 with a @code{C} calling convention) is:
28099 @smallexample
28100 @group
28101 @cartouche
28102 EXPORTS
28103     count
28104     factorial
28105     finalize_api
28106     initialize_api
28107 @end cartouche
28108 @end group
28109 @end smallexample
28111 @noindent
28112 If the @code{C} calling convention is missing from package @code{API},
28113 then the definition file contains the mangled Ada names of the above
28114 entities, which in this case are:
28116 @smallexample
28117 @group
28118 @cartouche
28119 EXPORTS
28120     api__count
28121     api__factorial
28122     api__finalize_api
28123     api__initialize_api
28124 @end cartouche
28125 @end group
28126 @end smallexample
28128 @node Using gnatdll
28129 @subsection Using @code{gnatdll}
28130 @findex gnatdll
28132 @menu
28133 * gnatdll Example::
28134 * gnatdll behind the Scenes::
28135 * Using dlltool::
28136 @end menu
28138 @noindent
28139 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28140 and non-Ada sources that make up your DLL have been compiled.
28141 @code{gnatdll} is actually in charge of two distinct tasks: build the
28142 static import library for the DLL and the actual DLL. The form of the
28143 @code{gnatdll} command is
28145 @smallexample
28146 @cartouche
28147 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28148 @c Expanding @ovar macro inline (explanation in macro def comments)
28149 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28150 @end cartouche
28151 @end smallexample
28153 @noindent
28154 where @var{list-of-files} is a list of ALI and object files. The object
28155 file list must be the exact list of objects corresponding to the non-Ada
28156 sources whose services are to be included in the DLL. The ALI file list
28157 must be the exact list of ALI files for the corresponding Ada sources
28158 whose services are to be included in the DLL. If @var{list-of-files} is
28159 missing, only the static import library is generated.
28161 @noindent
28162 You may specify any of the following switches to @code{gnatdll}:
28164 @table @code
28165 @c @item -a@ovar{address}
28166 @c Expanding @ovar macro inline (explanation in macro def comments)
28167 @item -a@r{[}@var{address}@r{]}
28168 @cindex @option{-a} (@code{gnatdll})
28169 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28170 specified the default address @var{0x11000000} will be used. By default,
28171 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28172 advise the reader to build relocatable DLL.
28174 @item -b @var{address}
28175 @cindex @option{-b} (@code{gnatdll})
28176 Set the relocatable DLL base address. By default the address is
28177 @code{0x11000000}.
28179 @item -bargs @var{opts}
28180 @cindex @option{-bargs} (@code{gnatdll})
28181 Binder options. Pass @var{opts} to the binder.
28183 @item -d @var{dllfile}
28184 @cindex @option{-d} (@code{gnatdll})
28185 @var{dllfile} is the name of the DLL. This switch must be present for
28186 @code{gnatdll} to do anything. The name of the generated import library is
28187 obtained algorithmically from @var{dllfile} as shown in the following
28188 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28189 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28190 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28191 as shown in the following example:
28192 if @var{dllfile} is @code{xyz.dll}, the definition
28193 file used is @code{xyz.def}.
28195 @item -e @var{deffile}
28196 @cindex @option{-e} (@code{gnatdll})
28197 @var{deffile} is the name of the definition file.
28199 @item -g
28200 @cindex @option{-g} (@code{gnatdll})
28201 Generate debugging information. This information is stored in the object
28202 file and copied from there to the final DLL file by the linker,
28203 where it can be read by the debugger. You must use the
28204 @option{-g} switch if you plan on using the debugger or the symbolic
28205 stack traceback.
28207 @item -h
28208 @cindex @option{-h} (@code{gnatdll})
28209 Help mode. Displays @code{gnatdll} switch usage information.
28211 @item -Idir
28212 @cindex @option{-I} (@code{gnatdll})
28213 Direct @code{gnatdll} to search the @var{dir} directory for source and
28214 object files needed to build the DLL.
28215 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28217 @item -k
28218 @cindex @option{-k} (@code{gnatdll})
28219 Removes the @code{@@}@var{nn} suffix from the import library's exported
28220 names, but keeps them for the link names. You must specify this
28221 option if you want to use a @code{Stdcall} function in a DLL for which
28222 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28223 of the Windows NT DLL for example. This option has no effect when
28224 @option{-n} option is specified.
28226 @item -l @var{file}
28227 @cindex @option{-l} (@code{gnatdll})
28228 The list of ALI and object files used to build the DLL are listed in
28229 @var{file}, instead of being given in the command line. Each line in
28230 @var{file} contains the name of an ALI or object file.
28232 @item -n
28233 @cindex @option{-n} (@code{gnatdll})
28234 No Import. Do not create the import library.
28236 @item -q
28237 @cindex @option{-q} (@code{gnatdll})
28238 Quiet mode. Do not display unnecessary messages.
28240 @item -v
28241 @cindex @option{-v} (@code{gnatdll})
28242 Verbose mode. Display extra information.
28244 @item -largs @var{opts}
28245 @cindex @option{-largs} (@code{gnatdll})
28246 Linker options. Pass @var{opts} to the linker.
28247 @end table
28249 @node gnatdll Example
28250 @subsubsection @code{gnatdll} Example
28252 @noindent
28253 As an example the command to build a relocatable DLL from @file{api.adb}
28254 once @file{api.adb} has been compiled and @file{api.def} created is
28256 @smallexample
28257 $ gnatdll -d api.dll api.ali
28258 @end smallexample
28260 @noindent
28261 The above command creates two files: @file{libapi.dll.a} (the import
28262 library) and @file{api.dll} (the actual DLL). If you want to create
28263 only the DLL, just type:
28265 @smallexample
28266 $ gnatdll -d api.dll -n api.ali
28267 @end smallexample
28269 @noindent
28270 Alternatively if you want to create just the import library, type:
28272 @smallexample
28273 $ gnatdll -d api.dll
28274 @end smallexample
28276 @node gnatdll behind the Scenes
28277 @subsubsection @code{gnatdll} behind the Scenes
28279 @noindent
28280 This section details the steps involved in creating a DLL. @code{gnatdll}
28281 does these steps for you. Unless you are interested in understanding what
28282 goes on behind the scenes, you should skip this section.
28284 We use the previous example of a DLL containing the Ada package @code{API},
28285 to illustrate the steps necessary to build a DLL. The starting point is a
28286 set of objects that will make up the DLL and the corresponding ALI
28287 files. In the case of this example this means that @file{api.o} and
28288 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28289 the following:
28291 @enumerate
28292 @item
28293 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28294 the information necessary to generate relocation information for the
28295 DLL.
28297 @smallexample
28298 @group
28299 $ gnatbind -n api
28300 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28301 @end group
28302 @end smallexample
28304 @noindent
28305 In addition to the base file, the @command{gnatlink} command generates an
28306 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28307 asks @command{gnatlink} to generate the routines @code{DllMain} and
28308 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28309 is loaded into memory.
28311 @item
28312 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28313 export table (@file{api.exp}). The export table contains the relocation
28314 information in a form which can be used during the final link to ensure
28315 that the Windows loader is able to place the DLL anywhere in memory.
28317 @smallexample
28318 @group
28319 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28320           --output-exp api.exp
28321 @end group
28322 @end smallexample
28324 @item
28325 @code{gnatdll} builds the base file using the new export table. Note that
28326 @command{gnatbind} must be called once again since the binder generated file
28327 has been deleted during the previous call to @command{gnatlink}.
28329 @smallexample
28330 @group
28331 $ gnatbind -n api
28332 $ gnatlink api -o api.jnk api.exp -mdll
28333       -Wl,--base-file,api.base
28334 @end group
28335 @end smallexample
28337 @item
28338 @code{gnatdll} builds the new export table using the new base file and
28339 generates the DLL import library @file{libAPI.dll.a}.
28341 @smallexample
28342 @group
28343 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28344           --output-exp api.exp --output-lib libAPI.a
28345 @end group
28346 @end smallexample
28348 @item
28349 Finally @code{gnatdll} builds the relocatable DLL using the final export
28350 table.
28352 @smallexample
28353 @group
28354 $ gnatbind -n api
28355 $ gnatlink api api.exp -o api.dll -mdll
28356 @end group
28357 @end smallexample
28358 @end enumerate
28360 @node Using dlltool
28361 @subsubsection Using @code{dlltool}
28363 @noindent
28364 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28365 DLLs and static import libraries. This section summarizes the most
28366 common @code{dlltool} switches. The form of the @code{dlltool} command
28369 @smallexample
28370 @c $ dlltool @ovar{switches}
28371 @c Expanding @ovar macro inline (explanation in macro def comments)
28372 $ dlltool @r{[}@var{switches}@r{]}
28373 @end smallexample
28375 @noindent
28376 @code{dlltool} switches include:
28378 @table @option
28379 @item --base-file @var{basefile}
28380 @cindex @option{--base-file} (@command{dlltool})
28381 Read the base file @var{basefile} generated by the linker. This switch
28382 is used to create a relocatable DLL.
28384 @item --def @var{deffile}
28385 @cindex @option{--def} (@command{dlltool})
28386 Read the definition file.
28388 @item --dllname @var{name}
28389 @cindex @option{--dllname} (@command{dlltool})
28390 Gives the name of the DLL. This switch is used to embed the name of the
28391 DLL in the static import library generated by @code{dlltool} with switch
28392 @option{--output-lib}.
28394 @item -k
28395 @cindex @option{-k} (@command{dlltool})
28396 Kill @code{@@}@var{nn} from exported names
28397 (@pxref{Windows Calling Conventions}
28398 for a discussion about @code{Stdcall}-style symbols.
28400 @item --help
28401 @cindex @option{--help} (@command{dlltool})
28402 Prints the @code{dlltool} switches with a concise description.
28404 @item --output-exp @var{exportfile}
28405 @cindex @option{--output-exp} (@command{dlltool})
28406 Generate an export file @var{exportfile}. The export file contains the
28407 export table (list of symbols in the DLL) and is used to create the DLL.
28409 @item --output-lib @var{libfile}
28410 @cindex @option{--output-lib} (@command{dlltool})
28411 Generate a static import library @var{libfile}.
28413 @item -v
28414 @cindex @option{-v} (@command{dlltool})
28415 Verbose mode.
28417 @item --as @var{assembler-name}
28418 @cindex @option{--as} (@command{dlltool})
28419 Use @var{assembler-name} as the assembler. The default is @code{as}.
28420 @end table
28422 @node GNAT and Windows Resources
28423 @section GNAT and Windows Resources
28424 @cindex Resources, windows
28426 @menu
28427 * Building Resources::
28428 * Compiling Resources::
28429 * Using Resources::
28430 @end menu
28432 @noindent
28433 Resources are an easy way to add Windows specific objects to your
28434 application. The objects that can be added as resources include:
28436 @itemize @bullet
28437 @item
28438 menus
28440 @item
28441 accelerators
28443 @item
28444 dialog boxes
28446 @item
28447 string tables
28449 @item
28450 bitmaps
28452 @item
28453 cursors
28455 @item
28456 icons
28458 @item
28459 fonts
28460 @end itemize
28462 @noindent
28463 This section explains how to build, compile and use resources.
28465 @node Building Resources
28466 @subsection Building Resources
28467 @cindex Resources, building
28469 @noindent
28470 A resource file is an ASCII file. By convention resource files have an
28471 @file{.rc} extension.
28472 The easiest way to build a resource file is to use Microsoft tools
28473 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28474 @code{dlgedit.exe} to build dialogs.
28475 It is always possible to build an @file{.rc} file yourself by writing a
28476 resource script.
28478 It is not our objective to explain how to write a resource file. A
28479 complete description of the resource script language can be found in the
28480 Microsoft documentation.
28482 @node Compiling Resources
28483 @subsection Compiling Resources
28484 @findex rc
28485 @findex windres
28486 @cindex Resources, compiling
28488 @noindent
28489 This section describes how to build a GNAT-compatible (COFF) object file
28490 containing the resources. This is done using the Resource Compiler
28491 @code{windres} as follows:
28493 @smallexample
28494 $ windres -i myres.rc -o myres.o
28495 @end smallexample
28497 @noindent
28498 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28499 file. You can specify an alternate preprocessor (usually named
28500 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28501 parameter. A list of all possible options may be obtained by entering
28502 the command @code{windres} @option{--help}.
28504 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28505 to produce a @file{.res} file (binary resource file). See the
28506 corresponding Microsoft documentation for further details. In this case
28507 you need to use @code{windres} to translate the @file{.res} file to a
28508 GNAT-compatible object file as follows:
28510 @smallexample
28511 $ windres -i myres.res -o myres.o
28512 @end smallexample
28514 @node Using Resources
28515 @subsection Using Resources
28516 @cindex Resources, using
28518 @noindent
28519 To include the resource file in your program just add the
28520 GNAT-compatible object file for the resource(s) to the linker
28521 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28522 option:
28524 @smallexample
28525 $ gnatmake myprog -largs myres.o
28526 @end smallexample
28528 @node Debugging a DLL
28529 @section Debugging a DLL
28530 @cindex DLL debugging
28532 @menu
28533 * Program and DLL Both Built with GCC/GNAT::
28534 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28535 @end menu
28537 @noindent
28538 Debugging a DLL is similar to debugging a standard program. But
28539 we have to deal with two different executable parts: the DLL and the
28540 program that uses it. We have the following four possibilities:
28542 @enumerate 1
28543 @item
28544 The program and the DLL are built with @code{GCC/GNAT}.
28545 @item
28546 The program is built with foreign tools and the DLL is built with
28547 @code{GCC/GNAT}.
28548 @item
28549 The program is built with @code{GCC/GNAT} and the DLL is built with
28550 foreign tools.
28551 @end enumerate
28553 @noindent
28554 In this section we address only cases one and two above.
28555 There is no point in trying to debug
28556 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28557 information in it. To do so you must use a debugger compatible with the
28558 tools suite used to build the DLL.
28560 @node Program and DLL Both Built with GCC/GNAT
28561 @subsection Program and DLL Both Built with GCC/GNAT
28563 @noindent
28564 This is the simplest case. Both the DLL and the program have @code{GDB}
28565 compatible debugging information. It is then possible to break anywhere in
28566 the process. Let's suppose here that the main procedure is named
28567 @code{ada_main} and that in the DLL there is an entry point named
28568 @code{ada_dll}.
28570 @noindent
28571 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28572 program must have been built with the debugging information (see GNAT -g
28573 switch). Here are the step-by-step instructions for debugging it:
28575 @enumerate 1
28576 @item Launch @code{GDB} on the main program.
28578 @smallexample
28579 $ gdb -nw ada_main
28580 @end smallexample
28582 @item Start the program and stop at the beginning of the main procedure
28584 @smallexample
28585 (gdb) start
28586 @end smallexample
28588 @noindent
28589 This step is required to be able to set a breakpoint inside the DLL. As long
28590 as the program is not run, the DLL is not loaded. This has the
28591 consequence that the DLL debugging information is also not loaded, so it is not
28592 possible to set a breakpoint in the DLL.
28594 @item Set a breakpoint inside the DLL
28596 @smallexample
28597 (gdb) break ada_dll
28598 (gdb) cont
28599 @end smallexample
28601 @end enumerate
28603 @noindent
28604 At this stage a breakpoint is set inside the DLL. From there on
28605 you can use the standard approach to debug the whole program
28606 (@pxref{Running and Debugging Ada Programs}).
28608 @ignore
28609 @c This used to work, probably because the DLLs were non-relocatable
28610 @c keep this section around until the problem is sorted out.
28612 To break on the @code{DllMain} routine it is not possible to follow
28613 the procedure above. At the time the program stop on @code{ada_main}
28614 the @code{DllMain} routine as already been called. Either you can use
28615 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28617 @enumerate 1
28618 @item Launch @code{GDB} on the main program.
28620 @smallexample
28621 $ gdb ada_main
28622 @end smallexample
28624 @item Load DLL symbols
28626 @smallexample
28627 (gdb) add-sym api.dll
28628 @end smallexample
28630 @item Set a breakpoint inside the DLL
28632 @smallexample
28633 (gdb) break ada_dll.adb:45
28634 @end smallexample
28636 Note that at this point it is not possible to break using the routine symbol
28637 directly as the program is not yet running. The solution is to break
28638 on the proper line (break in @file{ada_dll.adb} line 45).
28640 @item Start the program
28642 @smallexample
28643 (gdb) run
28644 @end smallexample
28646 @end enumerate
28647 @end ignore
28649 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28650 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28652 @menu
28653 * Debugging the DLL Directly::
28654 * Attaching to a Running Process::
28655 @end menu
28657 @noindent
28658 In this case things are slightly more complex because it is not possible to
28659 start the main program and then break at the beginning to load the DLL and the
28660 associated DLL debugging information. It is not possible to break at the
28661 beginning of the program because there is no @code{GDB} debugging information,
28662 and therefore there is no direct way of getting initial control. This
28663 section addresses this issue by describing some methods that can be used
28664 to break somewhere in the DLL to debug it.
28666 @noindent
28667 First suppose that the main procedure is named @code{main} (this is for
28668 example some C code built with Microsoft Visual C) and that there is a
28669 DLL named @code{test.dll} containing an Ada entry point named
28670 @code{ada_dll}.
28672 @noindent
28673 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28674 been built with debugging information (see GNAT -g option).
28676 @node Debugging the DLL Directly
28677 @subsubsection Debugging the DLL Directly
28679 @enumerate 1
28680 @item
28681 Find out the executable starting address
28683 @smallexample
28684 $ objdump --file-header main.exe
28685 @end smallexample
28687 The starting address is reported on the last line. For example:
28689 @smallexample
28690 main.exe:     file format pei-i386
28691 architecture: i386, flags 0x0000010a:
28692 EXEC_P, HAS_DEBUG, D_PAGED
28693 start address 0x00401010
28694 @end smallexample
28696 @item
28697 Launch the debugger on the executable.
28699 @smallexample
28700 $ gdb main.exe
28701 @end smallexample
28703 @item
28704 Set a breakpoint at the starting address, and launch the program.
28706 @smallexample
28707 $ (gdb) break *0x00401010
28708 $ (gdb) run
28709 @end smallexample
28711 The program will stop at the given address.
28713 @item
28714 Set a breakpoint on a DLL subroutine.
28716 @smallexample
28717 (gdb) break ada_dll.adb:45
28718 @end smallexample
28720 Or if you want to break using a symbol on the DLL, you need first to
28721 select the Ada language (language used by the DLL).
28723 @smallexample
28724 (gdb) set language ada
28725 (gdb) break ada_dll
28726 @end smallexample
28728 @item
28729 Continue the program.
28731 @smallexample
28732 (gdb) cont
28733 @end smallexample
28735 @noindent
28736 This will run the program until it reaches the breakpoint that has been
28737 set. From that point you can use the standard way to debug a program
28738 as described in (@pxref{Running and Debugging Ada Programs}).
28740 @end enumerate
28742 @noindent
28743 It is also possible to debug the DLL by attaching to a running process.
28745 @node Attaching to a Running Process
28746 @subsubsection Attaching to a Running Process
28747 @cindex DLL debugging, attach to process
28749 @noindent
28750 With @code{GDB} it is always possible to debug a running process by
28751 attaching to it. It is possible to debug a DLL this way. The limitation
28752 of this approach is that the DLL must run long enough to perform the
28753 attach operation. It may be useful for instance to insert a time wasting
28754 loop in the code of the DLL to meet this criterion.
28756 @enumerate 1
28758 @item Launch the main program @file{main.exe}.
28760 @smallexample
28761 $ main
28762 @end smallexample
28764 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28765 that the process PID for @file{main.exe} is 208.
28767 @item Launch gdb.
28769 @smallexample
28770 $ gdb
28771 @end smallexample
28773 @item Attach to the running process to be debugged.
28775 @smallexample
28776 (gdb) attach 208
28777 @end smallexample
28779 @item Load the process debugging information.
28781 @smallexample
28782 (gdb) symbol-file main.exe
28783 @end smallexample
28785 @item Break somewhere in the DLL.
28787 @smallexample
28788 (gdb) break ada_dll
28789 @end smallexample
28791 @item Continue process execution.
28793 @smallexample
28794 (gdb) cont
28795 @end smallexample
28797 @end enumerate
28799 @noindent
28800 This last step will resume the process execution, and stop at
28801 the breakpoint we have set. From there you can use the standard
28802 approach to debug a program as described in
28803 (@pxref{Running and Debugging Ada Programs}).
28805 @node Setting Stack Size from gnatlink
28806 @section Setting Stack Size from @command{gnatlink}
28808 @noindent
28809 It is possible to specify the program stack size at link time. On modern
28810 versions of Windows, starting with XP, this is mostly useful to set the size of
28811 the main stack (environment task). The other task stacks are set with pragma
28812 Storage_Size or with the @command{gnatbind -d} command.
28814 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28815 reserve size of individual tasks, the link-time stack size applies to all
28816 tasks, and pragma Storage_Size has no effect.
28817 In particular, Stack Overflow checks are made against this
28818 link-time specified size.
28820 This setting can be done with
28821 @command{gnatlink} using either:
28823 @itemize @bullet
28825 @item using @option{-Xlinker} linker option
28827 @smallexample
28828 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28829 @end smallexample
28831 This sets the stack reserve size to 0x10000 bytes and the stack commit
28832 size to 0x1000 bytes.
28834 @item using @option{-Wl} linker option
28836 @smallexample
28837 $ gnatlink hello -Wl,--stack=0x1000000
28838 @end smallexample
28840 This sets the stack reserve size to 0x1000000 bytes. Note that with
28841 @option{-Wl} option it is not possible to set the stack commit size
28842 because the coma is a separator for this option.
28844 @end itemize
28846 @node Setting Heap Size from gnatlink
28847 @section Setting Heap Size from @command{gnatlink}
28849 @noindent
28850 Under Windows systems, it is possible to specify the program heap size from
28851 @command{gnatlink} using either:
28853 @itemize @bullet
28855 @item using @option{-Xlinker} linker option
28857 @smallexample
28858 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28859 @end smallexample
28861 This sets the heap reserve size to 0x10000 bytes and the heap commit
28862 size to 0x1000 bytes.
28864 @item using @option{-Wl} linker option
28866 @smallexample
28867 $ gnatlink hello -Wl,--heap=0x1000000
28868 @end smallexample
28870 This sets the heap reserve size to 0x1000000 bytes. Note that with
28871 @option{-Wl} option it is not possible to set the heap commit size
28872 because the coma is a separator for this option.
28874 @end itemize
28876 @end ifset
28878 @c **********************************
28879 @c * GNU Free Documentation License *
28880 @c **********************************
28881 @include fdl.texi
28882 @c GNU Free Documentation License
28884 @node Index,,GNU Free Documentation License, Top
28885 @unnumbered Index
28887 @printindex cp
28889 @contents
28890 @c Put table of contents at end, otherwise it precedes the "title page" in
28891 @c the .txt version
28892 @c Edit the pdf file to move the contents to the beginning, after the title
28893 @c page
28895 @bye