2013-04-11 Robert Dewar <dewar@adacore.com>
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blobad48a2193f09a163a4aa4209c3de6c57e89b9a28
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-2013, Free Software Foundation, Inc.          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 @set TITLESUFFIX
98 @end ifset
100 @ifset vms
101 @set PLATFORM OpenVMS
102 @set TITLESUFFIX for OpenVMS
103 @end ifset
105 @c @ovar(ARG)
106 @c ----------
107 @c The ARG is an optional argument.  To be used for macro arguments in
108 @c their documentation (@defmac).
109 @macro ovar{varname}
110 @r{[}@var{\varname\}@r{]}@c
111 @end macro
112 @c Status as of November 2009:
113 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
114 @c differently, and faulty output is produced by one or the other
115 @c depending on whether the "@c" is present or absent.
116 @c As a result, the @ovar macro is not used, and all invocations
117 @c of the @ovar macro have been expanded inline.
120 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
121 @dircategory GNU Ada tools
122 @direntry
123 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
124 @end direntry
126 @include gcc-common.texi
128 @setchapternewpage odd
129 @syncodeindex fn cp
130 @c %**end of header
132 @titlepage
133 @title @value{EDITION} User's Guide
134 @ifset vms
135 @sp 1
136 @flushright
137 @titlefont{@i{@value{PLATFORM}}}
138 @end flushright
139 @end ifset
141 @sp 2
143 @subtitle GNAT, The GNU Ada Compiler
144 @versionsubtitle
145 @author AdaCore
147 @page
148 @vskip 0pt plus 1filll
150 @insertcopying
152 @end titlepage
154 @ifnottex
155 @node Top, About This Guide, (dir), (dir)
156 @top @value{EDITION} User's Guide
158 @noindent
159 @value{EDITION} User's Guide @value{PLATFORM}
161 @noindent
162 GNAT, The GNU Ada Compiler@*
163 GCC version @value{version-GCC}@*
165 @noindent
166 AdaCore@*
168 @menu
169 * About This Guide::
170 * Getting Started with GNAT::
171 * The GNAT Compilation Model::
172 * Compiling Using gcc::
173 * Binding Using gnatbind::
174 * Linking Using gnatlink::
175 * The GNAT Make Program gnatmake::
176 * Improving Performance::
177 * Renaming Files Using gnatchop::
178 * Configuration Pragmas::
179 * Handling Arbitrary File Naming Conventions Using gnatname::
180 * GNAT Project Manager::
181 * Tools Supporting Project Files::
182 * The Cross-Referencing Tools gnatxref and gnatfind::
183 * The GNAT Pretty-Printer gnatpp::
184 * The GNAT Metric Tool gnatmetric::
185 * File Name Krunching Using gnatkr::
186 * Preprocessing Using gnatprep::
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Memory Management Issues::
194 * Stack Related Facilities::
195 * Verifying Properties Using gnatcheck::
196 * Creating Sample Bodies Using gnatstub::
197 * Creating Unit Tests Using gnattest::
198 * Performing Dimensionality Analysis in GNAT::
199 * Generating Ada Bindings for C and C++ headers::
200 * Other Utility Programs::
201 * Running and Debugging Ada Programs::
202 @ifclear vms
203 * Code Coverage and Profiling::
204 @end ifclear
205 @ifset vms
206 * Compatibility with HP Ada::
207 @end ifset
208 * Platform-Specific Information for the Run-Time Libraries::
209 * Example of Binder Output File::
210 * Elaboration Order Handling in GNAT::
211 * Overflow Check Handling in GNAT::
212 * Conditional Compilation::
213 * Inline Assembler::
214 * Compatibility and Porting Guide::
215 @ifset unw
216 * Microsoft Windows Topics::
217 * Mac OS Topics::
218 @end ifset
219 * GNU Free Documentation License::
220 * Index::
222  --- The Detailed Node Listing ---
224 About This Guide
226 * What This Guide Contains::
227 * What You Should Know before Reading This Guide::
228 * Related Information::
229 * Conventions::
231 Getting Started with GNAT
233 * Running GNAT::
234 * Running a Simple Ada Program::
235 * Running a Program with Multiple Units::
236 * Using the gnatmake Utility::
237 @ifset vms
238 * Editing with Emacs::
239 @end ifset
240 @ifclear vms
241 * Introduction to GPS::
242 @end ifclear
244 The GNAT Compilation Model
246 * Source Representation::
247 * Foreign Language Representation::
248 * File Naming Rules::
249 * Using Other File Names::
250 * Alternative File Naming Schemes::
251 * Generating Object Files::
252 * Source Dependencies::
253 * The Ada Library Information Files::
254 * Binding an Ada Program::
255 * Mixed Language Programming::
256 @ifclear vms
257 * Building Mixed Ada & C++ Programs::
258 * Comparison between GNAT and C/C++ Compilation Models::
259 @end ifclear
260 * Comparison between GNAT and Conventional Ada Library Models::
261 @ifset vms
262 * Placement of temporary files::
263 @end ifset
265 Foreign Language Representation
267 * Latin-1::
268 * Other 8-Bit Codes::
269 * Wide Character Encodings::
271 Compiling Ada Programs With gcc
273 * Compiling Programs::
274 * Switches for gcc::
275 * Search Paths and the Run-Time Library (RTL)::
276 * Order of Compilation Issues::
277 * Examples::
279 Switches for gcc
281 * Output and Error Message Control::
282 * Warning Message Control::
283 * Debugging and Assertion Control::
284 * Validity Checking::
285 * Style Checking::
286 * Run-Time Checks::
287 * Using gcc for Syntax Checking::
288 * Using gcc for Semantic Checking::
289 * Compiling Different Versions of Ada::
290 * Character Set Control::
291 * File Naming Control::
292 * Subprogram Inlining Control::
293 * Auxiliary Output Control::
294 * Debugging Control::
295 * Exception Handling Control::
296 * Units to Sources Mapping Files::
297 * Integrated Preprocessing::
298 @ifset vms
299 * Return Codes::
300 @end ifset
302 Binding Ada Programs With gnatbind
304 * Running gnatbind::
305 * Switches for gnatbind::
306 * Command-Line Access::
307 * Search Paths for gnatbind::
308 * Examples of gnatbind Usage::
310 Switches for gnatbind
312 * Consistency-Checking Modes::
313 * Binder Error Message Control::
314 * Elaboration Control::
315 * Output Control::
316 * Binding with Non-Ada Main Programs::
317 * Binding Programs with No Main Subprogram::
319 Linking Using gnatlink
321 * Running gnatlink::
322 * Switches for gnatlink::
324 The GNAT Make Program gnatmake
326 * Running gnatmake::
327 * Switches for gnatmake::
328 * Mode Switches for gnatmake::
329 * Notes on the Command Line::
330 * How gnatmake Works::
331 * Examples of gnatmake Usage::
333 Improving Performance
334 * Performance Considerations::
335 * Text_IO Suggestions::
336 * Reducing Size of Ada Executables with gnatelim::
337 * Reducing Size of Executables with unused subprogram/data elimination::
339 Performance Considerations
340 * Controlling Run-Time Checks::
341 * Use of Restrictions::
342 * Optimization Levels::
343 * Debugging Optimized Code::
344 * Inlining of Subprograms::
345 * Vectorization of loops::
346 * Other Optimization Switches::
347 * Optimization and Strict Aliasing::
348 @ifset vms
349 * Coverage Analysis::
350 @end ifset
352 Reducing Size of Ada Executables with gnatelim
353 * About gnatelim::
354 * Running gnatelim::
355 * Processing Precompiled Libraries::
356 * Correcting the List of Eliminate Pragmas::
357 * Making Your Executables Smaller::
358 * Summary of the gnatelim Usage Cycle::
360 Reducing Size of Executables with unused subprogram/data elimination
361 * About unused subprogram/data elimination::
362 * Compilation options::
364 Renaming Files Using gnatchop
366 * Handling Files with Multiple Units::
367 * Operating gnatchop in Compilation Mode::
368 * Command Line for gnatchop::
369 * Switches for gnatchop::
370 * Examples of gnatchop Usage::
372 Configuration Pragmas
374 * Handling of Configuration Pragmas::
375 * The Configuration Pragmas Files::
377 Handling Arbitrary File Naming Conventions Using gnatname
379 * Arbitrary File Naming Conventions::
380 * Running gnatname::
381 * Switches for gnatname::
382 * Examples of gnatname Usage::
384 The Cross-Referencing Tools gnatxref and gnatfind
386 * Switches for gnatxref::
387 * Switches for gnatfind::
388 * Project Files for gnatxref and gnatfind::
389 * Regular Expressions in gnatfind and gnatxref::
390 * Examples of gnatxref Usage::
391 * Examples of gnatfind Usage::
393 The GNAT Pretty-Printer gnatpp
395 * Switches for gnatpp::
396 * Formatting Rules::
398 The GNAT Metrics Tool gnatmetric
400 * Switches for gnatmetric::
402 File Name Krunching Using gnatkr
404 * About gnatkr::
405 * Using gnatkr::
406 * Krunching Method::
407 * Examples of gnatkr Usage::
409 Preprocessing Using gnatprep
410 * Preprocessing Symbols::
411 * Using gnatprep::
412 * Switches for gnatprep::
413 * Form of Definitions File::
414 * Form of Input Text for gnatprep::
416 The GNAT Library Browser gnatls
418 * Running gnatls::
419 * Switches for gnatls::
420 * Examples of gnatls Usage::
422 Cleaning Up Using gnatclean
424 * Running gnatclean::
425 * Switches for gnatclean::
426 @c * Examples of gnatclean Usage::
428 @ifclear vms
430 GNAT and Libraries
432 * Introduction to Libraries in GNAT::
433 * General Ada Libraries::
434 * Stand-alone Ada Libraries::
435 * Rebuilding the GNAT Run-Time Library::
437 Using the GNU make Utility
439 * Using gnatmake in a Makefile::
440 * Automatically Creating a List of Directories::
441 * Generating the Command Line Switches::
442 * Overcoming Command Line Length Limits::
443 @end ifclear
445 Memory Management Issues
447 * Some Useful Memory Pools::
448 * The GNAT Debug Pool Facility::
449 @ifclear vms
450 * The gnatmem Tool::
451 @end ifclear
453 Stack Related Facilities
455 * Stack Overflow Checking::
456 * Static Stack Usage Analysis::
457 * Dynamic Stack Usage Analysis::
459 Some Useful Memory Pools
461 The GNAT Debug Pool Facility
463 @ifclear vms
464 The gnatmem Tool
466 * Running gnatmem::
467 * Switches for gnatmem::
468 * Example of gnatmem Usage::
469 @end ifclear
471 Verifying Properties Using gnatcheck
473 Sample Bodies Using gnatstub
475 * Running gnatstub::
476 * Switches for gnatstub::
478 Creating Unit Tests Using gnattest
480 * Running gnattest::
481 * Switches for gnattest::
482 * Project Attributes for gnattest::
483 * Simple Example::
484 * Setting Up and Tearing Down the Testing Environment::
485 * Regenerating Tests::
486 * Default Test Behavior::
487 * Testing Primitive Operations of Tagged Types::
488 * Testing Inheritance::
489 * Tagged Types Substitutability Testing::
490 * Testing with Contracts::
491 * Additional Tests::
492 @ifclear vms
493 * Support for other platforms/run-times::
494 @end ifclear
495 * Current Limitations::
497 Other Utility Programs
499 * Using Other Utility Programs with GNAT::
500 * The External Symbol Naming Scheme of GNAT::
501 * Converting Ada Files to html with gnathtml::
503 @ifclear vms
504 Code Coverage and Profiling
506 * Code Coverage of Ada Programs using gcov::
507 * Profiling an Ada Program using gprof::
508 @end ifclear
510 Running and Debugging Ada Programs
512 * The GNAT Debugger GDB::
513 * Running GDB::
514 * Introduction to GDB Commands::
515 * Using Ada Expressions::
516 * Calling User-Defined Subprograms::
517 * Using the Next Command in a Function::
518 * Ada Exceptions::
519 * Ada Tasks::
520 * Debugging Generic Units::
521 * Remote Debugging using gdbserver::
522 * GNAT Abnormal Termination or Failure to Terminate::
523 * Naming Conventions for GNAT Source Files::
524 * Getting Internal Debugging Information::
525 * Stack Traceback::
527 @ifset vms
528 * LSE::
529 @end ifset
531 @ifset vms
532 Compatibility with HP Ada
534 * Ada Language Compatibility::
535 * Differences in the Definition of Package System::
536 * Language-Related Features::
537 * The Package STANDARD::
538 * The Package SYSTEM::
539 * Tasking and Task-Related Features::
540 * Pragmas and Pragma-Related Features::
541 * Library of Predefined Units::
542 * Bindings::
543 * Main Program Definition::
544 * Implementation-Defined Attributes::
545 * Compiler and Run-Time Interfacing::
546 * Program Compilation and Library Management::
547 * Input-Output::
548 * Implementation Limits::
549 * Tools and Utilities::
551 Language-Related Features
553 * Integer Types and Representations::
554 * Floating-Point Types and Representations::
555 * Pragmas Float_Representation and Long_Float::
556 * Fixed-Point Types and Representations::
557 * Record and Array Component Alignment::
558 * Address Clauses::
559 * Other Representation Clauses::
561 Tasking and Task-Related Features
563 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
564 * Assigning Task IDs::
565 * Task IDs and Delays::
566 * Task-Related Pragmas::
567 * Scheduling and Task Priority::
568 * The Task Stack::
569 * External Interrupts::
571 Pragmas and Pragma-Related Features
573 * Restrictions on the Pragma INLINE::
574 * Restrictions on the Pragma INTERFACE::
575 * Restrictions on the Pragma SYSTEM_NAME::
577 Library of Predefined Units
579 * Changes to DECLIB::
581 Bindings
583 * Shared Libraries and Options Files::
584 * Interfaces to C::
585 @end ifset
587 Platform-Specific Information for the Run-Time Libraries
589 * Summary of Run-Time Configurations::
590 * Specifying a Run-Time Library::
591 * Choosing the Scheduling Policy::
592 * Solaris-Specific Considerations::
593 * Linux-Specific Considerations::
594 * AIX-Specific Considerations::
595 * RTX-Specific Considerations::
596 * HP-UX-Specific Considerations::
598 Example of Binder Output File
600 Elaboration Order Handling in GNAT
602 * Elaboration Code::
603 * Checking the Elaboration Order::
604 * Controlling the Elaboration Order::
605 * Controlling Elaboration in GNAT - Internal Calls::
606 * Controlling Elaboration in GNAT - External Calls::
607 * Default Behavior in GNAT - Ensuring Safety::
608 * Treatment of Pragma Elaborate::
609 * Elaboration Issues for Library Tasks::
610 * Mixing Elaboration Models::
611 * What to Do If the Default Elaboration Behavior Fails::
612 * Elaboration for Dispatching Calls::
613 * Summary of Procedures for Elaboration Control::
614 * Other Elaboration Order Considerations::
616 Overflow Check Handling in GNAT
617 * Background::
618 * Overflow Checking Modes in GNAT::
619 * Specifying the Desired Mode::
620 * Default Settings::
621 * Implementation Notes::
623 Conditional Compilation
624 * Use of Boolean Constants::
625 * Debugging - A Special Case::
626 * Conditionalizing Declarations::
627 * Use of Alternative Implementations::
628 * Preprocessing::
630 Inline Assembler
632 * Basic Assembler Syntax::
633 * A Simple Example of Inline Assembler::
634 * Output Variables in Inline Assembler::
635 * Input Variables in Inline Assembler::
636 * Inlining Inline Assembler Code::
637 * Other Asm Functionality::
639 Compatibility and Porting Guide
641 * Compatibility with Ada 83::
642 * Compatibility between Ada 95 and Ada 2005::
643 * Implementation-dependent characteristics::
644 @ifclear vms
645 @c This brief section is only in the non-VMS version
646 @c The complete chapter on HP Ada issues is in the VMS version
647 * Compatibility with HP Ada 83::
648 @end ifclear
649 * Compatibility with Other Ada Systems::
650 * Representation Clauses::
651 @ifset vms
652 * Transitioning to 64-Bit GNAT for OpenVMS::
653 @end ifset
655 @ifset unw
656 Microsoft Windows Topics
658 * Using GNAT on Windows::
659 * CONSOLE and WINDOWS subsystems::
660 * Temporary Files::
661 * Mixed-Language Programming on Windows::
662 * Windows Calling Conventions::
663 * Introduction to Dynamic Link Libraries (DLLs)::
664 * Using DLLs with GNAT::
665 * Building DLLs with GNAT::
666 * GNAT and Windows Resources::
667 * Debugging a DLL::
668 * Setting Stack Size from gnatlink::
669 * Setting Heap Size from gnatlink::
671 Mac OS Topics
673 * Codesigning the Debugger::
674 @end ifset
676 * Index::
677 @end menu
678 @end ifnottex
680 @node About This Guide
681 @unnumbered About This Guide
683 @noindent
684 @ifset vms
685 This guide describes the use of @value{EDITION},
686 a compiler and software development toolset for the full Ada
687 programming language, implemented on OpenVMS for HP's Alpha and
688 Integrity server (I64) platforms.
689 @end ifset
690 @ifclear vms
691 This guide describes the use of @value{EDITION},
692 a compiler and software development
693 toolset for the full Ada programming language.
694 @end ifclear
695 It documents the features of the compiler and tools, and explains
696 how to use them to build Ada applications.
698 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
699 Ada 83 compatibility mode.
700 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
701 but you can override with a compiler switch
702 (@pxref{Compiling Different Versions of Ada})
703 to explicitly specify the language version.
704 Throughout this manual, references to ``Ada'' without a year suffix
705 apply to both the Ada 95 and Ada 2005 versions of the language.
708 @ifclear FSFEDITION
709 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
710 ``GNAT'' in the remainder of this document.
711 @end ifclear
716 @menu
717 * What This Guide Contains::
718 * What You Should Know before Reading This Guide::
719 * Related Information::
720 * Conventions::
721 @end menu
723 @node What This Guide Contains
724 @unnumberedsec What This Guide Contains
726 @noindent
727 This guide contains the following chapters:
728 @itemize @bullet
730 @item
731 @ref{Getting Started with GNAT}, describes how to get started compiling
732 and running Ada programs with the GNAT Ada programming environment.
733 @item
734 @ref{The GNAT Compilation Model}, describes the compilation model used
735 by GNAT.
737 @item
738 @ref{Compiling Using gcc}, describes how to compile
739 Ada programs with @command{gcc}, the Ada compiler.
741 @item
742 @ref{Binding Using gnatbind}, describes how to
743 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
744 utility.
746 @item
747 @ref{Linking Using gnatlink},
748 describes @command{gnatlink}, a
749 program that provides for linking using the GNAT run-time library to
750 construct a program. @command{gnatlink} can also incorporate foreign language
751 object units into the executable.
753 @item
754 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
755 utility that automatically determines the set of sources
756 needed by an Ada compilation unit, and executes the necessary compilations
757 binding and link.
759 @item
760 @ref{Improving Performance}, shows various techniques for making your
761 Ada program run faster or take less space.
762 It discusses the effect of the compiler's optimization switch and
763 also describes the @command{gnatelim} tool and unused subprogram/data
764 elimination.
766 @item
767 @ref{Renaming Files Using gnatchop}, describes
768 @code{gnatchop}, a utility that allows you to preprocess a file that
769 contains Ada source code, and split it into one or more new files, one
770 for each compilation unit.
772 @item
773 @ref{Configuration Pragmas}, describes the configuration pragmas
774 handled by GNAT.
776 @item
777 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
778 shows how to override the default GNAT file naming conventions,
779 either for an individual unit or globally.
781 @item
782 @ref{GNAT Project Manager}, describes how to use project files
783 to organize large projects.
785 @item
786 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
787 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
788 way to navigate through sources.
790 @item
791 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
792 version of an Ada source file with control over casing, indentation,
793 comment placement, and other elements of program presentation style.
795 @item
796 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
797 metrics for an Ada source file, such as the number of types and subprograms,
798 and assorted complexity measures.
800 @item
801 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
802 file name krunching utility, used to handle shortened
803 file names on operating systems with a limit on the length of names.
805 @item
806 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
807 preprocessor utility that allows a single source file to be used to
808 generate multiple or parameterized source files by means of macro
809 substitution.
811 @item
812 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
813 utility that displays information about compiled units, including dependences
814 on the corresponding sources files, and consistency of compilations.
816 @item
817 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
818 to delete files that are produced by the compiler, binder and linker.
820 @ifclear vms
821 @item
822 @ref{GNAT and Libraries}, describes the process of creating and using
823 Libraries with GNAT. It also describes how to recompile the GNAT run-time
824 library.
826 @item
827 @ref{Using the GNU make Utility}, describes some techniques for using
828 the GNAT toolset in Makefiles.
829 @end ifclear
831 @item
832 @ref{Memory Management Issues}, describes some useful predefined storage pools
833 and in particular the GNAT Debug Pool facility, which helps detect incorrect
834 memory references.
835 @ifclear vms
836 It also describes @command{gnatmem}, a utility that monitors dynamic
837 allocation and deallocation and helps detect ``memory leaks''.
838 @end ifclear
840 @item
841 @ref{Stack Related Facilities}, describes some useful tools associated with
842 stack checking and analysis.
844 @item
845 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
846 a utility that checks Ada code against a set of rules.
848 @item
849 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
850 a utility that generates empty but compilable bodies for library units.
852 @item
853 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
854 a utility that generates unit testing templates for library units.
856 @item
857 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
858 facilities used in GNAT to declare dimensioned objects, and to verify that
859 uses of these objects are consistent with their given physical dimensions
860 (so that meters cannot be assigned to kilograms, and so on).
862 @item
863 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
864 generate automatically Ada bindings from C and C++ headers.
866 @item
867 @ref{Other Utility Programs}, discusses several other GNAT utilities,
868 including @code{gnathtml}.
870 @ifclear vms
871 @item
872 @ref{Code Coverage and Profiling}, describes how to perform a structural
873 coverage and profile the execution of Ada programs.
874 @end ifclear
876 @item
877 @ref{Running and Debugging Ada Programs}, describes how to run and debug
878 Ada programs.
880 @ifset vms
881 @item
882 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
883 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
884 developed by Digital Equipment Corporation and currently supported by HP.}
885 for OpenVMS Alpha. This product was formerly known as DEC Ada,
886 @cindex DEC Ada
887 and for
888 historical compatibility reasons, the relevant libraries still use the
889 DEC prefix.
890 @end ifset
892 @item
893 @ref{Platform-Specific Information for the Run-Time Libraries},
894 describes the various run-time
895 libraries supported by GNAT on various platforms and explains how to
896 choose a particular library.
898 @item
899 @ref{Example of Binder Output File}, shows the source code for the binder
900 output file for a sample program.
902 @item
903 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
904 you deal with elaboration order issues.
906 @item
907 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
908 you deal with arithmetic overflow issues.
910 @item
911 @ref{Conditional Compilation}, describes how to model conditional compilation,
912 both with Ada in general and with GNAT facilities in particular.
914 @item
915 @ref{Inline Assembler}, shows how to use the inline assembly facility
916 in an Ada program.
918 @item
919 @ref{Compatibility and Porting Guide}, contains sections on compatibility
920 of GNAT with other Ada development environments (including Ada 83 systems),
921 to assist in porting code from those environments.
923 @ifset unw
924 @item
925 @ref{Microsoft Windows Topics}, presents information relevant to the
926 Microsoft Windows platform.
928 @item
929 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
930 platform.
931 @end ifset
932 @end itemize
934 @c *************************************************
935 @node What You Should Know before Reading This Guide
936 @c *************************************************
937 @unnumberedsec What You Should Know before Reading This Guide
939 @cindex Ada 95 Language Reference Manual
940 @cindex Ada 2005 Language Reference Manual
941 @noindent
942 This guide assumes a basic familiarity with the Ada 95 language, as
943 described in the International Standard ANSI/ISO/IEC-8652:1995, January
944 1995.
945 It does not require knowledge of the new features introduced by Ada 2005,
946 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
947 and Amendment 1).
948 Both reference manuals are included in the GNAT documentation
949 package.
951 @node Related Information
952 @unnumberedsec Related Information
954 @noindent
955 For further information about related tools, refer to the following
956 documents:
958 @itemize @bullet
959 @item
960 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
961 Reference Manual}, which contains all reference material for the GNAT
962 implementation of Ada.
964 @ifset unw
965 @item
966 @cite{Using the GNAT Programming Studio}, which describes the GPS
967 Integrated Development Environment.
969 @item
970 @cite{GNAT Programming Studio Tutorial}, which introduces the
971 main GPS features through examples.
972 @end ifset
974 @item
975 @cite{Ada 95 Reference Manual}, which contains reference
976 material for the Ada 95 programming language.
978 @item
979 @cite{Ada 2005 Reference Manual}, which contains reference
980 material for the Ada 2005 programming language.
982 @item
983 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
984 @ifset vms
985 in the GNU:[DOCS] directory,
986 @end ifset
987 for all details on the use of the GNU source-level debugger.
989 @item
990 @xref{Top,, The extensible self-documenting text editor, emacs,
991 GNU Emacs Manual},
992 @ifset vms
993 located in the GNU:[DOCS] directory if the EMACS kit is installed,
994 @end ifset
995 for full information on the extensible editor and programming
996 environment Emacs.
998 @end itemize
1000 @c **************
1001 @node Conventions
1002 @unnumberedsec Conventions
1003 @cindex Conventions
1004 @cindex Typographical conventions
1006 @noindent
1007 Following are examples of the typographical and graphic conventions used
1008 in this guide:
1010 @itemize @bullet
1011 @item
1012 @code{Functions}, @command{utility program names}, @code{standard names},
1013 and @code{classes}.
1015 @item
1016 @option{Option flags}
1018 @item
1019 @file{File names}, @samp{button names}, and @samp{field names}.
1021 @item
1022 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1023 variables}.
1025 @item
1026 @emph{Emphasis}.
1028 @item
1029 @r{[}optional information or parameters@r{]}
1031 @item
1032 Examples are described by text
1033 @smallexample
1034 and then shown this way.
1035 @end smallexample
1036 @end itemize
1038 @noindent
1039 Commands that are entered by the user are preceded in this manual by the
1040 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1041 uses this sequence as a prompt, then the commands will appear exactly as
1042 you see them in the manual. If your system uses some other prompt, then
1043 the command will appear with the @code{$} replaced by whatever prompt
1044 character you are using.
1046 @ifset unw
1047 Full file names are shown with the ``@code{/}'' character
1048 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1049 If you are using GNAT on a Windows platform, please note that
1050 the ``@code{\}'' character should be used instead.
1051 @end ifset
1053 @c ****************************
1054 @node Getting Started with GNAT
1055 @chapter Getting Started with GNAT
1057 @noindent
1058 This chapter describes some simple ways of using GNAT to build
1059 executable Ada programs.
1060 @ifset unw
1061 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1062 show how to use the command line environment.
1063 @ref{Introduction to GPS}, provides a brief
1064 introduction to the GNAT Programming Studio, a visually-oriented
1065 Integrated Development Environment for GNAT.
1066 GPS offers a graphical ``look and feel'', support for development in
1067 other programming languages, comprehensive browsing features, and
1068 many other capabilities.
1069 For information on GPS please refer to
1070 @cite{Using the GNAT Programming Studio}.
1071 @end ifset
1073 @menu
1074 * Running GNAT::
1075 * Running a Simple Ada Program::
1076 * Running a Program with Multiple Units::
1077 * Using the gnatmake Utility::
1078 @ifset vms
1079 * Editing with Emacs::
1080 @end ifset
1081 @ifclear vms
1082 * Introduction to GPS::
1083 @end ifclear
1084 @end menu
1086 @node Running GNAT
1087 @section Running GNAT
1089 @noindent
1090 Three steps are needed to create an executable file from an Ada source
1091 file:
1093 @enumerate
1094 @item
1095 The source file(s) must be compiled.
1096 @item
1097 The file(s) must be bound using the GNAT binder.
1098 @item
1099 All appropriate object files must be linked to produce an executable.
1100 @end enumerate
1102 @noindent
1103 All three steps are most commonly handled by using the @command{gnatmake}
1104 utility program that, given the name of the main program, automatically
1105 performs the necessary compilation, binding and linking steps.
1107 @node Running a Simple Ada Program
1108 @section Running a Simple Ada Program
1110 @noindent
1111 Any text editor may be used to prepare an Ada program.
1112 (If @code{Emacs} is
1113 used, the optional Ada mode may be helpful in laying out the program.)
1115 program text is a normal text file. We will assume in our initial
1116 example that you have used your editor to prepare the following
1117 standard format text file:
1119 @smallexample @c ada
1120 @cartouche
1121 with Ada.Text_IO; use Ada.Text_IO;
1122 procedure Hello is
1123 begin
1124    Put_Line ("Hello WORLD!");
1125 end Hello;
1126 @end cartouche
1127 @end smallexample
1129 @noindent
1130 This file should be named @file{hello.adb}.
1131 With the normal default file naming conventions, GNAT requires
1132 that each file
1133 contain a single compilation unit whose file name is the
1134 unit name,
1135 with periods replaced by hyphens; the
1136 extension is @file{ads} for a
1137 spec and @file{adb} for a body.
1138 You can override this default file naming convention by use of the
1139 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1140 Alternatively, if you want to rename your files according to this default
1141 convention, which is probably more convenient if you will be using GNAT
1142 for all your compilations, then the @code{gnatchop} utility
1143 can be used to generate correctly-named source files
1144 (@pxref{Renaming Files Using gnatchop}).
1146 You can compile the program using the following command (@code{$} is used
1147 as the command prompt in the examples in this document):
1149 @smallexample
1150 $ gcc -c hello.adb
1151 @end smallexample
1153 @noindent
1154 @command{gcc} is the command used to run the compiler. This compiler is
1155 capable of compiling programs in several languages, including Ada and
1156 C. It assumes that you have given it an Ada program if the file extension is
1157 either @file{.ads} or @file{.adb}, and it will then call
1158 the GNAT compiler to compile the specified file.
1160 @ifclear vms
1161 The @option{-c} switch is required. It tells @command{gcc} to only do a
1162 compilation. (For C programs, @command{gcc} can also do linking, but this
1163 capability is not used directly for Ada programs, so the @option{-c}
1164 switch must always be present.)
1165 @end ifclear
1167 This compile command generates a file
1168 @file{hello.o}, which is the object
1169 file corresponding to your Ada program. It also generates
1170 an ``Ada Library Information'' file @file{hello.ali},
1171 which contains additional information used to check
1172 that an Ada program is consistent.
1173 To build an executable file,
1174 use @code{gnatbind} to bind the program
1175 and @command{gnatlink} to link it. The
1176 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1177 @file{ALI} file, but the default extension of @file{.ali} can
1178 be omitted. This means that in the most common case, the argument
1179 is simply the name of the main program:
1181 @smallexample
1182 $ gnatbind hello
1183 $ gnatlink hello
1184 @end smallexample
1186 @noindent
1187 A simpler method of carrying out these steps is to use
1188 @command{gnatmake},
1189 a master program that invokes all the required
1190 compilation, binding and linking tools in the correct order. In particular,
1191 @command{gnatmake} automatically recompiles any sources that have been
1192 modified since they were last compiled, or sources that depend
1193 on such modified sources, so that ``version skew'' is avoided.
1194 @cindex Version skew (avoided by @command{gnatmake})
1196 @smallexample
1197 $ gnatmake hello.adb
1198 @end smallexample
1200 @noindent
1201 The result is an executable program called @file{hello}, which can be
1202 run by entering:
1204 @smallexample
1205 $ ^hello^RUN HELLO^
1206 @end smallexample
1208 @noindent
1209 assuming that the current directory is on the search path
1210 for executable programs.
1212 @noindent
1213 and, if all has gone well, you will see
1215 @smallexample
1216 Hello WORLD!
1217 @end smallexample
1219 @noindent
1220 appear in response to this command.
1222 @c ****************************************
1223 @node Running a Program with Multiple Units
1224 @section Running a Program with Multiple Units
1226 @noindent
1227 Consider a slightly more complicated example that has three files: a
1228 main program, and the spec and body of a package:
1230 @smallexample @c ada
1231 @cartouche
1232 @group
1233 package Greetings is
1234    procedure Hello;
1235    procedure Goodbye;
1236 end Greetings;
1238 with Ada.Text_IO; use Ada.Text_IO;
1239 package body Greetings is
1240    procedure Hello is
1241    begin
1242       Put_Line ("Hello WORLD!");
1243    end Hello;
1245    procedure Goodbye is
1246    begin
1247       Put_Line ("Goodbye WORLD!");
1248    end Goodbye;
1249 end Greetings;
1250 @end group
1252 @group
1253 with Greetings;
1254 procedure Gmain is
1255 begin
1256    Greetings.Hello;
1257    Greetings.Goodbye;
1258 end Gmain;
1259 @end group
1260 @end cartouche
1261 @end smallexample
1263 @noindent
1264 Following the one-unit-per-file rule, place this program in the
1265 following three separate files:
1267 @table @file
1268 @item greetings.ads
1269 spec of package @code{Greetings}
1271 @item greetings.adb
1272 body of package @code{Greetings}
1274 @item gmain.adb
1275 body of main program
1276 @end table
1278 @noindent
1279 To build an executable version of
1280 this program, we could use four separate steps to compile, bind, and link
1281 the program, as follows:
1283 @smallexample
1284 $ gcc -c gmain.adb
1285 $ gcc -c greetings.adb
1286 $ gnatbind gmain
1287 $ gnatlink gmain
1288 @end smallexample
1290 @noindent
1291 Note that there is no required order of compilation when using GNAT.
1292 In particular it is perfectly fine to compile the main program first.
1293 Also, it is not necessary to compile package specs in the case where
1294 there is an accompanying body; you only need to compile the body. If you want
1295 to submit these files to the compiler for semantic checking and not code
1296 generation, then use the
1297 @option{-gnatc} switch:
1299 @smallexample
1300 $ gcc -c greetings.ads -gnatc
1301 @end smallexample
1303 @noindent
1304 Although the compilation can be done in separate steps as in the
1305 above example, in practice it is almost always more convenient
1306 to use the @command{gnatmake} tool. All you need to know in this case
1307 is the name of the main program's source file. The effect of the above four
1308 commands can be achieved with a single one:
1310 @smallexample
1311 $ gnatmake gmain.adb
1312 @end smallexample
1314 @noindent
1315 In the next section we discuss the advantages of using @command{gnatmake} in
1316 more detail.
1318 @c *****************************
1319 @node Using the gnatmake Utility
1320 @section Using the @command{gnatmake} Utility
1322 @noindent
1323 If you work on a program by compiling single components at a time using
1324 @command{gcc}, you typically keep track of the units you modify. In order to
1325 build a consistent system, you compile not only these units, but also any
1326 units that depend on the units you have modified.
1327 For example, in the preceding case,
1328 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1329 you edit @file{greetings.ads}, you must recompile both
1330 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1331 units that depend on @file{greetings.ads}.
1333 @code{gnatbind} will warn you if you forget one of these compilation
1334 steps, so that it is impossible to generate an inconsistent program as a
1335 result of forgetting to do a compilation. Nevertheless it is tedious and
1336 error-prone to keep track of dependencies among units.
1337 One approach to handle the dependency-bookkeeping is to use a
1338 makefile. However, makefiles present maintenance problems of their own:
1339 if the dependencies change as you change the program, you must make
1340 sure that the makefile is kept up-to-date manually, which is also an
1341 error-prone process.
1343 The @command{gnatmake} utility takes care of these details automatically.
1344 Invoke it using either one of the following forms:
1346 @smallexample
1347 $ gnatmake gmain.adb
1348 $ gnatmake ^gmain^GMAIN^
1349 @end smallexample
1351 @noindent
1352 The argument is the name of the file containing the main program;
1353 you may omit the extension. @command{gnatmake}
1354 examines the environment, automatically recompiles any files that need
1355 recompiling, and binds and links the resulting set of object files,
1356 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1357 In a large program, it
1358 can be extremely helpful to use @command{gnatmake}, because working out by hand
1359 what needs to be recompiled can be difficult.
1361 Note that @command{gnatmake}
1362 takes into account all the Ada rules that
1363 establish dependencies among units. These include dependencies that result
1364 from inlining subprogram bodies, and from
1365 generic instantiation. Unlike some other
1366 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1367 found by the compiler on a previous compilation, which may possibly
1368 be wrong when sources change. @command{gnatmake} determines the exact set of
1369 dependencies from scratch each time it is run.
1371 @ifset vms
1372 @node Editing with Emacs
1373 @section Editing with Emacs
1374 @cindex Emacs
1376 @noindent
1377 Emacs is an extensible self-documenting text editor that is available in a
1378 separate VMSINSTAL kit.
1380 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1381 click on the Emacs Help menu and run the Emacs Tutorial.
1382 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1383 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1385 Documentation on Emacs and other tools is available in Emacs under the
1386 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1387 use the middle mouse button to select a topic (e.g.@: Emacs).
1389 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1390 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1391 get to the Emacs manual.
1392 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1393 prompt.
1395 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1396 which is sufficiently extensible to provide for a complete programming
1397 environment and shell for the sophisticated user.
1398 @end ifset
1400 @ifclear vms
1401 @node Introduction to GPS
1402 @section Introduction to GPS
1403 @cindex GPS (GNAT Programming Studio)
1404 @cindex GNAT Programming Studio (GPS)
1405 @noindent
1406 Although the command line interface (@command{gnatmake}, etc.) alone
1407 is sufficient, a graphical Interactive Development
1408 Environment can make it easier for you to compose, navigate, and debug
1409 programs.  This section describes the main features of GPS
1410 (``GNAT Programming Studio''), the GNAT graphical IDE.
1411 You will see how to use GPS to build and debug an executable, and
1412 you will also learn some of the basics of the GNAT ``project'' facility.
1414 GPS enables you to do much more than is presented here;
1415 e.g., you can produce a call graph, interface to a third-party
1416 Version Control System, and inspect the generated assembly language
1417 for a program.
1418 Indeed, GPS also supports languages other than Ada.
1419 Such additional information, and an explanation of all of the GPS menu
1420 items. may be found in the on-line help, which includes
1421 a user's guide and a tutorial (these are also accessible from the GNAT
1422 startup menu).
1424 @menu
1425 * Building a New Program with GPS::
1426 * Simple Debugging with GPS::
1427 @end menu
1429 @node Building a New Program with GPS
1430 @subsection Building a New Program with GPS
1431 @noindent
1432 GPS invokes the GNAT compilation tools using information
1433 contained in a @emph{project} (also known as a @emph{project file}):
1434 a collection of properties such
1435 as source directories, identities of main subprograms, tool switches, etc.,
1436 and their associated values.
1437 See @ref{GNAT Project Manager} for details.
1438 In order to run GPS, you will need to either create a new project
1439 or else open an existing one.
1441 This section will explain how you can use GPS to create a project,
1442 to associate Ada source files with a project, and to build and run
1443 programs.
1445 @enumerate
1446 @item @emph{Creating a project}
1448 Invoke GPS, either from the command line or the platform's IDE.
1449 After it starts, GPS will display a ``Welcome'' screen with three
1450 radio buttons:
1452 @itemize @bullet
1453 @item
1454 @code{Start with default project in directory}
1456 @item
1457 @code{Create new project with wizard}
1459 @item
1460 @code{Open existing project}
1461 @end itemize
1463 @noindent
1464 Select @code{Create new project with wizard} and press @code{OK}.
1465 A new window will appear.  In the text box labeled with
1466 @code{Enter the name of the project to create}, type @file{sample}
1467 as the project name.
1468 In the next box, browse to choose the directory in which you
1469 would like to create the project file.
1470 After selecting an appropriate directory, press @code{Forward}.
1472 A window will appear with the title
1473 @code{Version Control System Configuration}.
1474 Simply press @code{Forward}.
1476 A window will appear with the title
1477 @code{Please select the source directories for this project}.
1478 The directory that you specified for the project file will be selected
1479 by default as the one to use for sources; simply press @code{Forward}.
1481 A window will appear with the title
1482 @code{Please select the build directory for this project}.
1483 The directory that you specified for the project file will be selected
1484 by default for object files and executables;
1485 simply press @code{Forward}.
1487 A window will appear with the title
1488 @code{Please select the main units for this project}.
1489 You will supply this information later, after creating the source file.
1490 Simply press @code{Forward} for now.
1492 A window will appear with the title
1493 @code{Please select the switches to build the project}.
1494 Press @code{Apply}.  This will create a project file named
1495 @file{sample.prj} in the directory that you had specified.
1497 @item @emph{Creating and saving the source file}
1499 After you create the new project, a GPS window will appear, which is
1500 partitioned into two main sections:
1502 @itemize @bullet
1503 @item
1504 A @emph{Workspace area}, initially greyed out, which you will use for
1505 creating and editing source files
1507 @item
1508 Directly below, a @emph{Messages area}, which initially displays a
1509 ``Welcome'' message.
1510 (If the Messages area is not visible, drag its border upward to expand it.)
1511 @end itemize
1513 @noindent
1514 Select @code{File} on the menu bar, and then the @code{New} command.
1515 The Workspace area will become white, and you can now
1516 enter the source program explicitly.
1517 Type the following text
1519 @smallexample @c ada
1520 @group
1521 with Ada.Text_IO; use Ada.Text_IO;
1522 procedure Hello is
1523 begin
1524   Put_Line("Hello from GPS!");
1525 end Hello;
1526 @end group
1527 @end smallexample
1529 @noindent
1530 Select @code{File}, then @code{Save As}, and enter the source file name
1531 @file{hello.adb}.
1532 The file will be saved in the same directory you specified as the
1533 location of the default project file.
1535 @item @emph{Updating the project file}
1537 You need to add the new source file to the project.
1538 To do this, select
1539 the @code{Project} menu and then @code{Edit project properties}.
1540 Click the @code{Main files} tab on the left, and then the
1541 @code{Add} button.
1542 Choose @file{hello.adb} from the list, and press @code{Open}.
1543 The project settings window will reflect this action.
1544 Click @code{OK}.
1546 @item @emph{Building and running the program}
1548 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1549 and select @file{hello.adb}.
1550 The Messages window will display the resulting invocations of @command{gcc},
1551 @command{gnatbind}, and @command{gnatlink}
1552 (reflecting the default switch settings from the
1553 project file that you created) and then a ``successful compilation/build''
1554 message.
1556 To run the program, choose the @code{Build} menu, then @code{Run}, and
1557 select @command{hello}.
1558 An @emph{Arguments Selection} window will appear.
1559 There are no command line arguments, so just click @code{OK}.
1561 The Messages window will now display the program's output (the string
1562 @code{Hello from GPS}), and at the bottom of the GPS window a status
1563 update is displayed (@code{Run: hello}).
1564 Close the GPS window (or select @code{File}, then @code{Exit}) to
1565 terminate this GPS session.
1566 @end enumerate
1568 @node Simple Debugging with GPS
1569 @subsection Simple Debugging with GPS
1570 @noindent
1571 This section illustrates basic debugging techniques (setting breakpoints,
1572 examining/modifying variables, single stepping).
1574 @enumerate
1575 @item @emph{Opening a project}
1577 Start GPS and select @code{Open existing project}; browse to
1578 specify the project file @file{sample.prj} that you had created in the
1579 earlier example.
1581 @item @emph{Creating a source file}
1583 Select @code{File}, then @code{New}, and type in the following program:
1585 @smallexample @c ada
1586 @group
1587 with Ada.Text_IO; use Ada.Text_IO;
1588 procedure Example is
1589    Line : String (1..80);
1590    N    : Natural;
1591 begin
1592    Put_Line("Type a line of text at each prompt; an empty line to exit");
1593    loop
1594       Put(": ");
1595       Get_Line (Line, N);
1596       Put_Line (Line (1..N) );
1597       exit when N=0;
1598    end loop;
1599 end Example;
1600 @end group
1601 @end smallexample
1603 @noindent
1604 Select @code{File}, then @code{Save as}, and enter the file name
1605 @file{example.adb}.
1607 @item @emph{Updating the project file}
1609 Add @code{Example} as a new main unit for the project:
1610 @enumerate a
1611 @item
1612 Select @code{Project}, then @code{Edit Project Properties}.
1614 @item
1615 Select the @code{Main files} tab, click @code{Add}, then
1616 select the file @file{example.adb} from the list, and
1617 click @code{Open}.
1618 You will see the file name appear in the list of main units
1620 @item
1621 Click @code{OK}
1622 @end enumerate
1624 @item @emph{Building/running the executable}
1626 To build the executable
1627 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1629 Run the program to see its effect (in the Messages area).
1630 Each line that you enter is displayed; an empty line will
1631 cause the loop to exit and the program to terminate.
1633 @item @emph{Debugging the program}
1635 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1636 which are required for debugging, are on by default when you create
1637 a new project.
1638 Thus unless you intentionally remove these settings, you will be able
1639 to debug any program that you develop using GPS.
1641 @enumerate a
1642 @item @emph{Initializing}
1644 Select @code{Debug}, then @code{Initialize}, then @file{example}
1646 @item @emph{Setting a breakpoint}
1648 After performing the initialization step, you will observe a small
1649 icon to the right of each line number.
1650 This serves as a toggle for breakpoints; clicking the icon will
1651 set a breakpoint at the corresponding line (the icon will change to
1652 a red circle with an ``x''), and clicking it again
1653 will remove the breakpoint / reset the icon.
1655 For purposes of this example, set a breakpoint at line 10 (the
1656 statement @code{Put_Line@ (Line@ (1..N));}
1658 @item @emph{Starting program execution}
1660 Select @code{Debug}, then @code{Run}.  When the
1661 @code{Program Arguments} window appears, click @code{OK}.
1662 A console window will appear; enter some line of text,
1663 e.g.@: @code{abcde}, at the prompt.
1664 The program will pause execution when it gets to the
1665 breakpoint, and the corresponding line is highlighted.
1667 @item @emph{Examining a variable}
1669 Move the mouse over one of the occurrences of the variable @code{N}.
1670 You will see the value (5) displayed, in ``tool tip'' fashion.
1671 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1672 You will see information about @code{N} appear in the @code{Debugger Data}
1673 pane, showing the value as 5.
1675 @item @emph{Assigning a new value to a variable}
1677 Right click on the @code{N} in the @code{Debugger Data} pane, and
1678 select @code{Set value of N}.
1679 When the input window appears, enter the value @code{4} and click
1680 @code{OK}.
1681 This value does not automatically appear in the @code{Debugger Data}
1682 pane; to see it, right click again on the @code{N} in the
1683 @code{Debugger Data} pane and select @code{Update value}.
1684 The new value, 4, will appear in red.
1686 @item @emph{Single stepping}
1688 Select @code{Debug}, then @code{Next}.
1689 This will cause the next statement to be executed, in this case the
1690 call of @code{Put_Line} with the string slice.
1691 Notice in the console window that the displayed string is simply
1692 @code{abcd} and not @code{abcde} which you had entered.
1693 This is because the upper bound of the slice is now 4 rather than 5.
1695 @item @emph{Removing a breakpoint}
1697 Toggle the breakpoint icon at line 10.
1699 @item @emph{Resuming execution from a breakpoint}
1701 Select @code{Debug}, then @code{Continue}.
1702 The program will reach the next iteration of the loop, and
1703 wait for input after displaying the prompt.
1704 This time, just hit the @kbd{Enter} key.
1705 The value of @code{N} will be 0, and the program will terminate.
1706 The console window will disappear.
1707 @end enumerate
1708 @end enumerate
1709 @end ifclear
1711 @node The GNAT Compilation Model
1712 @chapter The GNAT Compilation Model
1713 @cindex GNAT compilation model
1714 @cindex Compilation model
1716 @menu
1717 * Source Representation::
1718 * Foreign Language Representation::
1719 * File Naming Rules::
1720 * Using Other File Names::
1721 * Alternative File Naming Schemes::
1722 * Generating Object Files::
1723 * Source Dependencies::
1724 * The Ada Library Information Files::
1725 * Binding an Ada Program::
1726 * Mixed Language Programming::
1727 @ifclear vms
1728 * Building Mixed Ada & C++ Programs::
1729 * Comparison between GNAT and C/C++ Compilation Models::
1730 @end ifclear
1731 * Comparison between GNAT and Conventional Ada Library Models::
1732 @ifset vms
1733 * Placement of temporary files::
1734 @end ifset
1735 @end menu
1737 @noindent
1738 This chapter describes the compilation model used by GNAT. Although
1739 similar to that used by other languages, such as C and C++, this model
1740 is substantially different from the traditional Ada compilation models,
1741 which are based on a library. The model is initially described without
1742 reference to the library-based model. If you have not previously used an
1743 Ada compiler, you need only read the first part of this chapter. The
1744 last section describes and discusses the differences between the GNAT
1745 model and the traditional Ada compiler models. If you have used other
1746 Ada compilers, this section will help you to understand those
1747 differences, and the advantages of the GNAT model.
1749 @node Source Representation
1750 @section Source Representation
1751 @cindex Latin-1
1753 @noindent
1754 Ada source programs are represented in standard text files, using
1755 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1756 7-bit ASCII set, plus additional characters used for
1757 representing foreign languages (@pxref{Foreign Language Representation}
1758 for support of non-USA character sets). The format effector characters
1759 are represented using their standard ASCII encodings, as follows:
1761 @table @code
1762 @item VT
1763 @findex VT
1764 Vertical tab, @code{16#0B#}
1766 @item HT
1767 @findex HT
1768 Horizontal tab, @code{16#09#}
1770 @item CR
1771 @findex CR
1772 Carriage return, @code{16#0D#}
1774 @item LF
1775 @findex LF
1776 Line feed, @code{16#0A#}
1778 @item FF
1779 @findex FF
1780 Form feed, @code{16#0C#}
1781 @end table
1783 @noindent
1784 Source files are in standard text file format. In addition, GNAT will
1785 recognize a wide variety of stream formats, in which the end of
1786 physical lines is marked by any of the following sequences:
1787 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1788 in accommodating files that are imported from other operating systems.
1790 @cindex End of source file
1791 @cindex Source file, end
1792 @findex SUB
1793 The end of a source file is normally represented by the physical end of
1794 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1795 recognized as signalling the end of the source file. Again, this is
1796 provided for compatibility with other operating systems where this
1797 code is used to represent the end of file.
1799 Each file contains a single Ada compilation unit, including any pragmas
1800 associated with the unit. For example, this means you must place a
1801 package declaration (a package @dfn{spec}) and the corresponding body in
1802 separate files. An Ada @dfn{compilation} (which is a sequence of
1803 compilation units) is represented using a sequence of files. Similarly,
1804 you will place each subunit or child unit in a separate file.
1806 @node Foreign Language Representation
1807 @section Foreign Language Representation
1809 @noindent
1810 GNAT supports the standard character sets defined in Ada as well as
1811 several other non-standard character sets for use in localized versions
1812 of the compiler (@pxref{Character Set Control}).
1813 @menu
1814 * Latin-1::
1815 * Other 8-Bit Codes::
1816 * Wide Character Encodings::
1817 @end menu
1819 @node Latin-1
1820 @subsection Latin-1
1821 @cindex Latin-1
1823 @noindent
1824 The basic character set is Latin-1. This character set is defined by ISO
1825 standard 8859, part 1. The lower half (character codes @code{16#00#}
1826 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1827 half is used to represent additional characters. These include extended letters
1828 used by European languages, such as French accents, the vowels with umlauts
1829 used in German, and the extra letter A-ring used in Swedish.
1831 @findex Ada.Characters.Latin_1
1832 For a complete list of Latin-1 codes and their encodings, see the source
1833 file of library unit @code{Ada.Characters.Latin_1} in file
1834 @file{a-chlat1.ads}.
1835 You may use any of these extended characters freely in character or
1836 string literals. In addition, the extended characters that represent
1837 letters can be used in identifiers.
1839 @node Other 8-Bit Codes
1840 @subsection Other 8-Bit Codes
1842 @noindent
1843 GNAT also supports several other 8-bit coding schemes:
1845 @table @asis
1846 @item ISO 8859-2 (Latin-2)
1847 @cindex Latin-2
1848 @cindex ISO 8859-2
1849 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1850 equivalence.
1852 @item ISO 8859-3 (Latin-3)
1853 @cindex Latin-3
1854 @cindex ISO 8859-3
1855 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1856 equivalence.
1858 @item ISO 8859-4 (Latin-4)
1859 @cindex Latin-4
1860 @cindex ISO 8859-4
1861 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1862 equivalence.
1864 @item ISO 8859-5 (Cyrillic)
1865 @cindex ISO 8859-5
1866 @cindex Cyrillic
1867 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1868 lowercase equivalence.
1870 @item ISO 8859-15 (Latin-9)
1871 @cindex ISO 8859-15
1872 @cindex Latin-9
1873 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1874 lowercase equivalence
1876 @item IBM PC (code page 437)
1877 @cindex code page 437
1878 This code page is the normal default for PCs in the U.S. It corresponds
1879 to the original IBM PC character set. This set has some, but not all, of
1880 the extended Latin-1 letters, but these letters do not have the same
1881 encoding as Latin-1. In this mode, these letters are allowed in
1882 identifiers with uppercase and lowercase equivalence.
1884 @item IBM PC (code page 850)
1885 @cindex code page 850
1886 This code page is a modification of 437 extended to include all the
1887 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1888 mode, all these letters are allowed in identifiers with uppercase and
1889 lowercase equivalence.
1891 @item Full Upper 8-bit
1892 Any character in the range 80-FF allowed in identifiers, and all are
1893 considered distinct. In other words, there are no uppercase and lowercase
1894 equivalences in this range. This is useful in conjunction with
1895 certain encoding schemes used for some foreign character sets (e.g.,
1896 the typical method of representing Chinese characters on the PC).
1898 @item No Upper-Half
1899 No upper-half characters in the range 80-FF are allowed in identifiers.
1900 This gives Ada 83 compatibility for identifier names.
1901 @end table
1903 @noindent
1904 For precise data on the encodings permitted, and the uppercase and lowercase
1905 equivalences that are recognized, see the file @file{csets.adb} in
1906 the GNAT compiler sources. You will need to obtain a full source release
1907 of GNAT to obtain this file.
1909 @node Wide Character Encodings
1910 @subsection Wide Character Encodings
1912 @noindent
1913 GNAT allows wide character codes to appear in character and string
1914 literals, and also optionally in identifiers, by means of the following
1915 possible encoding schemes:
1917 @table @asis
1919 @item Hex Coding
1920 In this encoding, a wide character is represented by the following five
1921 character sequence:
1923 @smallexample
1924 ESC a b c d
1925 @end smallexample
1927 @noindent
1928 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1929 characters (using uppercase letters) of the wide character code. For
1930 example, ESC A345 is used to represent the wide character with code
1931 @code{16#A345#}.
1932 This scheme is compatible with use of the full Wide_Character set.
1934 @item Upper-Half Coding
1935 @cindex Upper-Half Coding
1936 The wide character with encoding @code{16#abcd#} where the upper bit is on
1937 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1938 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1939 character, but is not required to be in the upper half. This method can
1940 be also used for shift-JIS or EUC, where the internal coding matches the
1941 external coding.
1943 @item Shift JIS Coding
1944 @cindex Shift JIS Coding
1945 A wide character is represented by a two-character sequence,
1946 @code{16#ab#} and
1947 @code{16#cd#}, with the restrictions described for upper-half encoding as
1948 described above. The internal character code is the corresponding JIS
1949 character according to the standard algorithm for Shift-JIS
1950 conversion. Only characters defined in the JIS code set table can be
1951 used with this encoding method.
1953 @item EUC Coding
1954 @cindex EUC Coding
1955 A wide character is represented by a two-character sequence
1956 @code{16#ab#} and
1957 @code{16#cd#}, with both characters being in the upper half. The internal
1958 character code is the corresponding JIS character according to the EUC
1959 encoding algorithm. Only characters defined in the JIS code set table
1960 can be used with this encoding method.
1962 @item UTF-8 Coding
1963 A wide character is represented using
1964 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1965 10646-1/Am.2. Depending on the character value, the representation
1966 is a one, two, or three byte sequence:
1967 @smallexample
1968 @iftex
1969 @leftskip=.7cm
1970 @end iftex
1971 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1972 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1973 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1975 @end smallexample
1977 @noindent
1978 where the @var{xxx} bits correspond to the left-padded bits of the
1979 16-bit character value. Note that all lower half ASCII characters
1980 are represented as ASCII bytes and all upper half characters and
1981 other wide characters are represented as sequences of upper-half
1982 (The full UTF-8 scheme allows for encoding 31-bit characters as
1983 6-byte sequences, but in this implementation, all UTF-8 sequences
1984 of four or more bytes length will be treated as illegal).
1985 @item Brackets Coding
1986 In this encoding, a wide character is represented by the following eight
1987 character sequence:
1989 @smallexample
1990 [ " a b c d " ]
1991 @end smallexample
1993 @noindent
1994 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1995 characters (using uppercase letters) of the wide character code. For
1996 example, [``A345''] is used to represent the wide character with code
1997 @code{16#A345#}. It is also possible (though not required) to use the
1998 Brackets coding for upper half characters. For example, the code
1999 @code{16#A3#} can be represented as @code{[``A3'']}.
2001 This scheme is compatible with use of the full Wide_Character set,
2002 and is also the method used for wide character encoding in the standard
2003 ACVC (Ada Compiler Validation Capability) test suite distributions.
2005 @end table
2007 @noindent
2008 Note: Some of these coding schemes do not permit the full use of the
2009 Ada character set. For example, neither Shift JIS, nor EUC allow the
2010 use of the upper half of the Latin-1 set.
2012 @node File Naming Rules
2013 @section File Naming Rules
2015 @noindent
2016 The default file name is determined by the name of the unit that the
2017 file contains. The name is formed by taking the full expanded name of
2018 the unit and replacing the separating dots with hyphens and using
2019 ^lowercase^uppercase^ for all letters.
2021 An exception arises if the file name generated by the above rules starts
2022 with one of the characters
2023 @ifset vms
2024 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2025 @end ifset
2026 @ifclear vms
2027 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2028 @end ifclear
2029 and the second character is a
2030 minus. In this case, the character ^tilde^dollar sign^ is used in place
2031 of the minus. The reason for this special rule is to avoid clashes with
2032 the standard names for child units of the packages System, Ada,
2033 Interfaces, and GNAT, which use the prefixes
2034 @ifset vms
2035 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2036 @end ifset
2037 @ifclear vms
2038 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2039 @end ifclear
2040 respectively.
2042 The file extension is @file{.ads} for a spec and
2043 @file{.adb} for a body. The following list shows some
2044 examples of these rules.
2046 @table @file
2047 @item main.ads
2048 Main (spec)
2049 @item main.adb
2050 Main (body)
2051 @item arith_functions.ads
2052 Arith_Functions (package spec)
2053 @item arith_functions.adb
2054 Arith_Functions (package body)
2055 @item func-spec.ads
2056 Func.Spec (child package spec)
2057 @item func-spec.adb
2058 Func.Spec (child package body)
2059 @item main-sub.adb
2060 Sub (subunit of Main)
2061 @item ^a~bad.adb^A$BAD.ADB^
2062 A.Bad (child package body)
2063 @end table
2065 @noindent
2066 Following these rules can result in excessively long
2067 file names if corresponding
2068 unit names are long (for example, if child units or subunits are
2069 heavily nested). An option is available to shorten such long file names
2070 (called file name ``krunching''). This may be particularly useful when
2071 programs being developed with GNAT are to be used on operating systems
2072 with limited file name lengths. @xref{Using gnatkr}.
2074 Of course, no file shortening algorithm can guarantee uniqueness over
2075 all possible unit names; if file name krunching is used, it is your
2076 responsibility to ensure no name clashes occur. Alternatively you
2077 can specify the exact file names that you want used, as described
2078 in the next section. Finally, if your Ada programs are migrating from a
2079 compiler with a different naming convention, you can use the gnatchop
2080 utility to produce source files that follow the GNAT naming conventions.
2081 (For details @pxref{Renaming Files Using gnatchop}.)
2083 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2084 systems, case is not significant. So for example on @code{Windows XP}
2085 if the canonical name is @code{main-sub.adb}, you can use the file name
2086 @code{Main-Sub.adb} instead. However, case is significant for other
2087 operating systems, so for example, if you want to use other than
2088 canonically cased file names on a Unix system, you need to follow
2089 the procedures described in the next section.
2091 @node Using Other File Names
2092 @section Using Other File Names
2093 @cindex File names
2095 @noindent
2096 In the previous section, we have described the default rules used by
2097 GNAT to determine the file name in which a given unit resides. It is
2098 often convenient to follow these default rules, and if you follow them,
2099 the compiler knows without being explicitly told where to find all
2100 the files it needs.
2102 However, in some cases, particularly when a program is imported from
2103 another Ada compiler environment, it may be more convenient for the
2104 programmer to specify which file names contain which units. GNAT allows
2105 arbitrary file names to be used by means of the Source_File_Name pragma.
2106 The form of this pragma is as shown in the following examples:
2107 @cindex Source_File_Name pragma
2109 @smallexample @c ada
2110 @cartouche
2111 pragma Source_File_Name (My_Utilities.Stacks,
2112   Spec_File_Name => "myutilst_a.ada");
2113 pragma Source_File_name (My_Utilities.Stacks,
2114   Body_File_Name => "myutilst.ada");
2115 @end cartouche
2116 @end smallexample
2118 @noindent
2119 As shown in this example, the first argument for the pragma is the unit
2120 name (in this example a child unit). The second argument has the form
2121 of a named association. The identifier
2122 indicates whether the file name is for a spec or a body;
2123 the file name itself is given by a string literal.
2125 The source file name pragma is a configuration pragma, which means that
2126 normally it will be placed in the @file{gnat.adc}
2127 file used to hold configuration
2128 pragmas that apply to a complete compilation environment.
2129 For more details on how the @file{gnat.adc} file is created and used
2130 see @ref{Handling of Configuration Pragmas}.
2131 @cindex @file{gnat.adc}
2133 @ifclear vms
2134 GNAT allows completely arbitrary file names to be specified using the
2135 source file name pragma. However, if the file name specified has an
2136 extension other than @file{.ads} or @file{.adb} it is necessary to use
2137 a special syntax when compiling the file. The name in this case must be
2138 preceded by the special sequence @option{-x} followed by a space and the name
2139 of the language, here @code{ada}, as in:
2141 @smallexample
2142 $ gcc -c -x ada peculiar_file_name.sim
2143 @end smallexample
2144 @end ifclear
2146 @noindent
2147 @command{gnatmake} handles non-standard file names in the usual manner (the
2148 non-standard file name for the main program is simply used as the
2149 argument to gnatmake). Note that if the extension is also non-standard,
2150 then it must be included in the @command{gnatmake} command, it may not
2151 be omitted.
2153 @node Alternative File Naming Schemes
2154 @section Alternative File Naming Schemes
2155 @cindex File naming schemes, alternative
2156 @cindex File names
2158 In the previous section, we described the use of the @code{Source_File_Name}
2159 pragma to allow arbitrary names to be assigned to individual source files.
2160 However, this approach requires one pragma for each file, and especially in
2161 large systems can result in very long @file{gnat.adc} files, and also create
2162 a maintenance problem.
2164 GNAT also provides a facility for specifying systematic file naming schemes
2165 other than the standard default naming scheme previously described. An
2166 alternative scheme for naming is specified by the use of
2167 @code{Source_File_Name} pragmas having the following format:
2168 @cindex Source_File_Name pragma
2170 @smallexample @c ada
2171 pragma Source_File_Name (
2172    Spec_File_Name  => FILE_NAME_PATTERN
2173  @r{[},Casing          => CASING_SPEC@r{]}
2174  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2176 pragma Source_File_Name (
2177    Body_File_Name  => FILE_NAME_PATTERN
2178  @r{[},Casing          => CASING_SPEC@r{]}
2179  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2181 pragma Source_File_Name (
2182    Subunit_File_Name  => FILE_NAME_PATTERN
2183  @r{[},Casing             => CASING_SPEC@r{]}
2184  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2186 FILE_NAME_PATTERN ::= STRING_LITERAL
2187 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2188 @end smallexample
2190 @noindent
2191 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2192 It contains a single asterisk character, and the unit name is substituted
2193 systematically for this asterisk. The optional parameter
2194 @code{Casing} indicates
2195 whether the unit name is to be all upper-case letters, all lower-case letters,
2196 or mixed-case. If no
2197 @code{Casing} parameter is used, then the default is all
2198 ^lower-case^upper-case^.
2200 The optional @code{Dot_Replacement} string is used to replace any periods
2201 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2202 argument is used then separating dots appear unchanged in the resulting
2203 file name.
2204 Although the above syntax indicates that the
2205 @code{Casing} argument must appear
2206 before the @code{Dot_Replacement} argument, but it
2207 is also permissible to write these arguments in the opposite order.
2209 As indicated, it is possible to specify different naming schemes for
2210 bodies, specs, and subunits. Quite often the rule for subunits is the
2211 same as the rule for bodies, in which case, there is no need to give
2212 a separate @code{Subunit_File_Name} rule, and in this case the
2213 @code{Body_File_name} rule is used for subunits as well.
2215 The separate rule for subunits can also be used to implement the rather
2216 unusual case of a compilation environment (e.g.@: a single directory) which
2217 contains a subunit and a child unit with the same unit name. Although
2218 both units cannot appear in the same partition, the Ada Reference Manual
2219 allows (but does not require) the possibility of the two units coexisting
2220 in the same environment.
2222 The file name translation works in the following steps:
2224 @itemize @bullet
2226 @item
2227 If there is a specific @code{Source_File_Name} pragma for the given unit,
2228 then this is always used, and any general pattern rules are ignored.
2230 @item
2231 If there is a pattern type @code{Source_File_Name} pragma that applies to
2232 the unit, then the resulting file name will be used if the file exists. If
2233 more than one pattern matches, the latest one will be tried first, and the
2234 first attempt resulting in a reference to a file that exists will be used.
2236 @item
2237 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2238 for which the corresponding file exists, then the standard GNAT default
2239 naming rules are used.
2241 @end itemize
2243 @noindent
2244 As an example of the use of this mechanism, consider a commonly used scheme
2245 in which file names are all lower case, with separating periods copied
2246 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2247 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2248 two pragmas appear:
2250 @smallexample @c ada
2251 pragma Source_File_Name
2252   (Spec_File_Name => "*.1.ada");
2253 pragma Source_File_Name
2254   (Body_File_Name => "*.2.ada");
2255 @end smallexample
2257 @noindent
2258 The default GNAT scheme is actually implemented by providing the following
2259 default pragmas internally:
2261 @smallexample @c ada
2262 pragma Source_File_Name
2263   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2264 pragma Source_File_Name
2265   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2266 @end smallexample
2268 @noindent
2269 Our final example implements a scheme typically used with one of the
2270 Ada 83 compilers, where the separator character for subunits was ``__''
2271 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2272 by adding @file{.ADA}, and subunits by
2273 adding @file{.SEP}. All file names were
2274 upper case. Child units were not present of course since this was an
2275 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2276 the same double underscore separator for child units.
2278 @smallexample @c ada
2279 pragma Source_File_Name
2280   (Spec_File_Name => "*_.ADA",
2281    Dot_Replacement => "__",
2282    Casing = Uppercase);
2283 pragma Source_File_Name
2284   (Body_File_Name => "*.ADA",
2285    Dot_Replacement => "__",
2286    Casing = Uppercase);
2287 pragma Source_File_Name
2288   (Subunit_File_Name => "*.SEP",
2289    Dot_Replacement => "__",
2290    Casing = Uppercase);
2291 @end smallexample
2293 @node Generating Object Files
2294 @section Generating Object Files
2296 @noindent
2297 An Ada program consists of a set of source files, and the first step in
2298 compiling the program is to generate the corresponding object files.
2299 These are generated by compiling a subset of these source files.
2300 The files you need to compile are the following:
2302 @itemize @bullet
2303 @item
2304 If a package spec has no body, compile the package spec to produce the
2305 object file for the package.
2307 @item
2308 If a package has both a spec and a body, compile the body to produce the
2309 object file for the package. The source file for the package spec need
2310 not be compiled in this case because there is only one object file, which
2311 contains the code for both the spec and body of the package.
2313 @item
2314 For a subprogram, compile the subprogram body to produce the object file
2315 for the subprogram. The spec, if one is present, is as usual in a
2316 separate file, and need not be compiled.
2318 @item
2319 @cindex Subunits
2320 In the case of subunits, only compile the parent unit. A single object
2321 file is generated for the entire subunit tree, which includes all the
2322 subunits.
2324 @item
2325 Compile child units independently of their parent units
2326 (though, of course, the spec of all the ancestor unit must be present in order
2327 to compile a child unit).
2329 @item
2330 @cindex Generics
2331 Compile generic units in the same manner as any other units. The object
2332 files in this case are small dummy files that contain at most the
2333 flag used for elaboration checking. This is because GNAT always handles generic
2334 instantiation by means of macro expansion. However, it is still necessary to
2335 compile generic units, for dependency checking and elaboration purposes.
2336 @end itemize
2338 @noindent
2339 The preceding rules describe the set of files that must be compiled to
2340 generate the object files for a program. Each object file has the same
2341 name as the corresponding source file, except that the extension is
2342 @file{.o} as usual.
2344 You may wish to compile other files for the purpose of checking their
2345 syntactic and semantic correctness. For example, in the case where a
2346 package has a separate spec and body, you would not normally compile the
2347 spec. However, it is convenient in practice to compile the spec to make
2348 sure it is error-free before compiling clients of this spec, because such
2349 compilations will fail if there is an error in the spec.
2351 GNAT provides an option for compiling such files purely for the
2352 purposes of checking correctness; such compilations are not required as
2353 part of the process of building a program. To compile a file in this
2354 checking mode, use the @option{-gnatc} switch.
2356 @node Source Dependencies
2357 @section Source Dependencies
2359 @noindent
2360 A given object file clearly depends on the source file which is compiled
2361 to produce it. Here we are using @dfn{depends} in the sense of a typical
2362 @code{make} utility; in other words, an object file depends on a source
2363 file if changes to the source file require the object file to be
2364 recompiled.
2365 In addition to this basic dependency, a given object may depend on
2366 additional source files as follows:
2368 @itemize @bullet
2369 @item
2370 If a file being compiled @code{with}'s a unit @var{X}, the object file
2371 depends on the file containing the spec of unit @var{X}. This includes
2372 files that are @code{with}'ed implicitly either because they are parents
2373 of @code{with}'ed child units or they are run-time units required by the
2374 language constructs used in a particular unit.
2376 @item
2377 If a file being compiled instantiates a library level generic unit, the
2378 object file depends on both the spec and body files for this generic
2379 unit.
2381 @item
2382 If a file being compiled instantiates a generic unit defined within a
2383 package, the object file depends on the body file for the package as
2384 well as the spec file.
2386 @item
2387 @findex Inline
2388 @cindex @option{-gnatn} switch
2389 If a file being compiled contains a call to a subprogram for which
2390 pragma @code{Inline} applies and inlining is activated with the
2391 @option{-gnatn} switch, the object file depends on the file containing the
2392 body of this subprogram as well as on the file containing the spec. Note
2393 that for inlining to actually occur as a result of the use of this switch,
2394 it is necessary to compile in optimizing mode.
2396 @cindex @option{-gnatN} switch
2397 The use of @option{-gnatN} activates  inlining optimization
2398 that is performed by the front end of the compiler. This inlining does
2399 not require that the code generation be optimized. Like @option{-gnatn},
2400 the use of this switch generates additional dependencies.
2402 When using a gcc-based back end (in practice this means using any version
2403 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2404 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2405 Historically front end inlining was more extensive than the gcc back end
2406 inlining, but that is no longer the case.
2408 @item
2409 If an object file @file{O} depends on the proper body of a subunit through
2410 inlining or instantiation, it depends on the parent unit of the subunit.
2411 This means that any modification of the parent unit or one of its subunits
2412 affects the compilation of @file{O}.
2414 @item
2415 The object file for a parent unit depends on all its subunit body files.
2417 @item
2418 The previous two rules meant that for purposes of computing dependencies and
2419 recompilation, a body and all its subunits are treated as an indivisible whole.
2421 @noindent
2422 These rules are applied transitively: if unit @code{A} @code{with}'s
2423 unit @code{B}, whose elaboration calls an inlined procedure in package
2424 @code{C}, the object file for unit @code{A} will depend on the body of
2425 @code{C}, in file @file{c.adb}.
2427 The set of dependent files described by these rules includes all the
2428 files on which the unit is semantically dependent, as dictated by the
2429 Ada language standard. However, it is a superset of what the
2430 standard describes, because it includes generic, inline, and subunit
2431 dependencies.
2433 An object file must be recreated by recompiling the corresponding source
2434 file if any of the source files on which it depends are modified. For
2435 example, if the @code{make} utility is used to control compilation,
2436 the rule for an Ada object file must mention all the source files on
2437 which the object file depends, according to the above definition.
2438 The determination of the necessary
2439 recompilations is done automatically when one uses @command{gnatmake}.
2440 @end itemize
2442 @node The Ada Library Information Files
2443 @section The Ada Library Information Files
2444 @cindex Ada Library Information files
2445 @cindex @file{ALI} files
2447 @noindent
2448 Each compilation actually generates two output files. The first of these
2449 is the normal object file that has a @file{.o} extension. The second is a
2450 text file containing full dependency information. It has the same
2451 name as the source file, but an @file{.ali} extension.
2452 This file is known as the Ada Library Information (@file{ALI}) file.
2453 The following information is contained in the @file{ALI} file.
2455 @itemize @bullet
2456 @item
2457 Version information (indicates which version of GNAT was used to compile
2458 the unit(s) in question)
2460 @item
2461 Main program information (including priority and time slice settings,
2462 as well as the wide character encoding used during compilation).
2464 @item
2465 List of arguments used in the @command{gcc} command for the compilation
2467 @item
2468 Attributes of the unit, including configuration pragmas used, an indication
2469 of whether the compilation was successful, exception model used etc.
2471 @item
2472 A list of relevant restrictions applying to the unit (used for consistency)
2473 checking.
2475 @item
2476 Categorization information (e.g.@: use of pragma @code{Pure}).
2478 @item
2479 Information on all @code{with}'ed units, including presence of
2480 @code{Elaborate} or @code{Elaborate_All} pragmas.
2482 @item
2483 Information from any @code{Linker_Options} pragmas used in the unit
2485 @item
2486 Information on the use of @code{Body_Version} or @code{Version}
2487 attributes in the unit.
2489 @item
2490 Dependency information. This is a list of files, together with
2491 time stamp and checksum information. These are files on which
2492 the unit depends in the sense that recompilation is required
2493 if any of these units are modified.
2495 @item
2496 Cross-reference data. Contains information on all entities referenced
2497 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2498 provide cross-reference information.
2500 @end itemize
2502 @noindent
2503 For a full detailed description of the format of the @file{ALI} file,
2504 see the source of the body of unit @code{Lib.Writ}, contained in file
2505 @file{lib-writ.adb} in the GNAT compiler sources.
2507 @node Binding an Ada Program
2508 @section Binding an Ada Program
2510 @noindent
2511 When using languages such as C and C++, once the source files have been
2512 compiled the only remaining step in building an executable program
2513 is linking the object modules together. This means that it is possible to
2514 link an inconsistent version of a program, in which two units have
2515 included different versions of the same header.
2517 The rules of Ada do not permit such an inconsistent program to be built.
2518 For example, if two clients have different versions of the same package,
2519 it is illegal to build a program containing these two clients.
2520 These rules are enforced by the GNAT binder, which also determines an
2521 elaboration order consistent with the Ada rules.
2523 The GNAT binder is run after all the object files for a program have
2524 been created. It is given the name of the main program unit, and from
2525 this it determines the set of units required by the program, by reading the
2526 corresponding ALI files. It generates error messages if the program is
2527 inconsistent or if no valid order of elaboration exists.
2529 If no errors are detected, the binder produces a main program, in Ada by
2530 default, that contains calls to the elaboration procedures of those
2531 compilation unit that require them, followed by
2532 a call to the main program. This Ada program is compiled to generate the
2533 object file for the main program. The name of
2534 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2535 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2536 main program unit.
2538 Finally, the linker is used to build the resulting executable program,
2539 using the object from the main program from the bind step as well as the
2540 object files for the Ada units of the program.
2542 @node Mixed Language Programming
2543 @section Mixed Language Programming
2544 @cindex Mixed Language Programming
2546 @noindent
2547 This section describes how to develop a mixed-language program,
2548 specifically one that comprises units in both Ada and C.
2550 @menu
2551 * Interfacing to C::
2552 * Calling Conventions::
2553 @end menu
2555 @node Interfacing to C
2556 @subsection Interfacing to C
2557 @noindent
2558 Interfacing Ada with a foreign language such as C involves using
2559 compiler directives to import and/or export entity definitions in each
2560 language---using @code{extern} statements in C, for instance, and the
2561 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2562 A full treatment of these topics is provided in Appendix B, section 1
2563 of the Ada Reference Manual.
2565 There are two ways to build a program using GNAT that contains some Ada
2566 sources and some foreign language sources, depending on whether or not
2567 the main subprogram is written in Ada.  Here is a source example with
2568 the main subprogram in Ada:
2570 @smallexample
2571 /* file1.c */
2572 #include <stdio.h>
2574 void print_num (int num)
2576   printf ("num is %d.\n", num);
2577   return;
2580 /* file2.c */
2582 /* num_from_Ada is declared in my_main.adb */
2583 extern int num_from_Ada;
2585 int get_num (void)
2587   return num_from_Ada;
2589 @end smallexample
2591 @smallexample @c ada
2592 --  my_main.adb
2593 procedure My_Main is
2595    --  Declare then export an Integer entity called num_from_Ada
2596    My_Num : Integer := 10;
2597    pragma Export (C, My_Num, "num_from_Ada");
2599    --  Declare an Ada function spec for Get_Num, then use
2600    --  C function get_num for the implementation.
2601    function Get_Num return Integer;
2602    pragma Import (C, Get_Num, "get_num");
2604    --  Declare an Ada procedure spec for Print_Num, then use
2605    --  C function print_num for the implementation.
2606    procedure Print_Num (Num : Integer);
2607    pragma Import (C, Print_Num, "print_num");
2609 begin
2610    Print_Num (Get_Num);
2611 end My_Main;
2612 @end smallexample
2614 @enumerate
2615 @item
2616 To build this example, first compile the foreign language files to
2617 generate object files:
2618 @smallexample
2619 ^gcc -c file1.c^gcc -c FILE1.C^
2620 ^gcc -c file2.c^gcc -c FILE2.C^
2621 @end smallexample
2623 @item
2624 Then, compile the Ada units to produce a set of object files and ALI
2625 files:
2626 @smallexample
2627 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2628 @end smallexample
2630 @item
2631 Run the Ada binder on the Ada main program:
2632 @smallexample
2633 gnatbind my_main.ali
2634 @end smallexample
2636 @item
2637 Link the Ada main program, the Ada objects and the other language
2638 objects:
2639 @smallexample
2640 gnatlink my_main.ali file1.o file2.o
2641 @end smallexample
2642 @end enumerate
2644 The last three steps can be grouped in a single command:
2645 @smallexample
2646 gnatmake my_main.adb -largs file1.o file2.o
2647 @end smallexample
2649 @cindex Binder output file
2650 @noindent
2651 If the main program is in a language other than Ada, then you may have
2652 more than one entry point into the Ada subsystem. You must use a special
2653 binder option to generate callable routines that initialize and
2654 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2655 Calls to the initialization and finalization routines must be inserted
2656 in the main program, or some other appropriate point in the code. The
2657 call to initialize the Ada units must occur before the first Ada
2658 subprogram is called, and the call to finalize the Ada units must occur
2659 after the last Ada subprogram returns. The binder will place the
2660 initialization and finalization subprograms into the
2661 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2662 sources.  To illustrate, we have the following example:
2664 @smallexample
2665 /* main.c */
2666 extern void adainit (void);
2667 extern void adafinal (void);
2668 extern int add (int, int);
2669 extern int sub (int, int);
2671 int main (int argc, char *argv[])
2673   int a = 21, b = 7;
2675   adainit();
2677   /* Should print "21 + 7 = 28" */
2678   printf ("%d + %d = %d\n", a, b, add (a, b));
2679   /* Should print "21 - 7 = 14" */
2680   printf ("%d - %d = %d\n", a, b, sub (a, b));
2682   adafinal();
2684 @end smallexample
2686 @smallexample @c ada
2687 --  unit1.ads
2688 package Unit1 is
2689    function Add (A, B : Integer) return Integer;
2690    pragma Export (C, Add, "add");
2691 end Unit1;
2693 --  unit1.adb
2694 package body Unit1 is
2695    function Add (A, B : Integer) return Integer is
2696    begin
2697       return A + B;
2698    end Add;
2699 end Unit1;
2701 --  unit2.ads
2702 package Unit2 is
2703    function Sub (A, B : Integer) return Integer;
2704    pragma Export (C, Sub, "sub");
2705 end Unit2;
2707 --  unit2.adb
2708 package body Unit2 is
2709    function Sub (A, B : Integer) return Integer is
2710    begin
2711       return A - B;
2712    end Sub;
2713 end Unit2;
2714 @end smallexample
2716 @enumerate
2717 @item
2718 The build procedure for this application is similar to the last
2719 example's.  First, compile the foreign language files to generate object
2720 files:
2721 @smallexample
2722 ^gcc -c main.c^gcc -c main.c^
2723 @end smallexample
2725 @item
2726 Next, compile the Ada units to produce a set of object files and ALI
2727 files:
2728 @smallexample
2729 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2730 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2731 @end smallexample
2733 @item
2734 Run the Ada binder on every generated ALI file.  Make sure to use the
2735 @option{-n} option to specify a foreign main program:
2736 @smallexample
2737 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2738 @end smallexample
2740 @item
2741 Link the Ada main program, the Ada objects and the foreign language
2742 objects. You need only list the last ALI file here:
2743 @smallexample
2744 gnatlink unit2.ali main.o -o exec_file
2745 @end smallexample
2747 This procedure yields a binary executable called @file{exec_file}.
2748 @end enumerate
2750 @noindent
2751 Depending on the circumstances (for example when your non-Ada main object
2752 does not provide symbol @code{main}), you may also need to instruct the
2753 GNAT linker not to include the standard startup objects by passing the
2754 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2756 @node Calling Conventions
2757 @subsection Calling Conventions
2758 @cindex Foreign Languages
2759 @cindex Calling Conventions
2760 GNAT follows standard calling sequence conventions and will thus interface
2761 to any other language that also follows these conventions. The following
2762 Convention identifiers are recognized by GNAT:
2764 @table @code
2765 @cindex Interfacing to Ada
2766 @cindex Other Ada compilers
2767 @cindex Convention Ada
2768 @item Ada
2769 This indicates that the standard Ada calling sequence will be
2770 used and all Ada data items may be passed without any limitations in the
2771 case where GNAT is used to generate both the caller and callee. It is also
2772 possible to mix GNAT generated code and code generated by another Ada
2773 compiler. In this case, the data types should be restricted to simple
2774 cases, including primitive types. Whether complex data types can be passed
2775 depends on the situation. Probably it is safe to pass simple arrays, such
2776 as arrays of integers or floats. Records may or may not work, depending
2777 on whether both compilers lay them out identically. Complex structures
2778 involving variant records, access parameters, tasks, or protected types,
2779 are unlikely to be able to be passed.
2781 Note that in the case of GNAT running
2782 on a platform that supports HP Ada 83, a higher degree of compatibility
2783 can be guaranteed, and in particular records are layed out in an identical
2784 manner in the two compilers. Note also that if output from two different
2785 compilers is mixed, the program is responsible for dealing with elaboration
2786 issues. Probably the safest approach is to write the main program in the
2787 version of Ada other than GNAT, so that it takes care of its own elaboration
2788 requirements, and then call the GNAT-generated adainit procedure to ensure
2789 elaboration of the GNAT components. Consult the documentation of the other
2790 Ada compiler for further details on elaboration.
2792 However, it is not possible to mix the tasking run time of GNAT and
2793 HP Ada 83, All the tasking operations must either be entirely within
2794 GNAT compiled sections of the program, or entirely within HP Ada 83
2795 compiled sections of the program.
2797 @cindex Interfacing to Assembly
2798 @cindex Convention Assembler
2799 @item Assembler
2800 Specifies assembler as the convention. In practice this has the
2801 same effect as convention Ada (but is not equivalent in the sense of being
2802 considered the same convention).
2804 @cindex Convention Asm
2805 @findex Asm
2806 @item Asm
2807 Equivalent to Assembler.
2809 @cindex Interfacing to COBOL
2810 @cindex Convention COBOL
2811 @findex COBOL
2812 @item COBOL
2813 Data will be passed according to the conventions described
2814 in section B.4 of the Ada Reference Manual.
2816 @findex C
2817 @cindex Interfacing to C
2818 @cindex Convention C
2819 @item C
2820 Data will be passed according to the conventions described
2821 in section B.3 of the Ada Reference Manual.
2823 A note on interfacing to a C ``varargs'' function:
2824 @findex C varargs function
2825 @cindex Interfacing to C varargs function
2826 @cindex varargs function interfaces
2828 @itemize @bullet
2829 @item
2830 In C, @code{varargs} allows a function to take a variable number of
2831 arguments. There is no direct equivalent in this to Ada. One
2832 approach that can be used is to create a C wrapper for each
2833 different profile and then interface to this C wrapper. For
2834 example, to print an @code{int} value using @code{printf},
2835 create a C function @code{printfi} that takes two arguments, a
2836 pointer to a string and an int, and calls @code{printf}.
2837 Then in the Ada program, use pragma @code{Import} to
2838 interface to @code{printfi}.
2840 @item
2841 It may work on some platforms to directly interface to
2842 a @code{varargs} function by providing a specific Ada profile
2843 for a particular call. However, this does not work on
2844 all platforms, since there is no guarantee that the
2845 calling sequence for a two argument normal C function
2846 is the same as for calling a @code{varargs} C function with
2847 the same two arguments.
2848 @end itemize
2850 @cindex Convention Default
2851 @findex Default
2852 @item Default
2853 Equivalent to C.
2855 @cindex Convention External
2856 @findex External
2857 @item External
2858 Equivalent to C.
2860 @ifclear vms
2861 @findex C++
2862 @cindex Interfacing to C++
2863 @cindex Convention C++
2864 @item C_Plus_Plus (or CPP)
2865 This stands for C++. For most purposes this is identical to C.
2866 See the separate description of the specialized GNAT pragmas relating to
2867 C++ interfacing for further details.
2868 @end ifclear
2870 @findex Fortran
2871 @cindex Interfacing to Fortran
2872 @cindex Convention Fortran
2873 @item Fortran
2874 Data will be passed according to the conventions described
2875 in section B.5 of the Ada Reference Manual.
2877 @item Intrinsic
2878 This applies to an intrinsic operation, as defined in the Ada
2879 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2880 this means that the body of the subprogram is provided by the compiler itself,
2881 usually by means of an efficient code sequence, and that the user does not
2882 supply an explicit body for it. In an application program, the pragma may
2883 be applied to the following sets of names:
2885 @itemize @bullet
2886 @item
2887 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2888 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2889 two formal parameters. The
2890 first one must be a signed integer type or a modular type with a binary
2891 modulus, and the second parameter must be of type Natural.
2892 The return type must be the same as the type of the first argument. The size
2893 of this type can only be 8, 16, 32, or 64.
2895 @item
2896 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2897 The corresponding operator declaration must have parameters and result type
2898 that have the same root numeric type (for example, all three are long_float
2899 types). This simplifies the definition of operations that use type checking
2900 to perform dimensional checks:
2902 @smallexample @c ada
2903 type Distance is new Long_Float;
2904 type Time     is new Long_Float;
2905 type Velocity is new Long_Float;
2906 function "/" (D : Distance; T : Time)
2907   return Velocity;
2908 pragma Import (Intrinsic, "/");
2909 @end smallexample
2911 @noindent
2912 This common idiom is often programmed with a generic definition and an
2913 explicit body. The pragma makes it simpler to introduce such declarations.
2914 It incurs no overhead in compilation time or code size, because it is
2915 implemented as a single machine instruction.
2917 @item
2918 General subprogram entities, to bind an Ada subprogram declaration to
2919 a compiler builtin by name with back-ends where such interfaces are
2920 available. A typical example is the set of ``__builtin'' functions
2921 exposed by the GCC back-end, as in the following example:
2923 @smallexample @c ada
2924    function builtin_sqrt (F : Float) return Float;
2925    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2926 @end smallexample
2928 Most of the GCC builtins are accessible this way, and as for other
2929 import conventions (e.g. C), it is the user's responsibility to ensure
2930 that the Ada subprogram profile matches the underlying builtin
2931 expectations.
2932 @end itemize
2934 @noindent
2936 @ifset unw
2937 @findex Stdcall
2938 @cindex Convention Stdcall
2939 @item Stdcall
2940 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2941 and specifies that the @code{Stdcall} calling sequence will be used,
2942 as defined by the NT API. Nevertheless, to ease building
2943 cross-platform bindings this convention will be handled as a @code{C} calling
2944 convention on non-Windows platforms.
2946 @findex DLL
2947 @cindex Convention DLL
2948 @item DLL
2949 This is equivalent to @code{Stdcall}.
2951 @findex Win32
2952 @cindex Convention Win32
2953 @item Win32
2954 This is equivalent to @code{Stdcall}.
2955 @end ifset
2957 @findex Stubbed
2958 @cindex Convention Stubbed
2959 @item Stubbed
2960 This is a special convention that indicates that the compiler
2961 should provide a stub body that raises @code{Program_Error}.
2962 @end table
2964 @noindent
2965 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2966 that can be used to parameterize conventions and allow additional synonyms
2967 to be specified. For example if you have legacy code in which the convention
2968 identifier Fortran77 was used for Fortran, you can use the configuration
2969 pragma:
2971 @smallexample @c ada
2972 pragma Convention_Identifier (Fortran77, Fortran);
2973 @end smallexample
2975 @noindent
2976 And from now on the identifier Fortran77 may be used as a convention
2977 identifier (for example in an @code{Import} pragma) with the same
2978 meaning as Fortran.
2980 @ifclear vms
2981 @node Building Mixed Ada & C++ Programs
2982 @section Building Mixed Ada and C++ Programs
2984 @noindent
2985 A programmer inexperienced with mixed-language development may find that
2986 building an application containing both Ada and C++ code can be a
2987 challenge.  This section gives a few
2988 hints that should make this task easier. The first section addresses
2989 the differences between interfacing with C and interfacing with C++.
2990 The second section
2991 looks into the delicate problem of linking the complete application from
2992 its Ada and C++ parts. The last section gives some hints on how the GNAT
2993 run-time library can be adapted in order to allow inter-language dispatching
2994 with a new C++ compiler.
2996 @menu
2997 * Interfacing to C++::
2998 * Linking a Mixed C++ & Ada Program::
2999 * A Simple Example::
3000 * Interfacing with C++ constructors::
3001 * Interfacing with C++ at the Class Level::
3002 @end menu
3004 @node Interfacing to C++
3005 @subsection Interfacing to C++
3007 @noindent
3008 GNAT supports interfacing with the G++ compiler (or any C++ compiler
3009 generating code that is compatible with the G++ Application Binary
3010 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
3012 @noindent
3013 Interfacing can be done at 3 levels: simple data, subprograms, and
3014 classes. In the first two cases, GNAT offers a specific @code{Convention
3015 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
3016 Usually, C++ mangles the names of subprograms. To generate proper mangled
3017 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
3018 This problem can also be addressed manually in two ways:
3020 @itemize @bullet
3021 @item
3022 by modifying the C++ code in order to force a C convention using
3023 the @code{extern "C"} syntax.
3025 @item
3026 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3027 Link_Name argument of the pragma import.
3028 @end itemize
3030 @noindent
3031 Interfacing at the class level can be achieved by using the GNAT specific
3032 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3033 gnat_rm, GNAT Reference Manual}, for additional information.
3035 @node Linking a Mixed C++ & Ada Program
3036 @subsection Linking a Mixed C++ & Ada Program
3038 @noindent
3039 Usually the linker of the C++ development system must be used to link
3040 mixed applications because most C++ systems will resolve elaboration
3041 issues (such as calling constructors on global class instances)
3042 transparently during the link phase. GNAT has been adapted to ease the
3043 use of a foreign linker for the last phase. Three cases can be
3044 considered:
3045 @enumerate
3047 @item
3048 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3049 The C++ linker can simply be called by using the C++ specific driver
3050 called @code{g++}.
3052 Note that if the C++ code uses inline functions, you will need to
3053 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3054 order to provide an existing function implementation that the Ada code can
3055 link with.
3057 @smallexample
3058 $ g++ -c -fkeep-inline-functions file1.C
3059 $ g++ -c -fkeep-inline-functions file2.C
3060 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3061 @end smallexample
3063 @item
3064 Using GNAT and G++ from two different GCC installations: If both
3065 compilers are on the @env{PATH}, the previous method may be used. It is
3066 important to note that environment variables such as
3067 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3068 @env{GCC_ROOT} will affect both compilers
3069 at the same time and may make one of the two compilers operate
3070 improperly if set during invocation of the wrong compiler.  It is also
3071 very important that the linker uses the proper @file{libgcc.a} GCC
3072 library -- that is, the one from the C++ compiler installation. The
3073 implicit link command as suggested in the @command{gnatmake} command
3074 from the former example can be replaced by an explicit link command with
3075 the full-verbosity option in order to verify which library is used:
3076 @smallexample
3077 $ gnatbind ada_unit
3078 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3079 @end smallexample
3080 If there is a problem due to interfering environment variables, it can
3081 be worked around by using an intermediate script. The following example
3082 shows the proper script to use when GNAT has not been installed at its
3083 default location and g++ has been installed at its default location:
3085 @smallexample
3086 $ cat ./my_script
3087 #!/bin/sh
3088 unset BINUTILS_ROOT
3089 unset GCC_ROOT
3090 c++ $*
3091 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3092 @end smallexample
3094 @item
3095 Using a non-GNU C++ compiler: The commands previously described can be
3096 used to insure that the C++ linker is used. Nonetheless, you need to add
3097 a few more parameters to the link command line, depending on the exception
3098 mechanism used.
3100 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3101 to the libgcc libraries are required:
3103 @smallexample
3104 $ cat ./my_script
3105 #!/bin/sh
3106 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3107 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3108 @end smallexample
3110 Where CC is the name of the non-GNU C++ compiler.
3112 If the @code{zero cost} exception mechanism is used, and the platform
3113 supports automatic registration of exception tables (e.g.@: Solaris),
3114 paths to more objects are required:
3116 @smallexample
3117 $ cat ./my_script
3118 #!/bin/sh
3119 CC `gcc -print-file-name=crtbegin.o` $* \
3120 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3121 `gcc -print-file-name=crtend.o`
3122 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3123 @end smallexample
3125 If the @code{zero cost} exception mechanism is used, and the platform
3126 doesn't support automatic registration of exception tables (e.g.@: HP-UX
3127 or AIX), the simple approach described above will not work and
3128 a pre-linking phase using GNAT will be necessary.
3130 @end enumerate
3132 Another alternative is to use the @command{gprbuild} multi-language builder
3133 which has a large knowledge base and knows how to link Ada and C++ code
3134 together automatically in most cases.
3136 @node A Simple Example
3137 @subsection  A Simple Example
3138 @noindent
3139 The following example, provided as part of the GNAT examples, shows how
3140 to achieve procedural interfacing between Ada and C++ in both
3141 directions. The C++ class A has two methods. The first method is exported
3142 to Ada by the means of an extern C wrapper function. The second method
3143 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3144 a limited record with a layout comparable to the C++ class. The Ada
3145 subprogram, in turn, calls the C++ method. So, starting from the C++
3146 main program, the process passes back and forth between the two
3147 languages.
3149 @noindent
3150 Here are the compilation commands:
3151 @smallexample
3152 $ gnatmake -c simple_cpp_interface
3153 $ g++ -c cpp_main.C
3154 $ g++ -c ex7.C
3155 $ gnatbind -n simple_cpp_interface
3156 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3157       -lstdc++ ex7.o cpp_main.o
3158 @end smallexample
3160 @noindent
3161 Here are the corresponding sources:
3162 @smallexample
3164 //cpp_main.C
3166 #include "ex7.h"
3168 extern "C" @{
3169   void adainit (void);
3170   void adafinal (void);
3171   void method1 (A *t);
3174 void method1 (A *t)
3176   t->method1 ();
3179 int main ()
3181   A obj;
3182   adainit ();
3183   obj.method2 (3030);
3184   adafinal ();
3187 //ex7.h
3189 class Origin @{
3190  public:
3191   int o_value;
3193 class A : public Origin @{
3194  public:
3195   void method1 (void);
3196   void method2 (int v);
3197   A();
3198   int   a_value;
3201 //ex7.C
3203 #include "ex7.h"
3204 #include <stdio.h>
3206 extern "C" @{ void ada_method2 (A *t, int v);@}
3208 void A::method1 (void)
3210   a_value = 2020;
3211   printf ("in A::method1, a_value = %d \n",a_value);
3215 void A::method2 (int v)
3217    ada_method2 (this, v);
3218    printf ("in A::method2, a_value = %d \n",a_value);
3222 A::A(void)
3224    a_value = 1010;
3225   printf ("in A::A, a_value = %d \n",a_value);
3227 @end smallexample
3229 @smallexample @c ada
3230 -- Ada sources
3231 package body Simple_Cpp_Interface is
3233    procedure Ada_Method2 (This : in out A; V : Integer) is
3234    begin
3235       Method1 (This);
3236       This.A_Value := V;
3237    end Ada_Method2;
3239 end Simple_Cpp_Interface;
3241 with System;
3242 package Simple_Cpp_Interface is
3243    type A is limited
3244       record
3245          Vptr    : System.Address;
3246          O_Value : Integer;
3247          A_Value : Integer;
3248       end record;
3249    pragma Convention (C, A);
3251    procedure Method1 (This : in out A);
3252    pragma Import (C, Method1);
3254    procedure Ada_Method2 (This : in out A; V : Integer);
3255    pragma Export (C, Ada_Method2);
3257 end Simple_Cpp_Interface;
3258 @end smallexample
3260 @node Interfacing with C++ constructors
3261 @subsection Interfacing with C++ constructors
3262 @noindent
3264 In order to interface with C++ constructors GNAT provides the
3265 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3266 gnat_rm, GNAT Reference Manual}, for additional information).
3267 In this section we present some common uses of C++ constructors
3268 in mixed-languages programs in GNAT.
3270 Let us assume that we need to interface with the following
3271 C++ class:
3273 @smallexample
3274 @b{class} Root @{
3275 @b{public}:
3276   int  a_value;
3277   int  b_value;
3278   @b{virtual} int Get_Value ();
3279   Root();              // Default constructor
3280   Root(int v);         // 1st non-default constructor
3281   Root(int v, int w);  // 2nd non-default constructor
3283 @end smallexample
3285 For this purpose we can write the following package spec (further
3286 information on how to build this spec is available in
3287 @ref{Interfacing with C++ at the Class Level} and
3288 @ref{Generating Ada Bindings for C and C++ headers}).
3290 @smallexample @c ada
3291 with Interfaces.C; use Interfaces.C;
3292 package Pkg_Root is
3293   type Root is tagged limited record
3294      A_Value : int;
3295      B_Value : int;
3296   end record;
3297   pragma Import (CPP, Root);
3299   function Get_Value (Obj : Root) return int;
3300   pragma Import (CPP, Get_Value);
3302   function Constructor return Root;
3303   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3305   function Constructor (v : Integer) return Root;
3306   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3308   function Constructor (v, w : Integer) return Root;
3309   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3310 end Pkg_Root;
3311 @end smallexample
3313 On the Ada side the constructor is represented by a function (whose
3314 name is arbitrary) that returns the classwide type corresponding to
3315 the imported C++ class. Although the constructor is described as a
3316 function, it is typically a procedure with an extra implicit argument
3317 (the object being initialized) at the implementation level. GNAT
3318 issues the appropriate call, whatever it is, to get the object
3319 properly initialized.
3321 Constructors can only appear in the following contexts:
3323 @itemize @bullet
3324 @item
3325 On the right side of an initialization of an object of type @var{T}.
3326 @item
3327 On the right side of an initialization of a record component of type @var{T}.
3328 @item
3329 In an Ada 2005 limited aggregate.
3330 @item
3331 In an Ada 2005 nested limited aggregate.
3332 @item
3333 In an Ada 2005 limited aggregate that initializes an object built in
3334 place by an extended return statement.
3335 @end itemize
3337 @noindent
3338 In a declaration of an object whose type is a class imported from C++,
3339 either the default C++ constructor is implicitly called by GNAT, or
3340 else the required C++ constructor must be explicitly called in the
3341 expression that initializes the object. For example:
3343 @smallexample @c ada
3344   Obj1 : Root;
3345   Obj2 : Root := Constructor;
3346   Obj3 : Root := Constructor (v => 10);
3347   Obj4 : Root := Constructor (30, 40);
3348 @end smallexample
3350 The first two declarations are equivalent: in both cases the default C++
3351 constructor is invoked (in the former case the call to the constructor is
3352 implicit, and in the latter case the call is explicit in the object
3353 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3354 that takes an integer argument, and @code{Obj4} is initialized by the
3355 non-default C++ constructor that takes two integers.
3357 Let us derive the imported C++ class in the Ada side. For example:
3359 @smallexample @c ada
3360   type DT is new Root with record
3361      C_Value : Natural := 2009;
3362   end record;
3363 @end smallexample
3365 In this case the components DT inherited from the C++ side must be
3366 initialized by a C++ constructor, and the additional Ada components
3367 of type DT are initialized by GNAT. The initialization of such an
3368 object is done either by default, or by means of a function returning
3369 an aggregate of type DT, or by means of an extension aggregate.
3371 @smallexample @c ada
3372   Obj5 : DT;
3373   Obj6 : DT := Function_Returning_DT (50);
3374   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3375 @end smallexample
3377 The declaration of @code{Obj5} invokes the default constructors: the
3378 C++ default constructor of the parent type takes care of the initialization
3379 of the components inherited from Root, and GNAT takes care of the default
3380 initialization of the additional Ada components of type DT (that is,
3381 @code{C_Value} is initialized to value 2009). The order of invocation of
3382 the constructors is consistent with the order of elaboration required by
3383 Ada and C++. That is, the constructor of the parent type is always called
3384 before the constructor of the derived type.
3386 Let us now consider a record that has components whose type is imported
3387 from C++. For example:
3389 @smallexample @c ada
3390   type Rec1 is limited record
3391      Data1 : Root := Constructor (10);
3392      Value : Natural := 1000;
3393   end record;
3395   type Rec2 (D : Integer := 20) is limited record
3396      Rec   : Rec1;
3397      Data2 : Root := Constructor (D, 30);
3398   end record;
3399 @end smallexample
3401 The initialization of an object of type @code{Rec2} will call the
3402 non-default C++ constructors specified for the imported components.
3403 For example:
3405 @smallexample @c ada
3406   Obj8 : Rec2 (40);
3407 @end smallexample
3409 Using Ada 2005 we can use limited aggregates to initialize an object
3410 invoking C++ constructors that differ from those specified in the type
3411 declarations. For example:
3413 @smallexample @c ada
3414   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3415                           others => <>),
3416                   others => <>);
3417 @end smallexample
3419 The above declaration uses an Ada 2005 limited aggregate to
3420 initialize @code{Obj9}, and the C++ constructor that has two integer
3421 arguments is invoked to initialize the @code{Data1} component instead
3422 of the constructor specified in the declaration of type @code{Rec1}. In
3423 Ada 2005 the box in the aggregate indicates that unspecified components
3424 are initialized using the expression (if any) available in the component
3425 declaration. That is, in this case discriminant @code{D} is initialized
3426 to value @code{20}, @code{Value} is initialized to value 1000, and the
3427 non-default C++ constructor that handles two integers takes care of
3428 initializing component @code{Data2} with values @code{20,30}.
3430 In Ada 2005 we can use the extended return statement to build the Ada
3431 equivalent to C++ non-default constructors. For example:
3433 @smallexample @c ada
3434   function Constructor (V : Integer) return Rec2 is
3435   begin
3436      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3437                                    others => <>),
3438                            others => <>) do
3439         --  Further actions required for construction of
3440         --  objects of type Rec2
3441         ...
3442      end record;
3443   end Constructor;
3444 @end smallexample
3446 In this example the extended return statement construct is used to
3447 build in place the returned object whose components are initialized
3448 by means of a limited aggregate. Any further action associated with
3449 the constructor can be placed inside the construct.
3451 @node Interfacing with C++ at the Class Level
3452 @subsection Interfacing with C++ at the Class Level
3453 @noindent
3454 In this section we demonstrate the GNAT features for interfacing with
3455 C++ by means of an example making use of Ada 2005 abstract interface
3456 types. This example consists of a classification of animals; classes
3457 have been used to model our main classification of animals, and
3458 interfaces provide support for the management of secondary
3459 classifications. We first demonstrate a case in which the types and
3460 constructors are defined on the C++ side and imported from the Ada
3461 side, and latter the reverse case.
3463 The root of our derivation will be the @code{Animal} class, with a
3464 single private attribute (the @code{Age} of the animal) and two public
3465 primitives to set and get the value of this attribute.
3467 @smallexample
3468 @b{class} Animal @{
3469  @b{public}:
3470    @b{virtual} void Set_Age (int New_Age);
3471    @b{virtual} int Age ();
3472  @b{private}:
3473    int Age_Count;
3475 @end smallexample
3477 Abstract interface types are defined in C++ by means of classes with pure
3478 virtual functions and no data members. In our example we will use two
3479 interfaces that provide support for the common management of @code{Carnivore}
3480 and @code{Domestic} animals:
3482 @smallexample
3483 @b{class} Carnivore @{
3484 @b{public}:
3485    @b{virtual} int Number_Of_Teeth () = 0;
3488 @b{class} Domestic @{
3489 @b{public}:
3490    @b{virtual void} Set_Owner (char* Name) = 0;
3492 @end smallexample
3494 Using these declarations, we can now say that a @code{Dog} is an animal that is
3495 both Carnivore and Domestic, that is:
3497 @smallexample
3498 @b{class} Dog : Animal, Carnivore, Domestic @{
3499  @b{public}:
3500    @b{virtual} int  Number_Of_Teeth ();
3501    @b{virtual} void Set_Owner (char* Name);
3503    Dog(); // Constructor
3504  @b{private}:
3505    int  Tooth_Count;
3506    char *Owner;
3508 @end smallexample
3510 In the following examples we will assume that the previous declarations are
3511 located in a file named @code{animals.h}. The following package demonstrates
3512 how to import these C++ declarations from the Ada side:
3514 @smallexample @c ada
3515 with Interfaces.C.Strings; use Interfaces.C.Strings;
3516 package Animals is
3517   type Carnivore is interface;
3518   pragma Convention (C_Plus_Plus, Carnivore);
3519   function Number_Of_Teeth (X : Carnivore)
3520      return Natural is abstract;
3522   type Domestic is interface;
3523   pragma Convention (C_Plus_Plus, Set_Owner);
3524   procedure Set_Owner
3525     (X    : in out Domestic;
3526      Name : Chars_Ptr) is abstract;
3528   type Animal is tagged record
3529     Age : Natural := 0;
3530   end record;
3531   pragma Import (C_Plus_Plus, Animal);
3533   procedure Set_Age (X : in out Animal; Age : Integer);
3534   pragma Import (C_Plus_Plus, Set_Age);
3536   function Age (X : Animal) return Integer;
3537   pragma Import (C_Plus_Plus, Age);
3539   type Dog is new Animal and Carnivore and Domestic with record
3540     Tooth_Count : Natural;
3541     Owner       : String (1 .. 30);
3542   end record;
3543   pragma Import (C_Plus_Plus, Dog);
3545   function Number_Of_Teeth (A : Dog) return Integer;
3546   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3548   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3549   pragma Import (C_Plus_Plus, Set_Owner);
3551   function New_Dog return Dog;
3552   pragma CPP_Constructor (New_Dog);
3553   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3554 end Animals;
3555 @end smallexample
3557 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3558 interfacing with these C++ classes is easy. The only requirement is that all
3559 the primitives and components must be declared exactly in the same order in
3560 the two languages.
3562 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3563 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3564 the arguments to the called primitives will be the same as for C++. For the
3565 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3566 to indicate that they have been defined on the C++ side; this is required
3567 because the dispatch table associated with these tagged types will be built
3568 in the C++ side and therefore will not contain the predefined Ada primitives
3569 which Ada would otherwise expect.
3571 As the reader can see there is no need to indicate the C++ mangled names
3572 associated with each subprogram because it is assumed that all the calls to
3573 these primitives will be dispatching calls. The only exception is the
3574 constructor, which must be registered with the compiler by means of
3575 @code{pragma CPP_Constructor} and needs to provide its associated C++
3576 mangled name because the Ada compiler generates direct calls to it.
3578 With the above packages we can now declare objects of type Dog on the Ada side
3579 and dispatch calls to the corresponding subprograms on the C++ side. We can
3580 also extend the tagged type Dog with further fields and primitives, and
3581 override some of its C++ primitives on the Ada side. For example, here we have
3582 a type derivation defined on the Ada side that inherits all the dispatching
3583 primitives of the ancestor from the C++ side.
3585 @smallexample
3586 @b{with} Animals; @b{use} Animals;
3587 @b{package} Vaccinated_Animals @b{is}
3588   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3589   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3590 @b{end} Vaccinated_Animals;
3591 @end smallexample
3593 It is important to note that, because of the ABI compatibility, the programmer
3594 does not need to add any further information to indicate either the object
3595 layout or the dispatch table entry associated with each dispatching operation.
3597 Now let us define all the types and constructors on the Ada side and export
3598 them to C++, using the same hierarchy of our previous example:
3600 @smallexample @c ada
3601 with Interfaces.C.Strings;
3602 use Interfaces.C.Strings;
3603 package Animals is
3604   type Carnivore is interface;
3605   pragma Convention (C_Plus_Plus, Carnivore);
3606   function Number_Of_Teeth (X : Carnivore)
3607      return Natural is abstract;
3609   type Domestic is interface;
3610   pragma Convention (C_Plus_Plus, Set_Owner);
3611   procedure Set_Owner
3612     (X    : in out Domestic;
3613      Name : Chars_Ptr) is abstract;
3615   type Animal is tagged record
3616     Age : Natural := 0;
3617   end record;
3618   pragma Convention (C_Plus_Plus, Animal);
3620   procedure Set_Age (X : in out Animal; Age : Integer);
3621   pragma Export (C_Plus_Plus, Set_Age);
3623   function Age (X : Animal) return Integer;
3624   pragma Export (C_Plus_Plus, Age);
3626   type Dog is new Animal and Carnivore and Domestic with record
3627     Tooth_Count : Natural;
3628     Owner       : String (1 .. 30);
3629   end record;
3630   pragma Convention (C_Plus_Plus, Dog);
3632   function Number_Of_Teeth (A : Dog) return Integer;
3633   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3635   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3636   pragma Export (C_Plus_Plus, Set_Owner);
3638   function New_Dog return Dog'Class;
3639   pragma Export (C_Plus_Plus, New_Dog);
3640 end Animals;
3641 @end smallexample
3643 Compared with our previous example the only difference is the use of
3644 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3645 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3646 nothing else to be done; as explained above, the only requirement is that all
3647 the primitives and components are declared in exactly the same order.
3649 For completeness, let us see a brief C++ main program that uses the
3650 declarations available in @code{animals.h} (presented in our first example) to
3651 import and use the declarations from the Ada side, properly initializing and
3652 finalizing the Ada run-time system along the way:
3654 @smallexample
3655 @b{#include} "animals.h"
3656 @b{#include} <iostream>
3657 @b{using namespace} std;
3659 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3660 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3661 void Check_Animal (Animal *obj)       @{@dots{}@}
3662 void Check_Dog (Dog *obj)             @{@dots{}@}
3664 @b{extern} "C" @{
3665   void adainit (void);
3666   void adafinal (void);
3667   Dog* new_dog ();
3670 void test ()
3672   Dog *obj = new_dog();  // Ada constructor
3673   Check_Carnivore (obj); // Check secondary DT
3674   Check_Domestic (obj);  // Check secondary DT
3675   Check_Animal (obj);    // Check primary DT
3676   Check_Dog (obj);       // Check primary DT
3679 int main ()
3681   adainit ();  test();  adafinal ();
3682   return 0;
3684 @end smallexample
3686 @node Comparison between GNAT and C/C++ Compilation Models
3687 @section Comparison between GNAT and C/C++ Compilation Models
3689 @noindent
3690 The GNAT model of compilation is close to the C and C++ models. You can
3691 think of Ada specs as corresponding to header files in C. As in C, you
3692 don't need to compile specs; they are compiled when they are used. The
3693 Ada @code{with} is similar in effect to the @code{#include} of a C
3694 header.
3696 One notable difference is that, in Ada, you may compile specs separately
3697 to check them for semantic and syntactic accuracy. This is not always
3698 possible with C headers because they are fragments of programs that have
3699 less specific syntactic or semantic rules.
3701 The other major difference is the requirement for running the binder,
3702 which performs two important functions. First, it checks for
3703 consistency. In C or C++, the only defense against assembling
3704 inconsistent programs lies outside the compiler, in a makefile, for
3705 example. The binder satisfies the Ada requirement that it be impossible
3706 to construct an inconsistent program when the compiler is used in normal
3707 mode.
3709 @cindex Elaboration order control
3710 The other important function of the binder is to deal with elaboration
3711 issues. There are also elaboration issues in C++ that are handled
3712 automatically. This automatic handling has the advantage of being
3713 simpler to use, but the C++ programmer has no control over elaboration.
3714 Where @code{gnatbind} might complain there was no valid order of
3715 elaboration, a C++ compiler would simply construct a program that
3716 malfunctioned at run time.
3717 @end ifclear
3719 @node Comparison between GNAT and Conventional Ada Library Models
3720 @section Comparison between GNAT and Conventional Ada Library Models
3722 @noindent
3723 This section is intended for Ada programmers who have
3724 used an Ada compiler implementing the traditional Ada library
3725 model, as described in the Ada Reference Manual.
3727 @cindex GNAT library
3728 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3729 source files themselves acts as the library. Compiling Ada programs does
3730 not generate any centralized information, but rather an object file and
3731 a ALI file, which are of interest only to the binder and linker.
3732 In a traditional system, the compiler reads information not only from
3733 the source file being compiled, but also from the centralized library.
3734 This means that the effect of a compilation depends on what has been
3735 previously compiled. In particular:
3737 @itemize @bullet
3738 @item
3739 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3740 to the version of the unit most recently compiled into the library.
3742 @item
3743 Inlining is effective only if the necessary body has already been
3744 compiled into the library.
3746 @item
3747 Compiling a unit may obsolete other units in the library.
3748 @end itemize
3750 @noindent
3751 In GNAT, compiling one unit never affects the compilation of any other
3752 units because the compiler reads only source files. Only changes to source
3753 files can affect the results of a compilation. In particular:
3755 @itemize @bullet
3756 @item
3757 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3758 to the source version of the unit that is currently accessible to the
3759 compiler.
3761 @item
3762 @cindex Inlining
3763 Inlining requires the appropriate source files for the package or
3764 subprogram bodies to be available to the compiler. Inlining is always
3765 effective, independent of the order in which units are complied.
3767 @item
3768 Compiling a unit never affects any other compilations. The editing of
3769 sources may cause previous compilations to be out of date if they
3770 depended on the source file being modified.
3771 @end itemize
3773 @noindent
3774 The most important result of these differences is that order of compilation
3775 is never significant in GNAT. There is no situation in which one is
3776 required to do one compilation before another. What shows up as order of
3777 compilation requirements in the traditional Ada library becomes, in
3778 GNAT, simple source dependencies; in other words, there is only a set
3779 of rules saying what source files must be present when a file is
3780 compiled.
3782 @ifset vms
3783 @node Placement of temporary files
3784 @section Placement of temporary files
3785 @cindex Temporary files (user control over placement)
3787 @noindent
3788 GNAT creates temporary files in the directory designated by the environment
3789 variable @env{TMPDIR}.
3790 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3791 for detailed information on how environment variables are resolved.
3792 For most users the easiest way to make use of this feature is to simply
3793 define @env{TMPDIR} as a job level logical name).
3794 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3795 for compiler temporary files, then you can include something like the
3796 following command in your @file{LOGIN.COM} file:
3798 @smallexample
3799 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3800 @end smallexample
3802 @noindent
3803 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3804 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3805 designated by @env{TEMP}.
3806 If none of these environment variables are defined then GNAT uses the
3807 directory designated by the logical name @code{SYS$SCRATCH:}
3808 (by default the user's home directory). If all else fails
3809 GNAT uses the current directory for temporary files.
3810 @end ifset
3812 @c *************************
3813 @node Compiling Using gcc
3814 @chapter Compiling Using @command{gcc}
3816 @noindent
3817 This chapter discusses how to compile Ada programs using the @command{gcc}
3818 command. It also describes the set of switches
3819 that can be used to control the behavior of the compiler.
3820 @menu
3821 * Compiling Programs::
3822 * Switches for gcc::
3823 * Search Paths and the Run-Time Library (RTL)::
3824 * Order of Compilation Issues::
3825 * Examples::
3826 @end menu
3828 @node Compiling Programs
3829 @section Compiling Programs
3831 @noindent
3832 The first step in creating an executable program is to compile the units
3833 of the program using the @command{gcc} command. You must compile the
3834 following files:
3836 @itemize @bullet
3837 @item
3838 the body file (@file{.adb}) for a library level subprogram or generic
3839 subprogram
3841 @item
3842 the spec file (@file{.ads}) for a library level package or generic
3843 package that has no body
3845 @item
3846 the body file (@file{.adb}) for a library level package
3847 or generic package that has a body
3849 @end itemize
3851 @noindent
3852 You need @emph{not} compile the following files
3854 @itemize @bullet
3856 @item
3857 the spec of a library unit which has a body
3859 @item
3860 subunits
3861 @end itemize
3863 @noindent
3864 because they are compiled as part of compiling related units. GNAT
3865 package specs
3866 when the corresponding body is compiled, and subunits when the parent is
3867 compiled.
3869 @cindex cannot generate code
3870 If you attempt to compile any of these files, you will get one of the
3871 following error messages (where @var{fff} is the name of the file you
3872 compiled):
3874 @smallexample
3875 cannot generate code for file @var{fff} (package spec)
3876 to check package spec, use -gnatc
3878 cannot generate code for file @var{fff} (missing subunits)
3879 to check parent unit, use -gnatc
3881 cannot generate code for file @var{fff} (subprogram spec)
3882 to check subprogram spec, use -gnatc
3884 cannot generate code for file @var{fff} (subunit)
3885 to check subunit, use -gnatc
3886 @end smallexample
3888 @noindent
3889 As indicated by the above error messages, if you want to submit
3890 one of these files to the compiler to check for correct semantics
3891 without generating code, then use the @option{-gnatc} switch.
3893 The basic command for compiling a file containing an Ada unit is
3895 @smallexample
3896 @c $ gcc -c @ovar{switches} @file{file name}
3897 @c Expanding @ovar macro inline (explanation in macro def comments)
3898 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3899 @end smallexample
3901 @noindent
3902 where @var{file name} is the name of the Ada file (usually
3903 having an extension
3904 @file{.ads} for a spec or @file{.adb} for a body).
3905 @ifclear vms
3906 You specify the
3907 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3908 @end ifclear
3909 The result of a successful compilation is an object file, which has the
3910 same name as the source file but an extension of @file{.o} and an Ada
3911 Library Information (ALI) file, which also has the same name as the
3912 source file, but with @file{.ali} as the extension. GNAT creates these
3913 two output files in the current directory, but you may specify a source
3914 file in any directory using an absolute or relative path specification
3915 containing the directory information.
3917 @findex gnat1
3918 @command{gcc} is actually a driver program that looks at the extensions of
3919 the file arguments and loads the appropriate compiler. For example, the
3920 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3921 These programs are in directories known to the driver program (in some
3922 configurations via environment variables you set), but need not be in
3923 your path. The @command{gcc} driver also calls the assembler and any other
3924 utilities needed to complete the generation of the required object
3925 files.
3927 It is possible to supply several file names on the same @command{gcc}
3928 command. This causes @command{gcc} to call the appropriate compiler for
3929 each file. For example, the following command lists three separate
3930 files to be compiled:
3932 @smallexample
3933 $ gcc -c x.adb y.adb z.c
3934 @end smallexample
3936 @noindent
3937 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3938 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3939 The compiler generates three object files @file{x.o}, @file{y.o} and
3940 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3941 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3942 @ifclear vms
3943 except for
3944 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3945 @end ifclear
3947 @node Switches for gcc
3948 @section Switches for @command{gcc}
3950 @noindent
3951 The @command{gcc} command accepts switches that control the
3952 compilation process. These switches are fully described in this section.
3953 First we briefly list all the switches, in alphabetical order, then we
3954 describe the switches in more detail in functionally grouped sections.
3956 More switches exist for GCC than those documented here, especially
3957 for specific targets. However, their use is not recommended as
3958 they may change code generation in ways that are incompatible with
3959 the Ada run-time library, or can cause inconsistencies between
3960 compilation units.
3962 @menu
3963 * Output and Error Message Control::
3964 * Warning Message Control::
3965 * Debugging and Assertion Control::
3966 * Validity Checking::
3967 * Style Checking::
3968 * Run-Time Checks::
3969 * Using gcc for Syntax Checking::
3970 * Using gcc for Semantic Checking::
3971 * Compiling Different Versions of Ada::
3972 * Character Set Control::
3973 * File Naming Control::
3974 * Subprogram Inlining Control::
3975 * Auxiliary Output Control::
3976 * Debugging Control::
3977 * Exception Handling Control::
3978 * Units to Sources Mapping Files::
3979 * Integrated Preprocessing::
3980 * Code Generation Control::
3981 @ifset vms
3982 * Return Codes::
3983 @end ifset
3984 @end menu
3986 @table @option
3987 @c !sort!
3988 @ifclear vms
3989 @cindex @option{-b} (@command{gcc})
3990 @item -b @var{target}
3991 Compile your program to run on @var{target}, which is the name of a
3992 system configuration. You must have a GNAT cross-compiler built if
3993 @var{target} is not the same as your host system.
3995 @item -B@var{dir}
3996 @cindex @option{-B} (@command{gcc})
3997 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3998 from @var{dir} instead of the default location. Only use this switch
3999 when multiple versions of the GNAT compiler are available.
4000 @xref{Directory Options,, Options for Directory Search, gcc, Using the
4001 GNU Compiler Collection (GCC)}, for further details. You would normally
4002 use the @option{-b} or @option{-V} switch instead.
4004 @item -c
4005 @cindex @option{-c} (@command{gcc})
4006 Compile. Always use this switch when compiling Ada programs.
4008 Note: for some other languages when using @command{gcc}, notably in
4009 the case of C and C++, it is possible to use
4010 use @command{gcc} without a @option{-c} switch to
4011 compile and link in one step. In the case of GNAT, you
4012 cannot use this approach, because the binder must be run
4013 and @command{gcc} cannot be used to run the GNAT binder.
4014 @end ifclear
4016 @item -fcallgraph-info@r{[}=su,da@r{]}
4017 @cindex @option{-fcallgraph-info} (@command{gcc})
4018 Makes the compiler output callgraph information for the program, on a
4019 per-file basis. The information is generated in the VCG format.  It can
4020 be decorated with additional, per-node and/or per-edge information, if a
4021 list of comma-separated markers is additionally specified. When the
4022 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
4023 marker is specified, the callgraph is decorated with information about
4024 dynamically allocated objects.
4026 @item -fdump-scos
4027 @cindex @option{-fdump-scos} (@command{gcc})
4028 Generates SCO (Source Coverage Obligation) information in the ALI file.
4029 This information is used by advanced coverage tools. See unit @file{SCOs}
4030 in the compiler sources for details in files @file{scos.ads} and
4031 @file{scos.adb}.
4033 @item -flto@r{[}=n@r{]}
4034 @cindex @option{-flto} (@command{gcc})
4035 Enables Link Time Optimization. This switch must be used in conjunction
4036 with the traditional @option{-Ox} switches and instructs the compiler to
4037 defer most optimizations until the link stage. The advantage of this
4038 approach is that the compiler can do a whole-program analysis and choose
4039 the best interprocedural optimization strategy based on a complete view
4040 of the program, instead of a fragmentary view with the usual approach.
4041 This can also speed up the compilation of huge programs and reduce the
4042 size of the final executable, compared with a per-unit compilation with
4043 full inlining across modules enabled with the @option{-gnatn2} switch.
4044 The drawback of this approach is that it may require much more memory.
4045 The switch, as well as the accompanying @option{-Ox} switches, must be
4046 specified both for the compilation and the link phases.
4047 If the @var{n} parameter is specified, the optimization and final code
4048 generation at link time are executed using @var{n} parallel jobs by
4049 means of an installed @command{make} program.
4051 @item -fno-inline
4052 @cindex @option{-fno-inline} (@command{gcc})
4053 Suppresses all inlining, even if other optimization or inlining
4054 switches are set.  This includes suppression of inlining that
4055 results from the use of the pragma @code{Inline_Always}.
4056 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4057 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4058 effects if this switch is present.  Note that inlining can also
4059 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
4061 @item -fno-inline-functions
4062 @cindex @option{-fno-inline-functions} (@command{gcc})
4063 Suppresses automatic inlining of subprograms, which is enabled
4064 if @option{-O3} is used.
4066 @item -fno-inline-small-functions
4067 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4068 Suppresses automatic inlining of small subprograms, which is enabled
4069 if @option{-O2} is used.
4071 @item -fno-inline-functions-called-once
4072 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4073 Suppresses inlining of subprograms local to the unit and called once
4074 from within it, which is enabled if @option{-O1} is used.
4076 @item -fno-ivopts
4077 @cindex @option{-fno-ivopts} (@command{gcc})
4078 Suppresses high-level loop induction variable optimizations, which are
4079 enabled if @option{-O1} is used. These optimizations are generally
4080 profitable but, for some specific cases of loops with numerous uses
4081 of the iteration variable that follow a common pattern, they may end
4082 up destroying the regularity that could be exploited at a lower level
4083 and thus producing inferior code.
4085 @item -fno-strict-aliasing
4086 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4087 Causes the compiler to avoid assumptions regarding non-aliasing
4088 of objects of different types. See
4089 @ref{Optimization and Strict Aliasing} for details.
4091 @item -fstack-check
4092 @cindex @option{-fstack-check} (@command{gcc})
4093 Activates stack checking.
4094 See @ref{Stack Overflow Checking} for details.
4096 @item -fstack-usage
4097 @cindex @option{-fstack-usage} (@command{gcc})
4098 Makes the compiler output stack usage information for the program, on a
4099 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4101 @item ^-g^/DEBUG^
4102 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4103 Generate debugging information. This information is stored in the object
4104 file and copied from there to the final executable file by the linker,
4105 where it can be read by the debugger. You must use the
4106 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4108 @item -gnat83
4109 @cindex @option{-gnat83} (@command{gcc})
4110 Enforce Ada 83 restrictions.
4112 @item -gnat95
4113 @cindex @option{-gnat95} (@command{gcc})
4114 Enforce Ada 95 restrictions.
4116 @item -gnat05
4117 @cindex @option{-gnat05} (@command{gcc})
4118 Allow full Ada 2005 features.
4120 @item -gnat2005
4121 @cindex @option{-gnat2005} (@command{gcc})
4122 Allow full Ada 2005 features (same as @option{-gnat05})
4124 @item -gnat12
4125 @cindex @option{-gnat12} (@command{gcc})
4127 @item -gnat2012
4128 @cindex @option{-gnat2012} (@command{gcc})
4129 Allow full Ada 2012 features (same as @option{-gnat12})
4131 @item -gnata
4132 @cindex @option{-gnata} (@command{gcc})
4133 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4134 activated. Note that these pragmas can also be controlled using the
4135 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4136 It also activates pragmas @code{Check}, @code{Precondition}, and
4137 @code{Postcondition}. Note that these pragmas can also be controlled
4138 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
4139 also activates all assertions defined in the RM as aspects: preconditions,
4140 postconditions, type invariants and (sub)type predicates. In all Ada modes,
4141 corresponding pragmas for type invariants and (sub)type predicates are
4142 also activated.
4144 @item -gnatA
4145 @cindex @option{-gnatA} (@command{gcc})
4146 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4147 it will be ignored.
4149 @item -gnatb
4150 @cindex @option{-gnatb} (@command{gcc})
4151 Generate brief messages to @file{stderr} even if verbose mode set.
4153 @item -gnatB
4154 @cindex @option{-gnatB} (@command{gcc})
4155 Assume no invalid (bad) values except for 'Valid attribute use
4156 (@pxref{Validity Checking}).
4158 @item -gnatc
4159 @cindex @option{-gnatc} (@command{gcc})
4160 Check syntax and semantics only (no code generation attempted).
4162 @item -gnatC
4163 @cindex @option{-gnatC} (@command{gcc})
4164 Generate CodePeer information (no code generation attempted).
4165 This switch will generate an intermediate representation suitable for
4166 use by CodePeer (@file{.scil} files). This switch is not compatible with
4167 code generation (it will, among other things, disable some switches such
4168 as -gnatn, and enable others such as -gnata).
4170 @item -gnatd
4171 @cindex @option{-gnatd} (@command{gcc})
4172 Specify debug options for the compiler. The string of characters after
4173 the @option{-gnatd} specify the specific debug options. The possible
4174 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4175 compiler source file @file{debug.adb} for details of the implemented
4176 debug options. Certain debug options are relevant to applications
4177 programmers, and these are documented at appropriate points in this
4178 users guide.
4180 @ifclear vms
4181 @item -gnatD
4182 @cindex @option{-gnatD[nn]} (@command{gcc})
4183 @end ifclear
4184 @ifset vms
4185 @item /XDEBUG /LXDEBUG=nnn
4186 @end ifset
4187 Create expanded source files for source level debugging. This switch
4188 also suppress generation of cross-reference information
4189 (see @option{-gnatx}).
4191 @item ^-gnateA^/ALIASING_CHECK^
4192 @cindex @option{-gnateA} (@command{gcc})
4193 Check that there is no aliasing between two parameters of the same subprogram.
4195 @item -gnatec=@var{path}
4196 @cindex @option{-gnatec} (@command{gcc})
4197 Specify a configuration pragma file
4198 @ifclear vms
4199 (the equal sign is optional)
4200 @end ifclear
4201 (@pxref{The Configuration Pragmas Files}).
4203 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
4204 @cindex @option{-gnated} (@command{gcc})
4205 Disable atomic synchronization
4207 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4208 @cindex @option{-gnateD} (@command{gcc})
4209 Defines a symbol, associated with @var{value}, for preprocessing.
4210 (@pxref{Integrated Preprocessing}).
4212 @item -gnateE
4213 @cindex @option{-gnateE} (@command{gcc})
4214 Generate extra information in exception messages. In particular, display
4215 extra column information and the value and range associated with index and
4216 range check failures, and extra column information for access checks.
4217 In cases where the compiler is able to determine at compile time that
4218 a check will fail, it gives a warning, and the extra information is not
4219 produced at run time.
4221 @item -gnatef
4222 @cindex @option{-gnatef} (@command{gcc})
4223 Display full source path name in brief error messages.
4225 @item -gnateF
4226 @cindex @option{-gnateF} (@command{gcc})
4227 Check for overflow on all floating-point operations, including those
4228 for unconstrained predefined types. See description of pragma
4229 @code{Check_Float_Overflow} in GNAT RM.
4231 @item -gnateG
4232 @cindex @option{-gnateG} (@command{gcc})
4233 Save result of preprocessing in a text file.
4235 @item -gnatei@var{nnn}
4236 @cindex @option{-gnatei} (@command{gcc})
4237 Set maximum number of instantiations during compilation of a single unit to
4238 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
4239 the rare case when a single unit legitimately exceeds this limit.
4241 @item -gnateI@var{nnn}
4242 @cindex @option{-gnateI} (@command{gcc})
4243 Indicates that the source is a multi-unit source and that the index of the
4244 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4245 to be a valid index in the multi-unit source.
4247 @item -gnatem=@var{path}
4248 @cindex @option{-gnatem} (@command{gcc})
4249 Specify a mapping file
4250 @ifclear vms
4251 (the equal sign is optional)
4252 @end ifclear
4253 (@pxref{Units to Sources Mapping Files}).
4255 @item -gnatep=@var{file}
4256 @cindex @option{-gnatep} (@command{gcc})
4257 Specify a preprocessing data file
4258 @ifclear vms
4259 (the equal sign is optional)
4260 @end ifclear
4261 (@pxref{Integrated Preprocessing}).
4263 @item -gnateP
4264 @cindex @option{-gnateP} (@command{gcc})
4265 Turn categorization dependency errors into warnings.
4266 Ada requires that units that WITH one another have compatible categories, for
4267 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4268 these errors become warnings (which can be ignored, or suppressed in the usual
4269 manner). This can be useful in some specialized circumstances such as the
4270 temporary use of special test software.
4272 @item -gnateS
4273 @cindex @option{-gnateS} (@command{gcc})
4274 Synonym of @option{-fdump-scos}, kept for backards compatibility.
4276 @item ^-gnatet^/TARGET_DEPENDENT_INFO^
4277 @cindex @option{-gnatet} (@command{gcc})
4278 Generate target dependent information.
4280 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
4281 @cindex @option{-gnateV} (@command{gcc})
4282 Check validity of subprogram parameters.
4284 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
4285 @cindex @option{-gnateY} (@command{gcc})
4286 Ignore all STYLE_CHECKS pragmas. Full legality checks
4287 are still carried out, but the pragmas have no effect
4288 on what style checks are active. This allows all style
4289 checking options to be controlled from the command line.
4291 @item -gnatE
4292 @cindex @option{-gnatE} (@command{gcc})
4293 Full dynamic elaboration checks.
4295 @item -gnatf
4296 @cindex @option{-gnatf} (@command{gcc})
4297 Full errors. Multiple errors per line, all undefined references, do not
4298 attempt to suppress cascaded errors.
4300 @item -gnatF
4301 @cindex @option{-gnatF} (@command{gcc})
4302 Externals names are folded to all uppercase.
4304 @item ^-gnatg^/GNAT_INTERNAL^
4305 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4306 Internal GNAT implementation mode. This should not be used for
4307 applications programs, it is intended only for use by the compiler
4308 and its run-time library. For documentation, see the GNAT sources.
4309 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4310 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4311 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4312 so that all standard warnings and all standard style options are turned on.
4313 All warnings and style messages are treated as errors.
4315 @ifclear vms
4316 @item -gnatG=nn
4317 @cindex @option{-gnatG[nn]} (@command{gcc})
4318 @end ifclear
4319 @ifset vms
4320 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4321 @end ifset
4322 List generated expanded code in source form.
4324 @item ^-gnath^/HELP^
4325 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4326 Output usage information. The output is written to @file{stdout}.
4328 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4329 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4330 Identifier character set
4331 @ifclear vms
4332 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4333 @end ifclear
4334 For details of the possible selections for @var{c},
4335 see @ref{Character Set Control}.
4337 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4338 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4339 Ignore representation clauses. When this switch is used,
4340 representation clauses are treated as comments. This is useful
4341 when initially porting code where you want to ignore rep clause
4342 problems, and also for compiling foreign code (particularly
4343 for use with ASIS). The representation clauses that are ignored
4344 are: enumeration_representation_clause, record_representation_clause,
4345 and attribute_definition_clause for the following attributes:
4346 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4347 Object_Size, Size, Small, Stream_Size, and Value_Size.
4348 Note that this option should be used only for compiling -- the
4349 code is likely to malfunction at run time.
4351 @item -gnatjnn
4352 @cindex @option{-gnatjnn} (@command{gcc})
4353 Reformat error messages to fit on nn character lines
4355 @item -gnatk=@var{n}
4356 @cindex @option{-gnatk} (@command{gcc})
4357 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4359 @item -gnatl
4360 @cindex @option{-gnatl} (@command{gcc})
4361 Output full source listing with embedded error messages.
4363 @item -gnatL
4364 @cindex @option{-gnatL} (@command{gcc})
4365 Used in conjunction with -gnatG or -gnatD to intersperse original
4366 source lines (as comment lines with line numbers) in the expanded
4367 source output.
4369 @item -gnatm=@var{n}
4370 @cindex @option{-gnatm} (@command{gcc})
4371 Limit number of detected error or warning messages to @var{n}
4372 where @var{n} is in the range 1..999999. The default setting if
4373 no switch is given is 9999. If the number of warnings reaches this
4374 limit, then a message is output and further warnings are suppressed,
4375 but the compilation is continued. If the number of error messages
4376 reaches this limit, then a message is output and the compilation
4377 is abandoned. The equal sign here is optional. A value of zero
4378 means that no limit applies.
4380 @item -gnatn[12]
4381 @cindex @option{-gnatn} (@command{gcc})
4382 Activate inlining for subprograms for which pragma @code{Inline} is
4383 specified. This inlining is performed by the GCC back-end. An optional
4384 digit sets the inlining level: 1 for moderate inlining across modules
4385 or 2 for full inlining across modules. If no inlining level is specified,
4386 the compiler will pick it based on the optimization level.
4388 @item -gnatN
4389 @cindex @option{-gnatN} (@command{gcc})
4390 Activate front end inlining for subprograms for which
4391 pragma @code{Inline} is specified. This inlining is performed
4392 by the front end and will be visible in the
4393 @option{-gnatG} output.
4395 When using a gcc-based back end (in practice this means using any version
4396 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4397 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4398 Historically front end inlining was more extensive than the gcc back end
4399 inlining, but that is no longer the case.
4401 @item -gnato??
4402 @cindex @option{-gnato??} (@command{gcc})
4403 Set default mode for handling generation of code to avoid intermediate
4404 arithmetic overflow. Here `@code{??}' is two digits, a
4405 single digit, or nothing. Each digit is one of the digits `@code{1}'
4406 through `@code{3}':
4408 @itemize @bullet
4409 @item   @code{1}:
4410 all intermediate overflows checked against base type (@code{STRICT})
4411 @item   @code{2}:
4412 minimize intermediate overflows (@code{MINIMIZED})
4413 @item   @code{3}:
4414 eliminate intermediate overflows (@code{ELIMINATED})
4415 @end itemize
4417 If only one digit appears then it applies to all
4418 cases; if two digits are given, then the first applies outside
4419 assertions, and the second within assertions.
4421 If no digits follow the @option{-gnato}, then it is equivalent to
4422 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4423 causing all intermediate overflows to be handled in strict mode.
4425 This switch also causes arithmetic overflow checking to be performed
4426 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4428 The default if no option @option{-gnato} is given is that overflow handling
4429 is in @code{STRICT} mode (computations done using the base type), and that
4430 overflow checking is suppressed.
4432 Note that division by zero is a separate check that is not
4433 controlled by this switch (division by zero checking is on by default).
4435 See also @ref{Specifying the Desired Mode}.
4437 @item -gnatp
4438 @cindex @option{-gnatp} (@command{gcc})
4439 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4440 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4442 @item -gnat-p
4443 @cindex @option{-gnat-p} (@command{gcc})
4444 Cancel effect of previous @option{-gnatp} switch.
4446 @item -gnatP
4447 @cindex @option{-gnatP} (@command{gcc})
4448 Enable polling. This is required on some systems (notably Windows NT) to
4449 obtain asynchronous abort and asynchronous transfer of control capability.
4450 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4451 details.
4453 @item -gnatq
4454 @cindex @option{-gnatq} (@command{gcc})
4455 Don't quit. Try semantics, even if parse errors.
4457 @item -gnatQ
4458 @cindex @option{-gnatQ} (@command{gcc})
4459 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4461 @item -gnatr
4462 @cindex @option{-gnatr} (@command{gcc})
4463 Treat pragma Restrictions as Restriction_Warnings.
4465 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4466 @cindex @option{-gnatR} (@command{gcc})
4467 Output representation information for declared types and objects.
4469 @item -gnats
4470 @cindex @option{-gnats} (@command{gcc})
4471 Syntax check only.
4473 @item -gnatS
4474 @cindex @option{-gnatS} (@command{gcc})
4475 Print package Standard.
4477 @item -gnatt
4478 @cindex @option{-gnatt} (@command{gcc})
4479 Generate tree output file.
4481 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4482 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4483 All compiler tables start at @var{nnn} times usual starting size.
4485 @item -gnatu
4486 @cindex @option{-gnatu} (@command{gcc})
4487 List units for this compilation.
4489 @item -gnatU
4490 @cindex @option{-gnatU} (@command{gcc})
4491 Tag all error messages with the unique string ``error:''
4493 @item -gnatv
4494 @cindex @option{-gnatv} (@command{gcc})
4495 Verbose mode. Full error output with source lines to @file{stdout}.
4497 @item -gnatV
4498 @cindex @option{-gnatV} (@command{gcc})
4499 Control level of validity checking (@pxref{Validity Checking}).
4501 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4502 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4503 Warning mode where
4504 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4505 the exact warnings that
4506 are enabled or disabled (@pxref{Warning Message Control}).
4508 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4509 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4510 Wide character encoding method
4511 @ifclear vms
4512 (@var{e}=n/h/u/s/e/8).
4513 @end ifclear
4514 @ifset vms
4515 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4516 @end ifset
4518 @item -gnatx
4519 @cindex @option{-gnatx} (@command{gcc})
4520 Suppress generation of cross-reference information.
4522 @item -gnatX
4523 @cindex @option{-gnatX} (@command{gcc})
4524 Enable GNAT implementation extensions and latest Ada version.
4526 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4527 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4528 Enable built-in style checks (@pxref{Style Checking}).
4530 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4531 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4532 Distribution stub generation and compilation
4533 @ifclear vms
4534 (@var{m}=r/c for receiver/caller stubs).
4535 @end ifclear
4536 @ifset vms
4537 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4538 to be generated and compiled).
4539 @end ifset
4541 @item ^-I^/SEARCH=^@var{dir}
4542 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4543 @cindex RTL
4544 Direct GNAT to search the @var{dir} directory for source files needed by
4545 the current compilation
4546 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4548 @item ^-I-^/NOCURRENT_DIRECTORY^
4549 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4550 @cindex RTL
4551 Except for the source file named in the command line, do not look for source
4552 files in the directory containing the source file named in the command line
4553 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4555 @ifclear vms
4556 @item -mbig-switch
4557 @cindex @option{-mbig-switch} (@command{gcc})
4558 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4559 This standard gcc switch causes the compiler to use larger offsets in its
4560 jump table representation for @code{case} statements.
4561 This may result in less efficient code, but is sometimes necessary
4562 (for example on HP-UX targets)
4563 @cindex HP-UX and @option{-mbig-switch} option
4564 in order to compile large and/or nested @code{case} statements.
4566 @item -o @var{file}
4567 @cindex @option{-o} (@command{gcc})
4568 This switch is used in @command{gcc} to redirect the generated object file
4569 and its associated ALI file. Beware of this switch with GNAT, because it may
4570 cause the object file and ALI file to have different names which in turn
4571 may confuse the binder and the linker.
4572 @end ifclear
4574 @item -nostdinc
4575 @cindex @option{-nostdinc} (@command{gcc})
4576 Inhibit the search of the default location for the GNAT Run Time
4577 Library (RTL) source files.
4579 @item -nostdlib
4580 @cindex @option{-nostdlib} (@command{gcc})
4581 Inhibit the search of the default location for the GNAT Run Time
4582 Library (RTL) ALI files.
4584 @ifclear vms
4585 @c @item -O@ovar{n}
4586 @c Expanding @ovar macro inline (explanation in macro def comments)
4587 @item -O@r{[}@var{n}@r{]}
4588 @cindex @option{-O} (@command{gcc})
4589 @var{n} controls the optimization level.
4591 @table @asis
4592 @item n = 0
4593 No optimization, the default setting if no @option{-O} appears
4595 @item n = 1
4596 Normal optimization, the default if you specify @option{-O} without
4597 an operand. A good compromise between code quality and compilation
4598 time.
4600 @item n = 2
4601 Extensive optimization, may improve execution time, possibly at the cost of
4602 substantially increased compilation time.
4604 @item n = 3
4605 Same as @option{-O2}, and also includes inline expansion for small subprograms
4606 in the same unit.
4608 @item n = s
4609 Optimize space usage
4610 @end table
4612 @noindent
4613 See also @ref{Optimization Levels}.
4614 @end ifclear
4616 @ifset vms
4617 @item  /NOOPTIMIZE
4618 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4619 Equivalent to @option{/OPTIMIZE=NONE}.
4620 This is the default behavior in the absence of an @option{/OPTIMIZE}
4621 qualifier.
4623 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4624 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4625 Selects the level of optimization for your program. The supported
4626 keywords are as follows:
4627 @table @code
4628 @item   ALL
4629 Perform most optimizations, including those that
4630 are expensive.
4631 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4632 without keyword options.
4634 @item   NONE
4635 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4637 @item SOME
4638 Perform some optimizations, but omit ones that are costly.
4640 @item   DEVELOPMENT
4641 Same as @code{SOME}.
4643 @item INLINING
4644 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4645 automatic inlining of small subprograms within a unit
4647 @item   UNROLL_LOOPS
4648 Try to unroll loops. This keyword may be specified together with
4649 any keyword above other than @code{NONE}. Loop unrolling
4650 usually, but not always, improves the performance of programs.
4652 @item SPACE
4653 Optimize space usage
4654 @end table
4656 @noindent
4657 See also @ref{Optimization Levels}.
4658 @end ifset
4660 @ifclear vms
4661 @item -pass-exit-codes
4662 @cindex @option{-pass-exit-codes} (@command{gcc})
4663 Catch exit codes from the compiler and use the most meaningful as
4664 exit status.
4665 @end ifclear
4667 @item --RTS=@var{rts-path}
4668 @cindex @option{--RTS} (@command{gcc})
4669 Specifies the default location of the runtime library. Same meaning as the
4670 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4672 @item ^-S^/ASM^
4673 @cindex @option{^-S^/ASM^} (@command{gcc})
4674 ^Used in place of @option{-c} to^Used to^
4675 cause the assembler source file to be
4676 generated, using @file{^.s^.S^} as the extension,
4677 instead of the object file.
4678 This may be useful if you need to examine the generated assembly code.
4680 @item ^-fverbose-asm^/VERBOSE_ASM^
4681 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4682 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4683 to cause the generated assembly code file to be annotated with variable
4684 names, making it significantly easier to follow.
4686 @item ^-v^/VERBOSE^
4687 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4688 Show commands generated by the @command{gcc} driver. Normally used only for
4689 debugging purposes or if you need to be sure what version of the
4690 compiler you are executing.
4692 @ifclear vms
4693 @item -V @var{ver}
4694 @cindex @option{-V} (@command{gcc})
4695 Execute @var{ver} version of the compiler. This is the @command{gcc}
4696 version, not the GNAT version.
4697 @end ifclear
4699 @item ^-w^/NO_BACK_END_WARNINGS^
4700 @cindex @option{-w} (@command{gcc})
4701 Turn off warnings generated by the back end of the compiler. Use of
4702 this switch also causes the default for front end warnings to be set
4703 to suppress (as though @option{-gnatws} had appeared at the start of
4704 the options).
4706 @end table
4708 @ifclear vms
4709 @c Combining qualifiers does not work on VMS
4710 You may combine a sequence of GNAT switches into a single switch. For
4711 example, the combined switch
4713 @cindex Combining GNAT switches
4714 @smallexample
4715 -gnatofi3
4716 @end smallexample
4718 @noindent
4719 is equivalent to specifying the following sequence of switches:
4721 @smallexample
4722 -gnato -gnatf -gnati3
4723 @end smallexample
4724 @end ifclear
4726 @noindent
4727 The following restrictions apply to the combination of switches
4728 in this manner:
4730 @itemize @bullet
4731 @item
4732 The switch @option{-gnatc} if combined with other switches must come
4733 first in the string.
4735 @item
4736 The switch @option{-gnats} if combined with other switches must come
4737 first in the string.
4739 @item
4740 The switches
4741 ^^@option{/DISTRIBUTION_STUBS=},^
4742 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4743 switches, and only one of them may appear in the command line.
4745 @item
4746 The switch @option{-gnat-p} may not be combined with any other switch.
4748 @ifclear vms
4749 @item
4750 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4751 switch), then all further characters in the switch are interpreted
4752 as style modifiers (see description of @option{-gnaty}).
4754 @item
4755 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4756 switch), then all further characters in the switch are interpreted
4757 as debug flags (see description of @option{-gnatd}).
4759 @item
4760 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4761 switch), then all further characters in the switch are interpreted
4762 as warning mode modifiers (see description of @option{-gnatw}).
4764 @item
4765 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4766 switch), then all further characters in the switch are interpreted
4767 as validity checking options (@pxref{Validity Checking}).
4769 @item
4770 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4771 a combined list of options.
4772 @end ifclear
4773 @end itemize
4775 @node Output and Error Message Control
4776 @subsection Output and Error Message Control
4777 @findex stderr
4779 @noindent
4780 The standard default format for error messages is called ``brief format''.
4781 Brief format messages are written to @file{stderr} (the standard error
4782 file) and have the following form:
4784 @smallexample
4785 e.adb:3:04: Incorrect spelling of keyword "function"
4786 e.adb:4:20: ";" should be "is"
4787 @end smallexample
4789 @noindent
4790 The first integer after the file name is the line number in the file,
4791 and the second integer is the column number within the line.
4792 @ifclear vms
4793 @code{GPS} can parse the error messages
4794 and point to the referenced character.
4795 @end ifclear
4796 The following switches provide control over the error message
4797 format:
4799 @table @option
4800 @c !sort!
4801 @item -gnatv
4802 @cindex @option{-gnatv} (@command{gcc})
4803 @findex stdout
4804 @ifclear vms
4805 The v stands for verbose.
4806 @end ifclear
4807 The effect of this setting is to write long-format error
4808 messages to @file{stdout} (the standard output file.
4809 The same program compiled with the
4810 @option{-gnatv} switch would generate:
4812 @smallexample
4813 @cartouche
4814 3. funcion X (Q : Integer)
4815    |
4816 >>> Incorrect spelling of keyword "function"
4817 4. return Integer;
4818                  |
4819 >>> ";" should be "is"
4820 @end cartouche
4821 @end smallexample
4823 @noindent
4824 The vertical bar indicates the location of the error, and the @samp{>>>}
4825 prefix can be used to search for error messages. When this switch is
4826 used the only source lines output are those with errors.
4828 @item -gnatl
4829 @cindex @option{-gnatl} (@command{gcc})
4830 @ifclear vms
4831 The @code{l} stands for list.
4832 @end ifclear
4833 This switch causes a full listing of
4834 the file to be generated. In the case where a body is
4835 compiled, the corresponding spec is also listed, along
4836 with any subunits. Typical output from compiling a package
4837 body @file{p.adb} might look like:
4839 @smallexample @c ada
4840 @cartouche
4841  Compiling: p.adb
4843      1. package body p is
4844      2.    procedure a;
4845      3.    procedure a is separate;
4846      4. begin
4847      5.    null
4848                |
4849         >>> missing ";"
4851      6. end;
4853 Compiling: p.ads
4855      1. package p is
4856      2.    pragma Elaborate_Body
4857                                 |
4858         >>> missing ";"
4860      3. end p;
4862 Compiling: p-a.adb
4864      1. separate p
4865                 |
4866         >>> missing "("
4868      2. procedure a is
4869      3. begin
4870      4.    null
4871                |
4872         >>> missing ";"
4874      5. end;
4875 @end cartouche
4876 @end smallexample
4878 @noindent
4879 @findex stderr
4880 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4881 standard output is redirected, a brief summary is written to
4882 @file{stderr} (standard error) giving the number of error messages and
4883 warning messages generated.
4885 @item ^-gnatl^/OUTPUT_FILE^=file
4886 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4887 This has the same effect as @option{-gnatl} except that the output is
4888 written to a file instead of to standard output. If the given name
4889 @file{fname} does not start with a period, then it is the full name
4890 of the file to be written. If @file{fname} is an extension, it is
4891 appended to the name of the file being compiled. For example, if
4892 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4893 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4895 @item -gnatU
4896 @cindex @option{-gnatU} (@command{gcc})
4897 This switch forces all error messages to be preceded by the unique
4898 string ``error:''. This means that error messages take a few more
4899 characters in space, but allows easy searching for and identification
4900 of error messages.
4902 @item -gnatb
4903 @cindex @option{-gnatb} (@command{gcc})
4904 @ifclear vms
4905 The @code{b} stands for brief.
4906 @end ifclear
4907 This switch causes GNAT to generate the
4908 brief format error messages to @file{stderr} (the standard error
4909 file) as well as the verbose
4910 format message or full listing (which as usual is written to
4911 @file{stdout} (the standard output file).
4913 @item -gnatm=@var{n}
4914 @cindex @option{-gnatm} (@command{gcc})
4915 @ifclear vms
4916 The @code{m} stands for maximum.
4917 @end ifclear
4918 @var{n} is a decimal integer in the
4919 range of 1 to 999999 and limits the number of error or warning
4920 messages to be generated. For example, using
4921 @option{-gnatm2} might yield
4923 @smallexample
4924 e.adb:3:04: Incorrect spelling of keyword "function"
4925 e.adb:5:35: missing ".."
4926 fatal error: maximum number of errors detected
4927 compilation abandoned
4928 @end smallexample
4930 @noindent
4931 The default setting if
4932 no switch is given is 9999. If the number of warnings reaches this
4933 limit, then a message is output and further warnings are suppressed,
4934 but the compilation is continued. If the number of error messages
4935 reaches this limit, then a message is output and the compilation
4936 is abandoned. A value of zero means that no limit applies.
4938 @noindent
4939 Note that the equal sign is optional, so the switches
4940 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4942 @item -gnatf
4943 @cindex @option{-gnatf} (@command{gcc})
4944 @cindex Error messages, suppressing
4945 @ifclear vms
4946 The @code{f} stands for full.
4947 @end ifclear
4948 Normally, the compiler suppresses error messages that are likely to be
4949 redundant. This switch causes all error
4950 messages to be generated. In particular, in the case of
4951 references to undefined variables. If a given variable is referenced
4952 several times, the normal format of messages is
4953 @smallexample
4954 e.adb:7:07: "V" is undefined (more references follow)
4955 @end smallexample
4957 @noindent
4958 where the parenthetical comment warns that there are additional
4959 references to the variable @code{V}. Compiling the same program with the
4960 @option{-gnatf} switch yields
4962 @smallexample
4963 e.adb:7:07: "V" is undefined
4964 e.adb:8:07: "V" is undefined
4965 e.adb:8:12: "V" is undefined
4966 e.adb:8:16: "V" is undefined
4967 e.adb:9:07: "V" is undefined
4968 e.adb:9:12: "V" is undefined
4969 @end smallexample
4971 @noindent
4972 The @option{-gnatf} switch also generates additional information for
4973 some error messages.  Some examples are:
4975 @itemize @bullet
4976 @item
4977 Details on possibly non-portable unchecked conversion
4978 @item
4979 List possible interpretations for ambiguous calls
4980 @item
4981 Additional details on incorrect parameters
4982 @end itemize
4984 @item -gnatjnn
4985 @cindex @option{-gnatjnn} (@command{gcc})
4986 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4987 with continuation lines are treated as though the continuation lines were
4988 separate messages (and so a warning with two continuation lines counts as
4989 three warnings, and is listed as three separate messages).
4991 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4992 messages are output in a different manner. A message and all its continuation
4993 lines are treated as a unit, and count as only one warning or message in the
4994 statistics totals. Furthermore, the message is reformatted so that no line
4995 is longer than nn characters.
4997 @item -gnatq
4998 @cindex @option{-gnatq} (@command{gcc})
4999 @ifclear vms
5000 The @code{q} stands for quit (really ``don't quit'').
5001 @end ifclear
5002 In normal operation mode, the compiler first parses the program and
5003 determines if there are any syntax errors. If there are, appropriate
5004 error messages are generated and compilation is immediately terminated.
5005 This switch tells
5006 GNAT to continue with semantic analysis even if syntax errors have been
5007 found. This may enable the detection of more errors in a single run. On
5008 the other hand, the semantic analyzer is more likely to encounter some
5009 internal fatal error when given a syntactically invalid tree.
5011 @item -gnatQ
5012 @cindex @option{-gnatQ} (@command{gcc})
5013 In normal operation mode, the @file{ALI} file is not generated if any
5014 illegalities are detected in the program. The use of @option{-gnatQ} forces
5015 generation of the @file{ALI} file. This file is marked as being in
5016 error, so it cannot be used for binding purposes, but it does contain
5017 reasonably complete cross-reference information, and thus may be useful
5018 for use by tools (e.g., semantic browsing tools or integrated development
5019 environments) that are driven from the @file{ALI} file. This switch
5020 implies @option{-gnatq}, since the semantic phase must be run to get a
5021 meaningful ALI file.
5023 In addition, if @option{-gnatt} is also specified, then the tree file is
5024 generated even if there are illegalities. It may be useful in this case
5025 to also specify @option{-gnatq} to ensure that full semantic processing
5026 occurs. The resulting tree file can be processed by ASIS, for the purpose
5027 of providing partial information about illegal units, but if the error
5028 causes the tree to be badly malformed, then ASIS may crash during the
5029 analysis.
5031 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
5032 being in error, @command{gnatmake} will attempt to recompile the source when it
5033 finds such an @file{ALI} file, including with switch @option{-gnatc}.
5035 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
5036 since ALI files are never generated if @option{-gnats} is set.
5038 @end table
5040 @node Warning Message Control
5041 @subsection Warning Message Control
5042 @cindex Warning messages
5043 @noindent
5044 In addition to error messages, which correspond to illegalities as defined
5045 in the Ada Reference Manual, the compiler detects two kinds of warning
5046 situations.
5048 First, the compiler considers some constructs suspicious and generates a
5049 warning message to alert you to a possible error. Second, if the
5050 compiler detects a situation that is sure to raise an exception at
5051 run time, it generates a warning message. The following shows an example
5052 of warning messages:
5053 @smallexample
5054 e.adb:4:24: warning: creation of object may raise Storage_Error
5055 e.adb:10:17: warning: static value out of range
5056 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
5057 @end smallexample
5059 @noindent
5060 GNAT considers a large number of situations as appropriate
5061 for the generation of warning messages. As always, warnings are not
5062 definite indications of errors. For example, if you do an out-of-range
5063 assignment with the deliberate intention of raising a
5064 @code{Constraint_Error} exception, then the warning that may be
5065 issued does not indicate an error. Some of the situations for which GNAT
5066 issues warnings (at least some of the time) are given in the following
5067 list. This list is not complete, and new warnings are often added to
5068 subsequent versions of GNAT. The list is intended to give a general idea
5069 of the kinds of warnings that are generated.
5071 @itemize @bullet
5072 @item
5073 Possible infinitely recursive calls
5075 @item
5076 Out-of-range values being assigned
5078 @item
5079 Possible order of elaboration problems
5081 @item
5082 Assertions (pragma Assert) that are sure to fail
5084 @item
5085 Unreachable code
5087 @item
5088 Address clauses with possibly unaligned values, or where an attempt is
5089 made to overlay a smaller variable with a larger one.
5091 @item
5092 Fixed-point type declarations with a null range
5094 @item
5095 Direct_IO or Sequential_IO instantiated with a type that has access values
5097 @item
5098 Variables that are never assigned a value
5100 @item
5101 Variables that are referenced before being initialized
5103 @item
5104 Task entries with no corresponding @code{accept} statement
5106 @item
5107 Duplicate accepts for the same task entry in a @code{select}
5109 @item
5110 Objects that take too much storage
5112 @item
5113 Unchecked conversion between types of differing sizes
5115 @item
5116 Missing @code{return} statement along some execution path in a function
5118 @item
5119 Incorrect (unrecognized) pragmas
5121 @item
5122 Incorrect external names
5124 @item
5125 Allocation from empty storage pool
5127 @item
5128 Potentially blocking operation in protected type
5130 @item
5131 Suspicious parenthesization of expressions
5133 @item
5134 Mismatching bounds in an aggregate
5136 @item
5137 Attempt to return local value by reference
5139 @item
5140 Premature instantiation of a generic body
5142 @item
5143 Attempt to pack aliased components
5145 @item
5146 Out of bounds array subscripts
5148 @item
5149 Wrong length on string assignment
5151 @item
5152 Violations of style rules if style checking is enabled
5154 @item
5155 Unused @code{with} clauses
5157 @item
5158 @code{Bit_Order} usage that does not have any effect
5160 @item
5161 @code{Standard.Duration} used to resolve universal fixed expression
5163 @item
5164 Dereference of possibly null value
5166 @item
5167 Declaration that is likely to cause storage error
5169 @item
5170 Internal GNAT unit @code{with}'ed by application unit
5172 @item
5173 Values known to be out of range at compile time
5175 @item
5176 Unreferenced labels and variables
5178 @item
5179 Address overlays that could clobber memory
5181 @item
5182 Unexpected initialization when address clause present
5184 @item
5185 Bad alignment for address clause
5187 @item
5188 Useless type conversions
5190 @item
5191 Redundant assignment statements and other redundant constructs
5193 @item
5194 Useless exception handlers
5196 @item
5197 Accidental hiding of name by child unit
5199 @item
5200 Access before elaboration detected at compile time
5202 @item
5203 A range in a @code{for} loop that is known to be null or might be null
5205 @end itemize
5207 @noindent
5208 The following section lists compiler switches that are available
5209 to control the handling of warning messages. It is also possible
5210 to exercise much finer control over what warnings are issued and
5211 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5212 gnat_rm, GNAT Reference manual}.
5214 @table @option
5215 @c !sort!
5216 @item -gnatwa
5217 @emph{Activate most optional warnings.}
5218 @cindex @option{-gnatwa} (@command{gcc})
5219 This switch activates most optional warning messages.  See the remaining list
5220 in this section for details on optional warning messages that can be
5221 individually controlled.  The warnings that are not turned on by this
5222 switch are
5223 @option{-gnatwd} (implicit dereferencing),
5224 @option{-gnatwh} (hiding),
5225 @ifclear vms
5226 @option{-gnatw.d} (tag warnings with -gnatw switch)
5227 @end ifclear
5228 @option{-gnatw.h} (holes (gaps) in record layouts)
5229 @option{-gnatw.i} (overlapping actuals),
5230 @option{-gnatw.k} (redefinition of names in standard),
5231 @option{-gnatwl} (elaboration warnings),
5232 @option{-gnatw.l} (inherited aspects),
5233 @option{-gnatw.o} (warn on values set by out parameters ignored),
5234 @option{-gnatwt} (tracking of deleted conditional code)
5235 and @option{-gnatw.u} (unordered enumeration),
5236 All other optional warnings are turned on.
5238 @item -gnatwA
5239 @emph{Suppress all optional errors.}
5240 @cindex @option{-gnatwA} (@command{gcc})
5241 This switch suppresses all optional warning messages, see remaining list
5242 in this section for details on optional warning messages that can be
5243 individually controlled. Note that unlike switch @option{-gnatws}, the
5244 use of switch @option{-gnatwA} does not suppress warnings that are
5245 normally given unconditionally and cannot be individually controlled
5246 (for example, the warning about a missing exit path in a function).
5247 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5248 the use of switch @option{-gnatwA} can be individually turned back
5249 on. For example the use of switch @option{-gnatwA} followed by
5250 switch @option{-gnatwd} will suppress all optional warnings except
5251 the warnings for implicit dereferencing.
5253 @item -gnatw.a
5254 @emph{Activate warnings on failing assertions.}
5255 @cindex @option{-gnatw.a} (@command{gcc})
5256 @cindex Assert failures
5257 This switch activates warnings for assertions where the compiler can tell at
5258 compile time that the assertion will fail. Note that this warning is given
5259 even if assertions are disabled. The default is that such warnings are
5260 generated.
5262 @item -gnatw.A
5263 @emph{Suppress warnings on failing assertions.}
5264 @cindex @option{-gnatw.A} (@command{gcc})
5265 @cindex Assert failures
5266 This switch suppresses warnings for assertions where the compiler can tell at
5267 compile time that the assertion will fail.
5269 @item -gnatwb
5270 @emph{Activate warnings on bad fixed values.}
5271 @cindex @option{-gnatwb} (@command{gcc})
5272 @cindex Bad fixed values
5273 @cindex Fixed-point Small value
5274 @cindex Small value
5275 This switch activates warnings for static fixed-point expressions whose
5276 value is not an exact multiple of Small. Such values are implementation
5277 dependent, since an implementation is free to choose either of the multiples
5278 that surround the value. GNAT always chooses the closer one, but this is not
5279 required behavior, and it is better to specify a value that is an exact
5280 multiple, ensuring predictable execution. The default is that such warnings
5281 are not generated.
5283 @item -gnatwB
5284 @emph{Suppress warnings on bad fixed values.}
5285 @cindex @option{-gnatwB} (@command{gcc})
5286 This switch suppresses warnings for static fixed-point expressions whose
5287 value is not an exact multiple of Small.
5289 @item -gnatw.b
5290 @emph{Activate warnings on biased representation.}
5291 @cindex @option{-gnatw.b} (@command{gcc})
5292 @cindex Biased representation
5293 This switch activates warnings when a size clause, value size clause, component
5294 clause, or component size clause forces the use of biased representation for an
5295 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5296 to represent 10/11). The default is that such warnings are generated.
5298 @item -gnatw.B
5299 @emph{Suppress warnings on biased representation.}
5300 @cindex @option{-gnatwB} (@command{gcc})
5301 This switch suppresses warnings for representation clauses that force the use
5302 of biased representation.
5304 @item -gnatwc
5305 @emph{Activate warnings on conditionals.}
5306 @cindex @option{-gnatwc} (@command{gcc})
5307 @cindex Conditionals, constant
5308 This switch activates warnings for conditional expressions used in
5309 tests that are known to be True or False at compile time. The default
5310 is that such warnings are not generated.
5311 Note that this warning does
5312 not get issued for the use of boolean variables or constants whose
5313 values are known at compile time, since this is a standard technique
5314 for conditional compilation in Ada, and this would generate too many
5315 false positive warnings.
5317 This warning option also activates a special test for comparisons using
5318 the operators ``>='' and`` <=''.
5319 If the compiler can tell that only the equality condition is possible,
5320 then it will warn that the ``>'' or ``<'' part of the test
5321 is useless and that the operator could be replaced by ``=''.
5322 An example would be comparing a @code{Natural} variable <= 0.
5324 This warning option also generates warnings if
5325 one or both tests is optimized away in a membership test for integer
5326 values if the result can be determined at compile time. Range tests on
5327 enumeration types are not included, since it is common for such tests
5328 to include an end point.
5330 This warning can also be turned on using @option{-gnatwa}.
5332 @item -gnatwC
5333 @emph{Suppress warnings on conditionals.}
5334 @cindex @option{-gnatwC} (@command{gcc})
5335 This switch suppresses warnings for conditional expressions used in
5336 tests that are known to be True or False at compile time.
5338 @item -gnatw.c
5339 @emph{Activate warnings on missing component clauses.}
5340 @cindex @option{-gnatw.c} (@command{gcc})
5341 @cindex Component clause, missing
5342 This switch activates warnings for record components where a record
5343 representation clause is present and has component clauses for the
5344 majority, but not all, of the components. A warning is given for each
5345 component for which no component clause is present.
5347 This warning can also be turned on using @option{-gnatwa}.
5349 @item -gnatw.C
5350 @emph{Suppress warnings on missing component clauses.}
5351 @cindex @option{-gnatwC} (@command{gcc})
5352 This switch suppresses warnings for record components that are
5353 missing a component clause in the situation described above.
5355 @item -gnatwd
5356 @emph{Activate warnings on implicit dereferencing.}
5357 @cindex @option{-gnatwd} (@command{gcc})
5358 If this switch is set, then the use of a prefix of an access type
5359 in an indexed component, slice, or selected component without an
5360 explicit @code{.all} will generate a warning. With this warning
5361 enabled, access checks occur only at points where an explicit
5362 @code{.all} appears in the source code (assuming no warnings are
5363 generated as a result of this switch). The default is that such
5364 warnings are not generated.
5365 Note that @option{-gnatwa} does not affect the setting of
5366 this warning option.
5368 @item -gnatwD
5369 @emph{Suppress warnings on implicit dereferencing.}
5370 @cindex @option{-gnatwD} (@command{gcc})
5371 @cindex Implicit dereferencing
5372 @cindex Dereferencing, implicit
5373 This switch suppresses warnings for implicit dereferences in
5374 indexed components, slices, and selected components.
5376 @ifclear vms
5377 @item -gnatw.d
5378 @emph{Activate tagging of warning messages.}
5379 @cindex @option{-gnatw.d} (@command{gcc})
5380 If this switch is set, then warning messages are tagged, either with
5381 the string ``@option{-gnatw?}'' showing which switch controls the warning,
5382 or with ``[enabled by default]'' if the warning is not under control of a
5383 specific @option{-gnatw?} switch. This mode is off by default, and is not
5384 affected by the use of @code{-gnatwa}.
5386 @item -gnatw.D
5387 @emph{Deactivate tagging of warning messages.}
5388 @cindex @option{-gnatw.d} (@command{gcc})
5389 If this switch is set, then warning messages return to the default
5390 mode in which warnings are not tagged as described above for
5391 @code{-gnatw.d}.
5392 @end ifclear
5394 @item -gnatwe
5395 @emph{Treat warnings and style checks as errors.}
5396 @cindex @option{-gnatwe} (@command{gcc})
5397 @cindex Warnings, treat as error
5398 This switch causes warning messages and style check messages to be
5399 treated as errors.
5400 The warning string still appears, but the warning messages are counted
5401 as errors, and prevent the generation of an object file. Note that this
5402 is the only -gnatw switch that affects the handling of style check messages.
5404 @item -gnatw.e
5405 @emph{Activate every optional warning}
5406 @cindex @option{-gnatw.e} (@command{gcc})
5407 @cindex Warnings, activate every optional warning
5408 This switch activates all optional warnings, including those which
5409 are not activated by @code{-gnatwa}. The use of this switch is not
5410 recommended for normal use. If you turn this switch on, it is almost
5411 certain that you will get large numbers of useless warnings. The
5412 warnings that are excluded from @code{-gnatwa} are typically highly
5413 specialized warnings that are suitable for use only in code that has
5414 been specifically designed according to specialized coding rules.
5416 @item -gnatwf
5417 @emph{Activate warnings on unreferenced formals.}
5418 @cindex @option{-gnatwf} (@command{gcc})
5419 @cindex Formals, unreferenced
5420 This switch causes a warning to be generated if a formal parameter
5421 is not referenced in the body of the subprogram. This warning can
5422 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5423 default is that these warnings are not generated.
5425 @item -gnatwF
5426 @emph{Suppress warnings on unreferenced formals.}
5427 @cindex @option{-gnatwF} (@command{gcc})
5428 This switch suppresses warnings for unreferenced formal
5429 parameters. Note that the
5430 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5431 effect of warning on unreferenced entities other than subprogram
5432 formals.
5434 @item -gnatwg
5435 @emph{Activate warnings on unrecognized pragmas.}
5436 @cindex @option{-gnatwg} (@command{gcc})
5437 @cindex Pragmas, unrecognized
5438 This switch causes a warning to be generated if an unrecognized
5439 pragma is encountered. Apart from issuing this warning, the
5440 pragma is ignored and has no effect. This warning can
5441 also be turned on using @option{-gnatwa}. The default
5442 is that such warnings are issued (satisfying the Ada Reference
5443 Manual requirement that such warnings appear).
5445 @item -gnatwG
5446 @emph{Suppress warnings on unrecognized pragmas.}
5447 @cindex @option{-gnatwG} (@command{gcc})
5448 This switch suppresses warnings for unrecognized pragmas.
5450 @item -gnatwh
5451 @emph{Activate warnings on hiding.}
5452 @cindex @option{-gnatwh} (@command{gcc})
5453 @cindex Hiding of Declarations
5454 This switch activates warnings on hiding declarations.
5455 A declaration is considered hiding
5456 if it is for a non-overloadable entity, and it declares an entity with the
5457 same name as some other entity that is directly or use-visible. The default
5458 is that such warnings are not generated.
5459 Note that @option{-gnatwa} does not affect the setting of this warning option.
5461 @item -gnatwH
5462 @emph{Suppress warnings on hiding.}
5463 @cindex @option{-gnatwH} (@command{gcc})
5464 This switch suppresses warnings on hiding declarations.
5466 @item -gnatw.h
5467 @emph{Activate warnings on holes/gaps in records.}
5468 @cindex @option{-gnatw.h} (@command{gcc})
5469 @cindex Record Representation (gaps)
5470 This switch activates warnings on component clauses in record
5471 representation clauses that leave holes (gaps) in the record layout.
5472 If this warning option is active, then record representation clauses
5473 should specify a contiguous layout, adding unused fill fields if needed.
5474 Note that @option{-gnatwa} does not affect the setting of this warning option.
5476 @item -gnatw.H
5477 @emph{Suppress warnings on holes/gaps in records.}
5478 @cindex @option{-gnatw.H} (@command{gcc})
5479 This switch suppresses warnings on component clauses in record
5480 representation clauses that leave holes (haps) in the record layout.
5482 @item -gnatwi
5483 @emph{Activate warnings on implementation units.}
5484 @cindex @option{-gnatwi} (@command{gcc})
5485 This switch activates warnings for a @code{with} of an internal GNAT
5486 implementation unit, defined as any unit from the @code{Ada},
5487 @code{Interfaces}, @code{GNAT},
5488 ^^@code{DEC},^ or @code{System}
5489 hierarchies that is not
5490 documented in either the Ada Reference Manual or the GNAT
5491 Programmer's Reference Manual. Such units are intended only
5492 for internal implementation purposes and should not be @code{with}'ed
5493 by user programs. The default is that such warnings are generated
5494 This warning can also be turned on using @option{-gnatwa}.
5496 @item -gnatwI
5497 @emph{Disable warnings on implementation units.}
5498 @cindex @option{-gnatwI} (@command{gcc})
5499 This switch disables warnings for a @code{with} of an internal GNAT
5500 implementation unit.
5502 @item -gnatw.i
5503 @emph{Activate warnings on overlapping actuals.}
5504 @cindex @option{-gnatw.i} (@command{gcc})
5505 This switch enables a warning on statically detectable overlapping actuals in
5506 a subprogram call, when one of the actuals is an in-out parameter, and the
5507 types of the actuals are not by-copy types. The warning is off by default,
5508 and is not included under -gnatwa.
5510 @item -gnatw.I
5511 @emph{Disable warnings on overlapping actuals.}
5512 @cindex @option{-gnatw.I} (@command{gcc})
5513 This switch disables warnings on overlapping actuals in a call..
5515 @item -gnatwj
5516 @emph{Activate warnings on obsolescent features (Annex J).}
5517 @cindex @option{-gnatwj} (@command{gcc})
5518 @cindex Features, obsolescent
5519 @cindex Obsolescent features
5520 If this warning option is activated, then warnings are generated for
5521 calls to subprograms marked with @code{pragma Obsolescent} and
5522 for use of features in Annex J of the Ada Reference Manual. In the
5523 case of Annex J, not all features are flagged. In particular use
5524 of the renamed packages (like @code{Text_IO}) and use of package
5525 @code{ASCII} are not flagged, since these are very common and
5526 would generate many annoying positive warnings. The default is that
5527 such warnings are not generated. This warning is also turned on by
5528 the use of @option{-gnatwa}.
5530 In addition to the above cases, warnings are also generated for
5531 GNAT features that have been provided in past versions but which
5532 have been superseded (typically by features in the new Ada standard).
5533 For example, @code{pragma Ravenscar} will be flagged since its
5534 function is replaced by @code{pragma Profile(Ravenscar)}, and
5535 @code{pragma Interface_Name} will be flagged since its function
5536 is replaced by @code{pragma Import}.
5538 Note that this warning option functions differently from the
5539 restriction @code{No_Obsolescent_Features} in two respects.
5540 First, the restriction applies only to annex J features.
5541 Second, the restriction does flag uses of package @code{ASCII}.
5543 @item -gnatwJ
5544 @emph{Suppress warnings on obsolescent features (Annex J).}
5545 @cindex @option{-gnatwJ} (@command{gcc})
5546 This switch disables warnings on use of obsolescent features.
5548 @item -gnatwk
5549 @emph{Activate warnings on variables that could be constants.}
5550 @cindex @option{-gnatwk} (@command{gcc})
5551 This switch activates warnings for variables that are initialized but
5552 never modified, and then could be declared constants. The default is that
5553 such warnings are not given.
5554 This warning can also be turned on using @option{-gnatwa}.
5556 @item -gnatwK
5557 @emph{Suppress warnings on variables that could be constants.}
5558 @cindex @option{-gnatwK} (@command{gcc})
5559 This switch disables warnings on variables that could be declared constants.
5561 @item -gnatw.k
5562 @emph{Activate warnings on redefinition of names in standard.}
5563 @cindex @option{-gnatw.k} (@command{gcc})
5564 This switch activates warnings for declarations that declare a name that
5565 is defined in package Standard. Such declarations can be confusing,
5566 especially since the names in package Standard continue to be directly
5567 visible, meaning that use visibiliy on such redeclared names does not
5568 work as expected. Names of discriminants and components in records are
5569 not included in this check.
5570 This warning is not part of the warnings activated by @option{-gnatwa}.
5571 It must be explicitly activated.
5573 @item -gnatw.K
5574 @emph{Suppress warnings on variables that could be constants.}
5575 @cindex @option{-gnatwK} (@command{gcc})
5576 This switch activates warnings for declarations that declare a name that
5577 is defined in package Standard.
5579 @item -gnatwl
5580 @emph{Activate warnings for elaboration pragmas.}
5581 @cindex @option{-gnatwl} (@command{gcc})
5582 @cindex Elaboration, warnings
5583 This switch activates warnings on missing
5584 @code{Elaborate_All} and @code{Elaborate} pragmas.
5585 See the section in this guide on elaboration checking for details on
5586 when such pragmas should be used. In dynamic elaboration mode, this switch
5587 generations warnings about the need to add elaboration pragmas. Note however,
5588 that if you blindly follow these warnings, and add @code{Elaborate_All}
5589 warnings wherever they are recommended, you basically end up with the
5590 equivalent of the static elaboration model, which may not be what you want for
5591 legacy code for which the static model does not work.
5593 For the static model, the messages generated are labeled "info:" (for
5594 information messages). They are not warnings to add elaboration pragmas,
5595 merely informational messages showing what implicit elaboration pragmas
5596 have been added, for use in analyzing elaboration circularity problems.
5598 Warnings are also generated if you
5599 are using the static mode of elaboration, and a @code{pragma Elaborate}
5600 is encountered. The default is that such warnings
5601 are not generated.
5602 This warning is not automatically turned on by the use of @option{-gnatwa}.
5604 @item -gnatwL
5605 @emph{Suppress warnings for elaboration pragmas.}
5606 @cindex @option{-gnatwL} (@command{gcc})
5607 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5608 See the section in this guide on elaboration checking for details on
5609 when such pragmas should be used.
5611 @item -gnatw.l
5612 @emph{List inherited aspects.}
5613 @cindex @option{-gnatw.l} (@command{gcc})
5614 This switch causes the compiler to list inherited invariants,
5615 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5616 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5617 These messages are not automatically turned on by the use of @option{-gnatwa}.
5619 @item -gnatw.L
5620 @emph{Suppress listing of inherited aspects.}
5621 @cindex @option{-gnatw.L} (@command{gcc})
5622 This switch suppresses listing of inherited aspects.
5624 @item -gnatwm
5625 @emph{Activate warnings on modified but unreferenced variables.}
5626 @cindex @option{-gnatwm} (@command{gcc})
5627 This switch activates warnings for variables that are assigned (using
5628 an initialization value or with one or more assignment statements) but
5629 whose value is never read. The warning is suppressed for volatile
5630 variables and also for variables that are renamings of other variables
5631 or for which an address clause is given.
5632 This warning can also be turned on using @option{-gnatwa}.
5633 The default is that these warnings are not given.
5635 @item -gnatwM
5636 @emph{Disable warnings on modified but unreferenced variables.}
5637 @cindex @option{-gnatwM} (@command{gcc})
5638 This switch disables warnings for variables that are assigned or
5639 initialized, but never read.
5641 @item -gnatw.m
5642 @emph{Activate warnings on suspicious modulus values.}
5643 @cindex @option{-gnatw.m} (@command{gcc})
5644 This switch activates warnings for modulus values that seem suspicious.
5645 The cases caught are where the size is the same as the modulus (e.g.
5646 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5647 with no size clause. The guess in both cases is that 2**x was intended
5648 rather than x. In addition expressions of the form 2*x for small x
5649 generate a warning (the almost certainly accurate guess being that
5650 2**x was intended). The default is that these warnings are given.
5652 @item -gnatw.M
5653 @emph{Disable warnings on suspicious modulus values.}
5654 @cindex @option{-gnatw.M} (@command{gcc})
5655 This switch disables warnings for suspicious modulus values.
5657 @item -gnatwn
5658 @emph{Set normal warnings mode.}
5659 @cindex @option{-gnatwn} (@command{gcc})
5660 This switch sets normal warning mode, in which enabled warnings are
5661 issued and treated as warnings rather than errors. This is the default
5662 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5663 an explicit @option{-gnatws} or
5664 @option{-gnatwe}. It also cancels the effect of the
5665 implicit @option{-gnatwe} that is activated by the
5666 use of @option{-gnatg}.
5668 @item -gnatwo
5669 @emph{Activate warnings on address clause overlays.}
5670 @cindex @option{-gnatwo} (@command{gcc})
5671 @cindex Address Clauses, warnings
5672 This switch activates warnings for possibly unintended initialization
5673 effects of defining address clauses that cause one variable to overlap
5674 another. The default is that such warnings are generated.
5675 This warning can also be turned on using @option{-gnatwa}.
5677 @item -gnatwO
5678 @emph{Suppress warnings on address clause overlays.}
5679 @cindex @option{-gnatwO} (@command{gcc})
5680 This switch suppresses warnings on possibly unintended initialization
5681 effects of defining address clauses that cause one variable to overlap
5682 another.
5684 @item -gnatw.o
5685 @emph{Activate warnings on modified but unreferenced out parameters.}
5686 @cindex @option{-gnatw.o} (@command{gcc})
5687 This switch activates warnings for variables that are modified by using
5688 them as actuals for a call to a procedure with an out mode formal, where
5689 the resulting assigned value is never read. It is applicable in the case
5690 where there is more than one out mode formal. If there is only one out
5691 mode formal, the warning is issued by default (controlled by -gnatwu).
5692 The warning is suppressed for volatile
5693 variables and also for variables that are renamings of other variables
5694 or for which an address clause is given.
5695 The default is that these warnings are not given. Note that this warning
5696 is not included in -gnatwa, it must be activated explicitly.
5698 @item -gnatw.O
5699 @emph{Disable warnings on modified but unreferenced out parameters.}
5700 @cindex @option{-gnatw.O} (@command{gcc})
5701 This switch suppresses warnings for variables that are modified by using
5702 them as actuals for a call to a procedure with an out mode formal, where
5703 the resulting assigned value is never read.
5705 @item -gnatwp
5706 @emph{Activate warnings on ineffective pragma Inlines.}
5707 @cindex @option{-gnatwp} (@command{gcc})
5708 @cindex Inlining, warnings
5709 This switch activates warnings for failure of front end inlining
5710 (activated by @option{-gnatN}) to inline a particular call. There are
5711 many reasons for not being able to inline a call, including most
5712 commonly that the call is too complex to inline. The default is
5713 that such warnings are not given.
5714 This warning can also be turned on using @option{-gnatwa}.
5715 Warnings on ineffective inlining by the gcc back-end can be activated
5716 separately, using the gcc switch -Winline.
5718 @item -gnatwP
5719 @emph{Suppress warnings on ineffective pragma Inlines.}
5720 @cindex @option{-gnatwP} (@command{gcc})
5721 This switch suppresses warnings on ineffective pragma Inlines. If the
5722 inlining mechanism cannot inline a call, it will simply ignore the
5723 request silently.
5725 @item -gnatw.p
5726 @emph{Activate warnings on parameter ordering.}
5727 @cindex @option{-gnatw.p} (@command{gcc})
5728 @cindex Parameter order, warnings
5729 This switch activates warnings for cases of suspicious parameter
5730 ordering when the list of arguments are all simple identifiers that
5731 match the names of the formals, but are in a different order. The
5732 warning is suppressed if any use of named parameter notation is used,
5733 so this is the appropriate way to suppress a false positive (and
5734 serves to emphasize that the "misordering" is deliberate). The
5735 default is
5736 that such warnings are not given.
5737 This warning can also be turned on using @option{-gnatwa}.
5739 @item -gnatw.P
5740 @emph{Suppress warnings on parameter ordering.}
5741 @cindex @option{-gnatw.P} (@command{gcc})
5742 This switch suppresses warnings on cases of suspicious parameter
5743 ordering.
5745 @item -gnatwq
5746 @emph{Activate warnings on questionable missing parentheses.}
5747 @cindex @option{-gnatwq} (@command{gcc})
5748 @cindex Parentheses, warnings
5749 This switch activates warnings for cases where parentheses are not used and
5750 the result is potential ambiguity from a readers point of view. For example
5751 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5752 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5753 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5754 follow the rule of always parenthesizing to make the association clear, and
5755 this warning switch warns if such parentheses are not present. The default
5756 is that these warnings are given.
5757 This warning can also be turned on using @option{-gnatwa}.
5759 @item -gnatwQ
5760 @emph{Suppress warnings on questionable missing parentheses.}
5761 @cindex @option{-gnatwQ} (@command{gcc})
5762 This switch suppresses warnings for cases where the association is not
5763 clear and the use of parentheses is preferred.
5765 @item -gnatwr
5766 @emph{Activate warnings on redundant constructs.}
5767 @cindex @option{-gnatwr} (@command{gcc})
5768 This switch activates warnings for redundant constructs. The following
5769 is the current list of constructs regarded as redundant:
5771 @itemize @bullet
5772 @item
5773 Assignment of an item to itself.
5774 @item
5775 Type conversion that converts an expression to its own type.
5776 @item
5777 Use of the attribute @code{Base} where @code{typ'Base} is the same
5778 as @code{typ}.
5779 @item
5780 Use of pragma @code{Pack} when all components are placed by a record
5781 representation clause.
5782 @item
5783 Exception handler containing only a reraise statement (raise with no
5784 operand) which has no effect.
5785 @item
5786 Use of the operator abs on an operand that is known at compile time
5787 to be non-negative
5788 @item
5789 Comparison of boolean expressions to an explicit True value.
5790 @end itemize
5792 This warning can also be turned on using @option{-gnatwa}.
5793 The default is that warnings for redundant constructs are not given.
5795 @item -gnatwR
5796 @emph{Suppress warnings on redundant constructs.}
5797 @cindex @option{-gnatwR} (@command{gcc})
5798 This switch suppresses warnings for redundant constructs.
5800 @item -gnatw.r
5801 @emph{Activate warnings for object renaming function.}
5802 @cindex @option{-gnatw.r} (@command{gcc})
5803 This switch activates warnings for an object renaming that renames a
5804 function call, which is equivalent to a constant declaration (as
5805 opposed to renaming the function itself).  The default is that these
5806 warnings are given.  This warning can also be turned on using
5807 @option{-gnatwa}.
5809 @item -gnatw.R
5810 @emph{Suppress warnings for object renaming function.}
5811 @cindex @option{-gnatwT} (@command{gcc})
5812 This switch suppresses warnings for object renaming function.
5814 @item -gnatws
5815 @emph{Suppress all warnings.}
5816 @cindex @option{-gnatws} (@command{gcc})
5817 This switch completely suppresses the
5818 output of all warning messages from the GNAT front end, including
5819 both warnings that can be controlled by switches described in this
5820 section, and those that are normally given unconditionally. The
5821 effect of this suppress action can only be cancelled by a subsequent
5822 use of the switch @option{-gnatwn}.
5824 Note that switch @option{-gnatws} does not suppress
5825 warnings from the @command{gcc} back end.
5826 To suppress these back end warnings as well, use the switch @option{-w}
5827 in addition to @option{-gnatws}. Also this switch has no effect on the
5828 handling of style check messages.
5830 @item -gnatw.s
5831 @emph{Activate warnings on overridden size clauses.}
5832 @cindex @option{-gnatw.s} (@command{gcc})
5833 @cindex Record Representation (component sizes)
5834 This switch activates warnings on component clauses in record
5835 representation clauses where the length given overrides that
5836 specified by an explicit size clause for the component type. A
5837 warning is similarly given in the array case if a specified
5838 component size overrides an explicit size clause for the array
5839 component type.
5840 Note that @option{-gnatwa} does not affect the setting of this warning option.
5842 @item -gnatw.S
5843 @emph{Suppress warnings on overridden size clauses.}
5844 @cindex @option{-gnatw.S} (@command{gcc})
5845 This switch suppresses warnings on component clauses in record
5846 representation clauses that override size clauses, and similar
5847 warnings when an array component size overrides a size clause.
5849 @item -gnatwt
5850 @emph{Activate warnings for tracking of deleted conditional code.}
5851 @cindex @option{-gnatwt} (@command{gcc})
5852 @cindex Deactivated code, warnings
5853 @cindex Deleted code, warnings
5854 This switch activates warnings for tracking of code in conditionals (IF and
5855 CASE statements) that is detected to be dead code which cannot be executed, and
5856 which is removed by the front end. This warning is off by default, and is not
5857 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5858 useful for detecting deactivated code in certified applications.
5860 @item -gnatwT
5861 @emph{Suppress warnings for tracking of deleted conditional code.}
5862 @cindex @option{-gnatwT} (@command{gcc})
5863 This switch suppresses warnings for tracking of deleted conditional code.
5865 @item -gnatw.t
5866 @emph{Activate warnings on suspicious contracts.}
5867 @cindex @option{-gnatw.t} (@command{gcc})
5868 This switch activates warnings on suspicious postconditions (whether a
5869 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5870 and suspicious contract cases (pragma @code{Contract_Case}). A
5871 function postcondition or contract case is suspicious when no postcondition
5872 or contract case for this function mentions the result of the function.
5873 A procedure postcondition or contract case is suspicious when it only
5874 refers to the pre-state of the procedure, because in that case it should
5875 rather be expressed as a precondition. The default is that such warnings
5876 are not generated. This warning can also be turned on using @option{-gnatwa}.
5878 @item -gnatw.T
5879 @emph{Suppress warnings on suspicious contracts.}
5880 @cindex @option{-gnatw.T} (@command{gcc})
5881 This switch suppresses warnings on suspicious postconditions.
5883 @item -gnatwu
5884 @emph{Activate warnings on unused entities.}
5885 @cindex @option{-gnatwu} (@command{gcc})
5886 This switch activates warnings to be generated for entities that
5887 are declared but not referenced, and for units that are @code{with}'ed
5888 and not
5889 referenced. In the case of packages, a warning is also generated if
5890 no entities in the package are referenced. This means that if a with'ed
5891 package is referenced but the only references are in @code{use}
5892 clauses or @code{renames}
5893 declarations, a warning is still generated. A warning is also generated
5894 for a generic package that is @code{with}'ed but never instantiated.
5895 In the case where a package or subprogram body is compiled, and there
5896 is a @code{with} on the corresponding spec
5897 that is only referenced in the body,
5898 a warning is also generated, noting that the
5899 @code{with} can be moved to the body. The default is that
5900 such warnings are not generated.
5901 This switch also activates warnings on unreferenced formals
5902 (it includes the effect of @option{-gnatwf}).
5903 This warning can also be turned on using @option{-gnatwa}.
5905 @item -gnatwU
5906 @emph{Suppress warnings on unused entities.}
5907 @cindex @option{-gnatwU} (@command{gcc})
5908 This switch suppresses warnings for unused entities and packages.
5909 It also turns off warnings on unreferenced formals (and thus includes
5910 the effect of @option{-gnatwF}).
5912 @item -gnatw.u
5913 @emph{Activate warnings on unordered enumeration types.}
5914 @cindex @option{-gnatw.u} (@command{gcc})
5915 This switch causes enumeration types to be considered as conceptually
5916 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5917 The effect is to generate warnings in clients that use explicit comparisons
5918 or subranges, since these constructs both treat objects of the type as
5919 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5920 which the type is declared, or its body or subunits.) Please refer to
5921 the description of pragma @code{Ordered} in the
5922 @cite{@value{EDITION} Reference Manual} for further details.
5923 The default is that such warnings are not generated.
5924 This warning is not automatically turned on by the use of @option{-gnatwa}.
5926 @item -gnatw.U
5927 @emph{Deactivate warnings on unordered enumeration types.}
5928 @cindex @option{-gnatw.U} (@command{gcc})
5929 This switch causes all enumeration types to be considered as ordered, so
5930 that no warnings are given for comparisons or subranges for any type.
5932 @item -gnatwv
5933 @emph{Activate warnings on unassigned variables.}
5934 @cindex @option{-gnatwv} (@command{gcc})
5935 @cindex Unassigned variable warnings
5936 This switch activates warnings for access to variables which
5937 may not be properly initialized. The default is that
5938 such warnings are generated.
5939 This warning can also be turned on using @option{-gnatwa}.
5941 @item -gnatwV
5942 @emph{Suppress warnings on unassigned variables.}
5943 @cindex @option{-gnatwV} (@command{gcc})
5944 This switch suppresses warnings for access to variables which
5945 may not be properly initialized.
5946 For variables of a composite type, the warning can also be suppressed in
5947 Ada 2005 by using a default initialization with a box. For example, if
5948 Table is an array of records whose components are only partially uninitialized,
5949 then the following code:
5951 @smallexample @c ada
5952    Tab : Table := (others => <>);
5953 @end smallexample
5955 will suppress warnings on subsequent statements that access components
5956 of variable Tab.
5958 @item -gnatw.v
5959 @emph{Activate info messages for non-default bit order.}
5960 @cindex @option{-gnatw.v} (@command{gcc})
5961 @cindex bit order warnings
5962 This switch activates messages (labeled "info", they are not warnings,
5963 just informational messages) about the effects of non-default bit-order
5964 on records to which a component clause is applied. The effect of specifying
5965 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5966 these messages, which are given by default, are useful in understanding the
5967 exact consequences of using this feature. These messages
5968 can also be turned on using @option{-gnatwa}
5970 @item -gnatw.V
5971 @emph{Suppress info messages for non-default bit order.}
5972 @cindex @option{-gnatw.V} (@command{gcc})
5973 This switch suppresses information messages for the effects of specifying
5974 non-default bit order on record components with component clauses.
5976 @item -gnatww
5977 @emph{Activate warnings on wrong low bound assumption.}
5978 @cindex @option{-gnatww} (@command{gcc})
5979 @cindex String indexing warnings
5980 This switch activates warnings for indexing an unconstrained string parameter
5981 with a literal or S'Length. This is a case where the code is assuming that the
5982 low bound is one, which is in general not true (for example when a slice is
5983 passed). The default is that such warnings are generated.
5984 This warning can also be turned on using @option{-gnatwa}.
5986 @item -gnatwW
5987 @emph{Suppress warnings on wrong low bound assumption.}
5988 @cindex @option{-gnatwW} (@command{gcc})
5989 This switch suppresses warnings for indexing an unconstrained string parameter
5990 with a literal or S'Length. Note that this warning can also be suppressed
5991 in a particular case by adding an
5992 assertion that the lower bound is 1,
5993 as shown in the following example.
5995 @smallexample @c ada
5996    procedure K (S : String) is
5997       pragma Assert (S'First = 1);
5998       @dots{}
5999 @end smallexample
6001 @item -gnatw.w
6002 @emph{Activate warnings on unnecessary Warnings Off pragmas}
6003 @cindex @option{-gnatw.w} (@command{gcc})
6004 @cindex Warnings Off control
6005 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
6006 where either the pragma is entirely useless (because it suppresses no
6007 warnings), or it could be replaced by @code{pragma Unreferenced} or
6008 @code{pragma Unmodified}. The default is that these warnings are not given.
6009 Note that this warning is not included in -gnatwa, it must be
6010 activated explicitly.
6012 @item -gnatw.W
6013 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
6014 @cindex @option{-gnatw.W} (@command{gcc})
6015 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
6017 @item -gnatwx
6018 @emph{Activate warnings on Export/Import pragmas.}
6019 @cindex @option{-gnatwx} (@command{gcc})
6020 @cindex Export/Import pragma warnings
6021 This switch activates warnings on Export/Import pragmas when
6022 the compiler detects a possible conflict between the Ada and
6023 foreign language calling sequences. For example, the use of
6024 default parameters in a convention C procedure is dubious
6025 because the C compiler cannot supply the proper default, so
6026 a warning is issued. The default is that such warnings are
6027 generated.
6028 This warning can also be turned on using @option{-gnatwa}.
6030 @item -gnatwX
6031 @emph{Suppress warnings on Export/Import pragmas.}
6032 @cindex @option{-gnatwX} (@command{gcc})
6033 This switch suppresses warnings on Export/Import pragmas.
6034 The sense of this is that you are telling the compiler that
6035 you know what you are doing in writing the pragma, and it
6036 should not complain at you.
6038 @item -gnatw.x
6039 @emph{Activate warnings for No_Exception_Propagation mode.}
6040 @cindex @option{-gnatwm} (@command{gcc})
6041 This switch activates warnings for exception usage when pragma Restrictions
6042 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
6043 explicit exception raises which are not covered by a local handler, and for
6044 exception handlers which do not cover a local raise. The default is that these
6045 warnings are not given.
6047 @item -gnatw.X
6048 @emph{Disable warnings for No_Exception_Propagation mode.}
6049 This switch disables warnings for exception usage when pragma Restrictions
6050 (No_Exception_Propagation) is in effect.
6052 @item -gnatwy
6053 @emph{Activate warnings for Ada compatibility issues.}
6054 @cindex @option{-gnatwy} (@command{gcc})
6055 @cindex Ada compatibility issues warnings
6056 For the most part, newer versions of Ada are upwards compatible
6057 with older versions. For example, Ada 2005 programs will almost
6058 always work when compiled as Ada 2012.
6059 However there are some exceptions (for example the fact that
6060 @code{some} is now a reserved word in Ada 2012). This
6061 switch activates several warnings to help in identifying
6062 and correcting such incompatibilities. The default is that
6063 these warnings are generated. Note that at one point Ada 2005
6064 was called Ada 0Y, hence the choice of character.
6065 This warning can also be turned on using @option{-gnatwa}.
6067 @item -gnatwY
6068 @emph{Disable warnings for Ada compatibility issues.}
6069 @cindex @option{-gnatwY} (@command{gcc})
6070 @cindex Ada compatibility issues warnings
6071 This switch suppresses the warnings intended to help in identifying
6072 incompatibilities between Ada language versions.
6074 @item -gnatwz
6075 @emph{Activate warnings on unchecked conversions.}
6076 @cindex @option{-gnatwz} (@command{gcc})
6077 @cindex Unchecked_Conversion warnings
6078 This switch activates warnings for unchecked conversions
6079 where the types are known at compile time to have different
6080 sizes. The default
6081 is that such warnings are generated. Warnings are also
6082 generated for subprogram pointers with different conventions,
6083 and, on VMS only, for data pointers with different conventions.
6084 This warning can also be turned on using @option{-gnatwa}.
6086 @item -gnatwZ
6087 @emph{Suppress warnings on unchecked conversions.}
6088 @cindex @option{-gnatwZ} (@command{gcc})
6089 This switch suppresses warnings for unchecked conversions
6090 where the types are known at compile time to have different
6091 sizes or conventions.
6093 @item ^-Wunused^WARNINGS=UNUSED^
6094 @cindex @option{-Wunused}
6095 The warnings controlled by the @option{-gnatw} switch are generated by
6096 the front end of the compiler. The @option{GCC} back end can provide
6097 additional warnings and they are controlled by the @option{-W} switch.
6098 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
6099 warnings for entities that are declared but not referenced.
6101 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
6102 @cindex @option{-Wuninitialized}
6103 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
6104 the back end warning for uninitialized variables. This switch must be
6105 used in conjunction with an optimization level greater than zero.
6107 @item -Wstack-usage=@var{len}
6108 @cindex @option{-Wstack-usage}
6109 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
6110 See @ref{Static Stack Usage Analysis} for details.
6112 @item ^-Wall^/ALL_BACK_END_WARNINGS^
6113 @cindex @option{-Wall}
6114 This switch enables most warnings from the @option{GCC} back end.
6115 The code generator detects a number of warning situations that are missed
6116 by the @option{GNAT} front end, and this switch can be used to activate them.
6117 The use of this switch also sets the default front end warning mode to
6118 @option{-gnatwa}, that is, most front end warnings activated as well.
6120 @item ^-w^/NO_BACK_END_WARNINGS^
6121 @cindex @option{-w}
6122 Conversely, this switch suppresses warnings from the @option{GCC} back end.
6123 The use of this switch also sets the default front end warning mode to
6124 @option{-gnatws}, that is, front end warnings suppressed as well.
6126 @end table
6128 @noindent
6129 @ifclear vms
6130 A string of warning parameters can be used in the same parameter. For example:
6132 @smallexample
6133 -gnatwaGe
6134 @end smallexample
6136 @noindent
6137 will turn on all optional warnings except for unrecognized pragma warnings,
6138 and also specify that warnings should be treated as errors.
6139 @end ifclear
6141 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
6143 @table @option
6144 @c !sort!
6145 @item -gnatw.a
6146 @item -gnatwB
6147 @item -gnatw.b
6148 @item -gnatwC
6149 @item -gnatw.C
6150 @item -gnatwD
6151 @item -gnatwF
6152 @item -gnatwg
6153 @item -gnatwH
6154 @item -gnatwi
6155 @item -gnatw.I
6156 @item -gnatwJ
6157 @item -gnatwK
6158 @item -gnatwL
6159 @item -gnatw.L
6160 @item -gnatwM
6161 @item -gnatw.m
6162 @item -gnatwn
6163 @item -gnatwo
6164 @item -gnatw.O
6165 @item -gnatwP
6166 @item -gnatw.P
6167 @item -gnatwq
6168 @item -gnatwR
6169 @item -gnatw.R
6170 @item -gnatw.S
6171 @item -gnatwT
6172 @item -gnatw.T
6173 @item -gnatwU
6174 @item -gnatwv
6175 @item -gnatww
6176 @item -gnatw.W
6177 @item -gnatwx
6178 @item -gnatw.X
6179 @item -gnatwy
6180 @item -gnatwz
6182 @end table
6184 @node Debugging and Assertion Control
6185 @subsection Debugging and Assertion Control
6187 @table @option
6188 @item -gnata
6189 @cindex @option{-gnata} (@command{gcc})
6190 @findex Assert
6191 @findex Debug
6192 @cindex Assertions
6194 @noindent
6195 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6196 are ignored. This switch, where @samp{a} stands for assert, causes
6197 @code{Assert} and @code{Debug} pragmas to be activated.
6199 The pragmas have the form:
6201 @smallexample
6202 @cartouche
6203    @b{pragma} Assert (@var{Boolean-expression} @r{[},
6204                       @var{static-string-expression}@r{]})
6205    @b{pragma} Debug (@var{procedure call})
6206 @end cartouche
6207 @end smallexample
6209 @noindent
6210 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6211 If the result is @code{True}, the pragma has no effect (other than
6212 possible side effects from evaluating the expression). If the result is
6213 @code{False}, the exception @code{Assert_Failure} declared in the package
6214 @code{System.Assertions} is
6215 raised (passing @var{static-string-expression}, if present, as the
6216 message associated with the exception). If no string expression is
6217 given the default is a string giving the file name and line number
6218 of the pragma.
6220 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6221 @code{pragma Debug} may appear within a declaration sequence, allowing
6222 debugging procedures to be called between declarations.
6224 @ifset vms
6225 @item /DEBUG@r{[}=debug-level@r{]}
6226 @itemx  /NODEBUG
6227 Specifies how much debugging information is to be included in
6228 the resulting object file where 'debug-level' is one of the following:
6229 @table @code
6230 @item   TRACEBACK
6231 Include both debugger symbol records and traceback
6232 the object file.
6233 This is the default setting.
6234 @item   ALL
6235 Include both debugger symbol records and traceback in
6236 object file.
6237 @item   NONE
6238 Excludes both debugger symbol records and traceback
6239 the object file. Same as /NODEBUG.
6240 @item   SYMBOLS
6241 Includes only debugger symbol records in the object
6242 file. Note that this doesn't include traceback information.
6243 @end table
6244 @end ifset
6245 @end table
6247 @node Validity Checking
6248 @subsection Validity Checking
6249 @findex Validity Checking
6251 @noindent
6252 The Ada Reference Manual defines the concept of invalid values (see
6253 RM 13.9.1). The primary source of invalid values is uninitialized
6254 variables. A scalar variable that is left uninitialized may contain
6255 an invalid value; the concept of invalid does not apply to access or
6256 composite types.
6258 It is an error to read an invalid value, but the RM does not require
6259 run-time checks to detect such errors, except for some minimal
6260 checking to prevent erroneous execution (i.e. unpredictable
6261 behavior). This corresponds to the @option{-gnatVd} switch below,
6262 which is the default. For example, by default, if the expression of a
6263 case statement is invalid, it will raise Constraint_Error rather than
6264 causing a wild jump, and if an array index on the left-hand side of an
6265 assignment is invalid, it will raise Constraint_Error rather than
6266 overwriting an arbitrary memory location.
6268 The @option{-gnatVa} may be used to enable additional validity checks,
6269 which are not required by the RM. These checks are often very
6270 expensive (which is why the RM does not require them). These checks
6271 are useful in tracking down uninitialized variables, but they are
6272 not usually recommended for production builds.
6274 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6275 control; you can enable whichever validity checks you desire. However,
6276 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6277 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6278 sufficient for non-debugging use.
6280 The @option{-gnatB} switch tells the compiler to assume that all
6281 values are valid (that is, within their declared subtype range)
6282 except in the context of a use of the Valid attribute. This means
6283 the compiler can generate more efficient code, since the range
6284 of values is better known at compile time. However, an uninitialized
6285 variable can cause wild jumps and memory corruption in this mode.
6287 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6288 checking mode as described below.
6289 @ifclear vms
6290 The @code{x} argument is a string of letters that
6291 indicate validity checks that are performed or not performed in addition
6292 to the default checks required by Ada as described above.
6293 @end ifclear
6294 @ifset vms
6295 The options allowed for this qualifier
6296 indicate validity checks that are performed or not performed in addition
6297 to the default checks required by Ada as described above.
6298 @end ifset
6300 @table @option
6301 @c !sort!
6302 @item -gnatVa
6303 @emph{All validity checks.}
6304 @cindex @option{-gnatVa} (@command{gcc})
6305 All validity checks are turned on.
6306 @ifclear vms
6307 That is, @option{-gnatVa} is
6308 equivalent to @option{gnatVcdfimorst}.
6309 @end ifclear
6311 @item -gnatVc
6312 @emph{Validity checks for copies.}
6313 @cindex @option{-gnatVc} (@command{gcc})
6314 The right hand side of assignments, and the initializing values of
6315 object declarations are validity checked.
6317 @item -gnatVd
6318 @emph{Default (RM) validity checks.}
6319 @cindex @option{-gnatVd} (@command{gcc})
6320 Some validity checks are done by default following normal Ada semantics
6321 (RM 13.9.1 (9-11)).
6322 A check is done in case statements that the expression is within the range
6323 of the subtype. If it is not, Constraint_Error is raised.
6324 For assignments to array components, a check is done that the expression used
6325 as index is within the range. If it is not, Constraint_Error is raised.
6326 Both these validity checks may be turned off using switch @option{-gnatVD}.
6327 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6328 switch @option{-gnatVd} will leave the checks turned on.
6329 Switch @option{-gnatVD} should be used only if you are sure that all such
6330 expressions have valid values. If you use this switch and invalid values
6331 are present, then the program is erroneous, and wild jumps or memory
6332 overwriting may occur.
6334 @item -gnatVe
6335 @emph{Validity checks for elementary components.}
6336 @cindex @option{-gnatVe} (@command{gcc})
6337 In the absence of this switch, assignments to record or array components are
6338 not validity checked, even if validity checks for assignments generally
6339 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6340 require valid data, but assignment of individual components does. So for
6341 example, there is a difference between copying the elements of an array with a
6342 slice assignment, compared to assigning element by element in a loop. This
6343 switch allows you to turn off validity checking for components, even when they
6344 are assigned component by component.
6346 @item -gnatVf
6347 @emph{Validity checks for floating-point values.}
6348 @cindex @option{-gnatVf} (@command{gcc})
6349 In the absence of this switch, validity checking occurs only for discrete
6350 values. If @option{-gnatVf} is specified, then validity checking also applies
6351 for floating-point values, and NaNs and infinities are considered invalid,
6352 as well as out of range values for constrained types. Note that this means
6353 that standard IEEE infinity mode is not allowed. The exact contexts
6354 in which floating-point values are checked depends on the setting of other
6355 options. For example,
6356 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6357 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6358 (the order does not matter) specifies that floating-point parameters of mode
6359 @code{in} should be validity checked.
6361 @item -gnatVi
6362 @emph{Validity checks for @code{in} mode parameters}
6363 @cindex @option{-gnatVi} (@command{gcc})
6364 Arguments for parameters of mode @code{in} are validity checked in function
6365 and procedure calls at the point of call.
6367 @item -gnatVm
6368 @emph{Validity checks for @code{in out} mode parameters.}
6369 @cindex @option{-gnatVm} (@command{gcc})
6370 Arguments for parameters of mode @code{in out} are validity checked in
6371 procedure calls at the point of call. The @code{'m'} here stands for
6372 modify, since this concerns parameters that can be modified by the call.
6373 Note that there is no specific option to test @code{out} parameters,
6374 but any reference within the subprogram will be tested in the usual
6375 manner, and if an invalid value is copied back, any reference to it
6376 will be subject to validity checking.
6378 @item -gnatVn
6379 @emph{No validity checks.}
6380 @cindex @option{-gnatVn} (@command{gcc})
6381 This switch turns off all validity checking, including the default checking
6382 for case statements and left hand side subscripts. Note that the use of
6383 the switch @option{-gnatp} suppresses all run-time checks, including
6384 validity checks, and thus implies @option{-gnatVn}. When this switch
6385 is used, it cancels any other @option{-gnatV} previously issued.
6387 @item -gnatVo
6388 @emph{Validity checks for operator and attribute operands.}
6389 @cindex @option{-gnatVo} (@command{gcc})
6390 Arguments for predefined operators and attributes are validity checked.
6391 This includes all operators in package @code{Standard},
6392 the shift operators defined as intrinsic in package @code{Interfaces}
6393 and operands for attributes such as @code{Pos}. Checks are also made
6394 on individual component values for composite comparisons, and on the
6395 expressions in type conversions and qualified expressions. Checks are
6396 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6398 @item -gnatVp
6399 @emph{Validity checks for parameters.}
6400 @cindex @option{-gnatVp} (@command{gcc})
6401 This controls the treatment of parameters within a subprogram (as opposed
6402 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6403 of parameters on a call. If either of these call options is used, then
6404 normally an assumption is made within a subprogram that the input arguments
6405 have been validity checking at the point of call, and do not need checking
6406 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6407 is not made, and parameters are not assumed to be valid, so their validity
6408 will be checked (or rechecked) within the subprogram.
6410 @item -gnatVr
6411 @emph{Validity checks for function returns.}
6412 @cindex @option{-gnatVr} (@command{gcc})
6413 The expression in @code{return} statements in functions is validity
6414 checked.
6416 @item -gnatVs
6417 @emph{Validity checks for subscripts.}
6418 @cindex @option{-gnatVs} (@command{gcc})
6419 All subscripts expressions are checked for validity, whether they appear
6420 on the right side or left side (in default mode only left side subscripts
6421 are validity checked).
6423 @item -gnatVt
6424 @emph{Validity checks for tests.}
6425 @cindex @option{-gnatVt} (@command{gcc})
6426 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6427 statements are checked, as well as guard expressions in entry calls.
6429 @end table
6431 @noindent
6432 The @option{-gnatV} switch may be followed by
6433 ^a string of letters^a list of options^
6434 to turn on a series of validity checking options.
6435 For example,
6436 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6437 specifies that in addition to the default validity checking, copies and
6438 function return expressions are to be validity checked.
6439 In order to make it easier
6440 to specify the desired combination of effects,
6441 @ifclear vms
6442 the upper case letters @code{CDFIMORST} may
6443 be used to turn off the corresponding lower case option.
6444 @end ifclear
6445 @ifset vms
6446 the prefix @code{NO} on an option turns off the corresponding validity
6447 checking:
6448 @itemize @bullet
6449 @item @code{NOCOPIES}
6450 @item @code{NODEFAULT}
6451 @item @code{NOFLOATS}
6452 @item @code{NOIN_PARAMS}
6453 @item @code{NOMOD_PARAMS}
6454 @item @code{NOOPERANDS}
6455 @item @code{NORETURNS}
6456 @item @code{NOSUBSCRIPTS}
6457 @item @code{NOTESTS}
6458 @end itemize
6459 @end ifset
6460 Thus
6461 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6462 turns on all validity checking options except for
6463 checking of @code{@b{in out}} procedure arguments.
6465 The specification of additional validity checking generates extra code (and
6466 in the case of @option{-gnatVa} the code expansion can be substantial).
6467 However, these additional checks can be very useful in detecting
6468 uninitialized variables, incorrect use of unchecked conversion, and other
6469 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6470 is useful in conjunction with the extra validity checking, since this
6471 ensures that wherever possible uninitialized variables have invalid values.
6473 See also the pragma @code{Validity_Checks} which allows modification of
6474 the validity checking mode at the program source level, and also allows for
6475 temporary disabling of validity checks.
6477 @node Style Checking
6478 @subsection Style Checking
6479 @findex Style checking
6481 @noindent
6482 The @option{-gnaty^x^(option,option,@dots{})^} switch
6483 @cindex @option{-gnaty} (@command{gcc})
6484 causes the compiler to
6485 enforce specified style rules. A limited set of style rules has been used
6486 in writing the GNAT sources themselves. This switch allows user programs
6487 to activate all or some of these checks. If the source program fails a
6488 specified style check, an appropriate message is given, preceded by
6489 the character sequence ``(style)''. This message does not prevent
6490 successful compilation (unless the @option{-gnatwe} switch is used).
6492 Note that this is by no means intended to be a general facility for
6493 checking arbitrary coding standards. It is simply an embedding of the
6494 style rules we have chosen for the GNAT sources. If you are starting
6495 a project which does not have established style standards, you may
6496 find it useful to adopt the entire set of GNAT coding standards, or
6497 some subset of them. If you already have an established set of coding
6498 standards, then it may be that selected style checking options do
6499 indeed correspond to choices you have made, but for general checking
6500 of an existing set of coding rules, you should look to the gnatcheck
6501 tool, which is designed for that purpose.
6503 @ifset vms
6504 @code{(option,option,@dots{})} is a sequence of keywords
6505 @end ifset
6506 @ifclear vms
6507 The string @var{x} is a sequence of letters or digits
6508 @end ifclear
6509 indicating the particular style
6510 checks to be performed. The following checks are defined:
6512 @table @option
6513 @c !sort!
6514 @item 0-9
6515 @emph{Specify indentation level.}
6516 If a digit from 1-9 appears
6517 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6518 then proper indentation is checked, with the digit indicating the
6519 indentation level required. A value of zero turns off this style check.
6520 The general style of required indentation is as specified by
6521 the examples in the Ada Reference Manual. Full line comments must be
6522 aligned with the @code{--} starting on a column that is a multiple of
6523 the alignment level, or they may be aligned the same way as the following
6524 non-blank line (this is useful when full line comments appear in the middle
6525 of a statement.
6527 @item ^a^ATTRIBUTE^
6528 @emph{Check attribute casing.}
6529 Attribute names, including the case of keywords such as @code{digits}
6530 used as attributes names, must be written in mixed case, that is, the
6531 initial letter and any letter following an underscore must be uppercase.
6532 All other letters must be lowercase.
6534 @item ^A^ARRAY_INDEXES^
6535 @emph{Use of array index numbers in array attributes.}
6536 When using the array attributes First, Last, Range,
6537 or Length, the index number must be omitted for one-dimensional arrays
6538 and is required for multi-dimensional arrays.
6540 @item ^b^BLANKS^
6541 @emph{Blanks not allowed at statement end.}
6542 Trailing blanks are not allowed at the end of statements. The purpose of this
6543 rule, together with h (no horizontal tabs), is to enforce a canonical format
6544 for the use of blanks to separate source tokens.
6546 @item ^B^BOOLEAN_OPERATORS^
6547 @emph{Check Boolean operators.}
6548 The use of AND/OR operators is not permitted except in the cases of modular
6549 operands, array operands, and simple stand-alone boolean variables or
6550 boolean constants. In all other cases @code{and then}/@code{or else} are
6551 required.
6553 @item ^c^COMMENTS^
6554 @emph{Check comments, double space.}
6555 Comments must meet the following set of rules:
6557 @itemize @bullet
6559 @item
6560 The ``@code{--}'' that starts the column must either start in column one,
6561 or else at least one blank must precede this sequence.
6563 @item
6564 Comments that follow other tokens on a line must have at least one blank
6565 following the ``@code{--}'' at the start of the comment.
6567 @item
6568 Full line comments must have at least two blanks following the
6569 ``@code{--}'' that starts the comment, with the following exceptions.
6571 @item
6572 A line consisting only of the ``@code{--}'' characters, possibly preceded
6573 by blanks is permitted.
6575 @item
6576 A comment starting with ``@code{--x}'' where @code{x} is a special character
6577 is permitted.
6578 This allows proper processing of the output generated by specialized tools
6579 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6580 annotation
6581 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6582 special character is defined as being in one of the ASCII ranges
6583 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6584 Note that this usage is not permitted
6585 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6587 @item
6588 A line consisting entirely of minus signs, possibly preceded by blanks, is
6589 permitted. This allows the construction of box comments where lines of minus
6590 signs are used to form the top and bottom of the box.
6592 @item
6593 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6594 least one blank follows the initial ``@code{--}''. Together with the preceding
6595 rule, this allows the construction of box comments, as shown in the following
6596 example:
6597 @smallexample
6598 ---------------------------
6599 -- This is a box comment --
6600 -- with two text lines.  --
6601 ---------------------------
6602 @end smallexample
6603 @end itemize
6605 @item ^C^COMMENTS1^
6606 @emph{Check comments, single space.}
6607 This is identical to @code{^c^COMMENTS^} except that only one space
6608 is required following the @code{--} of a comment instead of two.
6610 @item ^d^DOS_LINE_ENDINGS^
6611 @emph{Check no DOS line terminators present.}
6612 All lines must be terminated by a single ASCII.LF
6613 character (in particular the DOS line terminator sequence CR/LF is not
6614 allowed).
6616 @item ^e^END^
6617 @emph{Check end/exit labels.}
6618 Optional labels on @code{end} statements ending subprograms and on
6619 @code{exit} statements exiting named loops, are required to be present.
6621 @item ^f^VTABS^
6622 @emph{No form feeds or vertical tabs.}
6623 Neither form feeds nor vertical tab characters are permitted
6624 in the source text.
6626 @item ^g^GNAT^
6627 @emph{GNAT style mode.}
6628 The set of style check switches is set to match that used by the GNAT sources.
6629 This may be useful when developing code that is eventually intended to be
6630 incorporated into GNAT. For further details, see GNAT sources.
6632 @item ^h^HTABS^
6633 @emph{No horizontal tabs.}
6634 Horizontal tab characters are not permitted in the source text.
6635 Together with the b (no blanks at end of line) check, this
6636 enforces a canonical form for the use of blanks to separate
6637 source tokens.
6639 @item ^i^IF_THEN^
6640 @emph{Check if-then layout.}
6641 The keyword @code{then} must appear either on the same
6642 line as corresponding @code{if}, or on a line on its own, lined
6643 up under the @code{if} with at least one non-blank line in between
6644 containing all or part of the condition to be tested.
6646 @item ^I^IN_MODE^
6647 @emph{check mode IN keywords.}
6648 Mode @code{in} (the default mode) is not
6649 allowed to be given explicitly. @code{in out} is fine,
6650 but not @code{in} on its own.
6652 @item ^k^KEYWORD^
6653 @emph{Check keyword casing.}
6654 All keywords must be in lower case (with the exception of keywords
6655 such as @code{digits} used as attribute names to which this check
6656 does not apply).
6658 @item ^l^LAYOUT^
6659 @emph{Check layout.}
6660 Layout of statement and declaration constructs must follow the
6661 recommendations in the Ada Reference Manual, as indicated by the
6662 form of the syntax rules. For example an @code{else} keyword must
6663 be lined up with the corresponding @code{if} keyword.
6665 There are two respects in which the style rule enforced by this check
6666 option are more liberal than those in the Ada Reference Manual. First
6667 in the case of record declarations, it is permissible to put the
6668 @code{record} keyword on the same line as the @code{type} keyword, and
6669 then the @code{end} in @code{end record} must line up under @code{type}.
6670 This is also permitted when the type declaration is split on two lines.
6671 For example, any of the following three layouts is acceptable:
6673 @smallexample @c ada
6674 @cartouche
6675 type q is record
6676    a : integer;
6677    b : integer;
6678 end record;
6680 type q is
6681    record
6682       a : integer;
6683       b : integer;
6684    end record;
6686 type q is
6687    record
6688       a : integer;
6689       b : integer;
6690 end record;
6692 @end cartouche
6693 @end smallexample
6695 @noindent
6696 Second, in the case of a block statement, a permitted alternative
6697 is to put the block label on the same line as the @code{declare} or
6698 @code{begin} keyword, and then line the @code{end} keyword up under
6699 the block label. For example both the following are permitted:
6701 @smallexample @c ada
6702 @cartouche
6703 Block : declare
6704    A : Integer := 3;
6705 begin
6706    Proc (A, A);
6707 end Block;
6709 Block :
6710    declare
6711       A : Integer := 3;
6712    begin
6713       Proc (A, A);
6714    end Block;
6715 @end cartouche
6716 @end smallexample
6718 @noindent
6719 The same alternative format is allowed for loops. For example, both of
6720 the following are permitted:
6722 @smallexample @c ada
6723 @cartouche
6724 Clear : while J < 10 loop
6725    A (J) := 0;
6726 end loop Clear;
6728 Clear :
6729    while J < 10 loop
6730       A (J) := 0;
6731    end loop Clear;
6732 @end cartouche
6733 @end smallexample
6735 @item ^Lnnn^MAX_NESTING=nnn^
6736 @emph{Set maximum nesting level.}
6737 The maximum level of nesting of constructs (including subprograms, loops,
6738 blocks, packages, and conditionals) may not exceed the given value
6739 @option{nnn}. A value of zero disconnects this style check.
6741 @item ^m^LINE_LENGTH^
6742 @emph{Check maximum line length.}
6743 The length of source lines must not exceed 79 characters, including
6744 any trailing blanks. The value of 79 allows convenient display on an
6745 80 character wide device or window, allowing for possible special
6746 treatment of 80 character lines. Note that this count is of
6747 characters in the source text. This means that a tab character counts
6748 as one character in this count and a wide character sequence counts as
6749 a single character (however many bytes are needed in the encoding).
6751 @item ^Mnnn^MAX_LENGTH=nnn^
6752 @emph{Set maximum line length.}
6753 The length of lines must not exceed the
6754 given value @option{nnn}. The maximum value that can be specified is 32767.
6755 If neither style option for setting the line length is used, then the
6756 default is 255. This also controls the maximum length of lexical elements,
6757 where the only restriction is that they must fit on a single line.
6759 @item ^n^STANDARD_CASING^
6760 @emph{Check casing of entities in Standard.}
6761 Any identifier from Standard must be cased
6762 to match the presentation in the Ada Reference Manual (for example,
6763 @code{Integer} and @code{ASCII.NUL}).
6765 @item ^N^NONE^
6766 @emph{Turn off all style checks.}
6767 All style check options are turned off.
6769 @item ^o^ORDERED_SUBPROGRAMS^
6770 @emph{Check order of subprogram bodies.}
6771 All subprogram bodies in a given scope
6772 (e.g.@: a package body) must be in alphabetical order. The ordering
6773 rule uses normal Ada rules for comparing strings, ignoring casing
6774 of letters, except that if there is a trailing numeric suffix, then
6775 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6776 before Junk10).
6778 @item ^O^OVERRIDING_INDICATORS^
6779 @emph{Check that overriding subprograms are explicitly marked as such.}
6780 The declaration of a primitive operation of a type extension that overrides
6781 an inherited operation must carry an overriding indicator.
6783 @item ^p^PRAGMA^
6784 @emph{Check pragma casing.}
6785 Pragma names must be written in mixed case, that is, the
6786 initial letter and any letter following an underscore must be uppercase.
6787 All other letters must be lowercase.
6789 @item ^r^REFERENCES^
6790 @emph{Check references.}
6791 All identifier references must be cased in the same way as the
6792 corresponding declaration. No specific casing style is imposed on
6793 identifiers. The only requirement is for consistency of references
6794 with declarations.
6796 @item ^s^SPECS^
6797 @emph{Check separate specs.}
6798 Separate declarations (``specs'') are required for subprograms (a
6799 body is not allowed to serve as its own declaration). The only
6800 exception is that parameterless library level procedures are
6801 not required to have a separate declaration. This exception covers
6802 the most frequent form of main program procedures.
6804 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6805 @emph{Check no statements after @code{then}/@code{else}.}
6806 No statements are allowed
6807 on the same line as a @code{then} or @code{else} keyword following the
6808 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6809 affected, and a special exception allows a pragma to appear after @code{else}.
6811 @item ^t^TOKEN^
6812 @emph{Check token spacing.}
6813 The following token spacing rules are enforced:
6815 @itemize @bullet
6817 @item
6818 The keywords @code{abs} and @code{not} must be followed by a space.
6820 @item
6821 The token @code{=>} must be surrounded by spaces.
6823 @item
6824 The token @code{<>} must be preceded by a space or a left parenthesis.
6826 @item
6827 Binary operators other than @code{**} must be surrounded by spaces.
6828 There is no restriction on the layout of the @code{**} binary operator.
6830 @item
6831 Colon must be surrounded by spaces.
6833 @item
6834 Colon-equal (assignment, initialization) must be surrounded by spaces.
6836 @item
6837 Comma must be the first non-blank character on the line, or be
6838 immediately preceded by a non-blank character, and must be followed
6839 by a space.
6841 @item
6842 If the token preceding a left parenthesis ends with a letter or digit, then
6843 a space must separate the two tokens.
6845 @item
6846 if the token following a right parenthesis starts with a letter or digit, then
6847 a space must separate the two tokens.
6849 @item
6850 A right parenthesis must either be the first non-blank character on
6851 a line, or it must be preceded by a non-blank character.
6853 @item
6854 A semicolon must not be preceded by a space, and must not be followed by
6855 a non-blank character.
6857 @item
6858 A unary plus or minus may not be followed by a space.
6860 @item
6861 A vertical bar must be surrounded by spaces.
6862 @end itemize
6864 @item
6865 Exactly one blank (and no other white space) must appear between
6866 a @code{not} token and a following @code{in} token.
6868 @item ^u^UNNECESSARY_BLANK_LINES^
6869 @emph{Check unnecessary blank lines.}
6870 Unnecessary blank lines are not allowed. A blank line is considered
6871 unnecessary if it appears at the end of the file, or if more than
6872 one blank line occurs in sequence.
6874 @item ^x^XTRA_PARENS^
6875 @emph{Check extra parentheses.}
6876 Unnecessary extra level of parentheses (C-style) are not allowed
6877 around conditions in @code{if} statements, @code{while} statements and
6878 @code{exit} statements.
6880 @item ^y^ALL_BUILTIN^
6881 @emph{Set all standard style check options}
6882 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6883 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6884 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6885 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6887 @ifclear vms
6888 @item -
6889 @emph{Remove style check options}
6890 This causes any subsequent options in the string to act as canceling the
6891 corresponding style check option. To cancel maximum nesting level control,
6892 use @option{L} parameter witout any integer value after that, because any
6893 digit following @option{-} in the parameter string of the @option{-gnaty}
6894 option will be threated as canceling indentation check. The same is true
6895 for @option{M} parameter. @option{y} and @option{N} parameters are not
6896 allowed after @option{-}.
6898 @item +
6899 This causes any subsequent options in the string to enable the corresponding
6900 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6901 if any.
6902 @end ifclear
6904 @ifset vms
6905 @item NOxxx
6906 @emph{Removing style check options}
6907 If the name of a style check is preceded by @option{NO} then the corresponding
6908 style check is turned off. For example @option{NOCOMMENTS} turns off style
6909 checking for comments.
6910 @end ifset
6911 @end table
6913 @noindent
6914 In the above rules, appearing in column one is always permitted, that is,
6915 counts as meeting either a requirement for a required preceding space,
6916 or as meeting a requirement for no preceding space.
6918 Appearing at the end of a line is also always permitted, that is, counts
6919 as meeting either a requirement for a following space, or as meeting
6920 a requirement for no following space.
6922 @noindent
6923 If any of these style rules is violated, a message is generated giving
6924 details on the violation. The initial characters of such messages are
6925 always ``@code{(style)}''. Note that these messages are treated as warning
6926 messages, so they normally do not prevent the generation of an object
6927 file. The @option{-gnatwe} switch can be used to treat warning messages,
6928 including style messages, as fatal errors.
6930 The switch
6931 @ifclear vms
6932 @option{-gnaty} on its own (that is not
6933 followed by any letters or digits) is equivalent
6934 to the use of @option{-gnatyy} as described above, that is all
6935 built-in standard style check options are enabled.
6937 @end ifclear
6938 @ifset vms
6939 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6940 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6941 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6942 @end ifset
6944 The switch
6945 @ifclear vms
6946 @option{-gnatyN}
6947 @end ifclear
6948 @ifset vms
6949 /STYLE_CHECKS=NONE
6950 @end ifset
6951 clears any previously set style checks.
6953 @node Run-Time Checks
6954 @subsection Run-Time Checks
6955 @cindex Division by zero
6956 @cindex Access before elaboration
6957 @cindex Checks, division by zero
6958 @cindex Checks, access before elaboration
6959 @cindex Checks, stack overflow checking
6961 @noindent
6962 By default, the following checks are suppressed: integer overflow
6963 checks, stack overflow checks, and checks for access before
6964 elaboration on subprogram calls. All other checks, including range
6965 checks and array bounds checks, are turned on by default. The
6966 following @command{gcc} switches refine this default behavior.
6968 @table @option
6969 @c !sort!
6970 @item -gnatp
6971 @cindex @option{-gnatp} (@command{gcc})
6972 @cindex Suppressing checks
6973 @cindex Checks, suppressing
6974 @findex Suppress
6975 This switch causes the unit to be compiled
6976 as though @code{pragma Suppress (All_checks)}
6977 had been present in the source. Validity checks are also eliminated (in
6978 other words @option{-gnatp} also implies @option{-gnatVn}.
6979 Use this switch to improve the performance
6980 of the code at the expense of safety in the presence of invalid data or
6981 program bugs.
6983 Note that when checks are suppressed, the compiler is allowed, but not
6984 required, to omit the checking code. If the run-time cost of the
6985 checking code is zero or near-zero, the compiler will generate it even
6986 if checks are suppressed. In particular, if the compiler can prove
6987 that a certain check will necessarily fail, it will generate code to
6988 do an unconditional ``raise'', even if checks are suppressed. The
6989 compiler warns in this case. Another case in which checks may not be
6990 eliminated is when they are embedded in certain run time routines such
6991 as math library routines.
6993 Of course, run-time checks are omitted whenever the compiler can prove
6994 that they will not fail, whether or not checks are suppressed.
6996 Note that if you suppress a check that would have failed, program
6997 execution is erroneous, which means the behavior is totally
6998 unpredictable. The program might crash, or print wrong answers, or
6999 do anything else. It might even do exactly what you wanted it to do
7000 (and then it might start failing mysteriously next week or next
7001 year). The compiler will generate code based on the assumption that
7002 the condition being checked is true, which can result in disaster if
7003 that assumption is wrong.
7005 The @option{-gnatp} switch has no effect if a subsequent
7006 @option{-gnat-p} switch appears.
7008 @item -gnat-p
7009 @cindex @option{-gnat-p} (@command{gcc})
7010 @cindex Suppressing checks
7011 @cindex Checks, suppressing
7012 @findex Suppress
7013 This switch cancels the effect of a previous @option{gnatp} switch.
7015 @item -gnato??
7016 @cindex @option{-gnato??} (@command{gcc})
7017 @cindex Overflow checks
7018 @cindex Overflow mode
7019 @cindex Check, overflow
7020 This switch controls the mode used for computing intermediate
7021 arithmetic integer operations, and also enables overflow checking.
7022 For a full description of overflow mode and checking control, see
7023 the ``Overflow Check Handling in GNAT'' appendix in this
7024 User's Guide.
7026 Overflow checks are always enabled by this switch. The argument
7027 controls the mode, using the codes
7029 @itemize
7030 @item 1 = STRICT
7031 In STRICT mode, intermediate operations are always done using the
7032 base type, and overflow checking ensures that the result is within
7033 the base type range.
7035 @item 2 = MINIMIZED
7036 In MINIMIZED mode, overflows in intermediate operations are avoided
7037 where possible by using a larger integer type for the computation
7038 (typically @code{Long_Long_Integer}). Overflow checking ensures that
7039 the result fits in this larger integer type.
7041 @item 3 = ELIMINATED
7042 In ELIMINATED mode, overflows in intermediate operations are avoided
7043 by using multi-precision arithmetic. In this case, overflow checking
7044 has no effect on intermediate operations (since overflow is impossible).
7045 @end itemize
7047 If two digits are present after @option{-gnato} then the first digit
7048 sets the mode for expressions outside assertions, and the second digit
7049 sets the mode for expressions within assertions. Here assertions is used
7050 in the technical sense (which includes for example precondition and
7051 postcondition expressions).
7053 If one digit is present, the corresponding mode is applicable to both
7054 expressions within and outside assertion expressions.
7056 If no digits are present, the default is to enable overflow checks
7057 and set STRICT mode for both kinds of expressions. This is compatible
7058 with the use of @option{-gnato} in previous versions of GNAT.
7060 @findex Machine_Overflows
7061 Note that the @option{-gnato??} switch does not affect the code generated
7062 for any floating-point operations; it applies only to integer semantics.
7063 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
7064 attribute set to @code{False} and the normal mode of operation is to
7065 generate IEEE NaN and infinite values on overflow or invalid operations
7066 (such as dividing 0.0 by 0.0).
7068 The reason that we distinguish overflow checking from other kinds of
7069 range constraint checking is that a failure of an overflow check, unlike
7070 for example the failure of a range check, can result in an incorrect
7071 value, but cannot cause random memory destruction (like an out of range
7072 subscript), or a wild jump (from an out of range case value). Overflow
7073 checking is also quite expensive in time and space, since in general it
7074 requires the use of double length arithmetic.
7076 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
7077 so overflow checking is not performed in default mode. This means that out of
7078 the box, with the default settings, @value{EDITION} does not do all the checks
7079 expected from the language description in the Ada Reference Manual.
7080 If you want all constraint checks to be performed, as described in this Manual,
7081 then you must explicitly use the @option{-gnato??}
7082 switch either on the @command{gnatmake} or @command{gcc} command.
7084 @item -gnatE
7085 @cindex @option{-gnatE} (@command{gcc})
7086 @cindex Elaboration checks
7087 @cindex Check, elaboration
7088 Enables dynamic checks for access-before-elaboration
7089 on subprogram calls and generic instantiations.
7090 Note that @option{-gnatE} is not necessary for safety, because in the
7091 default mode, GNAT ensures statically that the checks would not fail.
7092 For full details of the effect and use of this switch,
7093 @xref{Compiling Using gcc}.
7095 @item -fstack-check
7096 @cindex @option{-fstack-check} (@command{gcc})
7097 @cindex Stack Overflow Checking
7098 @cindex Checks, stack overflow checking
7099 Activates stack overflow checking. For full details of the effect and use of
7100 this switch see @ref{Stack Overflow Checking}.
7101 @end table
7103 @findex Unsuppress
7104 @noindent
7105 The setting of these switches only controls the default setting of the
7106 checks. You may modify them using either @code{Suppress} (to remove
7107 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
7108 the program source.
7110 @node Using gcc for Syntax Checking
7111 @subsection Using @command{gcc} for Syntax Checking
7112 @table @option
7113 @item -gnats
7114 @cindex @option{-gnats} (@command{gcc})
7115 @ifclear vms
7117 @noindent
7118 The @code{s} stands for ``syntax''.
7119 @end ifclear
7121 Run GNAT in syntax checking only mode. For
7122 example, the command
7124 @smallexample
7125 $ gcc -c -gnats x.adb
7126 @end smallexample
7128 @noindent
7129 compiles file @file{x.adb} in syntax-check-only mode. You can check a
7130 series of files in a single command
7131 @ifclear vms
7132 , and can use wild cards to specify such a group of files.
7133 Note that you must specify the @option{-c} (compile
7134 only) flag in addition to the @option{-gnats} flag.
7135 @end ifclear
7137 You may use other switches in conjunction with @option{-gnats}. In
7138 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
7139 format of any generated error messages.
7141 When the source file is empty or contains only empty lines and/or comments,
7142 the output is a warning:
7144 @smallexample
7145 $ gcc -c -gnats -x ada toto.txt
7146 toto.txt:1:01: warning: empty file, contains no compilation units
7148 @end smallexample
7150 Otherwise, the output is simply the error messages, if any. No object file or
7151 ALI file is generated by a syntax-only compilation. Also, no units other
7152 than the one specified are accessed. For example, if a unit @code{X}
7153 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
7154 check only mode does not access the source file containing unit
7155 @code{Y}.
7157 @cindex Multiple units, syntax checking
7158 Normally, GNAT allows only a single unit in a source file. However, this
7159 restriction does not apply in syntax-check-only mode, and it is possible
7160 to check a file containing multiple compilation units concatenated
7161 together. This is primarily used by the @code{gnatchop} utility
7162 (@pxref{Renaming Files Using gnatchop}).
7163 @end table
7165 @node Using gcc for Semantic Checking
7166 @subsection Using @command{gcc} for Semantic Checking
7167 @table @option
7168 @item -gnatc
7169 @cindex @option{-gnatc} (@command{gcc})
7171 @ifclear vms
7172 @noindent
7173 The @code{c} stands for ``check''.
7174 @end ifclear
7175 Causes the compiler to operate in semantic check mode,
7176 with full checking for all illegalities specified in the
7177 Ada Reference Manual, but without generation of any object code
7178 (no object file is generated).
7180 Because dependent files must be accessed, you must follow the GNAT
7181 semantic restrictions on file structuring to operate in this mode:
7183 @itemize @bullet
7184 @item
7185 The needed source files must be accessible
7186 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7188 @item
7189 Each file must contain only one compilation unit.
7191 @item
7192 The file name and unit name must match (@pxref{File Naming Rules}).
7193 @end itemize
7195 The output consists of error messages as appropriate. No object file is
7196 generated. An @file{ALI} file is generated for use in the context of
7197 cross-reference tools, but this file is marked as not being suitable
7198 for binding (since no object file is generated).
7199 The checking corresponds exactly to the notion of
7200 legality in the Ada Reference Manual.
7202 Any unit can be compiled in semantics-checking-only mode, including
7203 units that would not normally be compiled (subunits,
7204 and specifications where a separate body is present).
7205 @end table
7207 @node Compiling Different Versions of Ada
7208 @subsection Compiling Different Versions of Ada
7210 @noindent
7211 The switches described in this section allow you to explicitly specify
7212 the version of the Ada language that your programs are written in.
7213 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
7214 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
7215 indicate Ada 83 compatibility mode.
7217 @table @option
7218 @cindex Compatibility with Ada 83
7220 @item -gnat83 (Ada 83 Compatibility Mode)
7221 @cindex @option{-gnat83} (@command{gcc})
7222 @cindex ACVC, Ada 83 tests
7223 @cindex Ada 83 mode
7225 @noindent
7226 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7227 specifies that the program is to be compiled in Ada 83 mode. With
7228 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7229 semantics where this can be done easily.
7230 It is not possible to guarantee this switch does a perfect
7231 job; some subtle tests, such as are
7232 found in earlier ACVC tests (and that have been removed from the ACATS suite
7233 for Ada 95), might not compile correctly.
7234 Nevertheless, this switch may be useful in some circumstances, for example
7235 where, due to contractual reasons, existing code needs to be maintained
7236 using only Ada 83 features.
7238 With few exceptions (most notably the need to use @code{<>} on
7239 @cindex Generic formal parameters
7240 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7241 reserved words, and the use of packages
7242 with optional bodies), it is not necessary to specify the
7243 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7244 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7245 a correct Ada 83 program is usually also a correct program
7246 in these later versions of the language standard.
7247 For further information, please refer to @ref{Compatibility and Porting Guide}.
7249 @item -gnat95 (Ada 95 mode)
7250 @cindex @option{-gnat95} (@command{gcc})
7251 @cindex Ada 95 mode
7253 @noindent
7254 This switch directs the compiler to implement the Ada 95 version of the
7255 language.
7256 Since Ada 95 is almost completely upwards
7257 compatible with Ada 83, Ada 83 programs may generally be compiled using
7258 this switch (see the description of the @option{-gnat83} switch for further
7259 information about Ada 83 mode).
7260 If an Ada 2005 program is compiled in Ada 95 mode,
7261 uses of the new Ada 2005 features will cause error
7262 messages or warnings.
7264 This switch also can be used to cancel the effect of a previous
7265 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7266 switch earlier in the command line.
7268 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7269 @cindex @option{-gnat05} (@command{gcc})
7270 @cindex @option{-gnat2005} (@command{gcc})
7271 @cindex Ada 2005 mode
7273 @noindent
7274 This switch directs the compiler to implement the Ada 2005 version of the
7275 language, as documented in the official Ada standards document.
7276 Since Ada 2005 is almost completely upwards
7277 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7278 may generally be compiled using this switch (see the description of the
7279 @option{-gnat83} and @option{-gnat95} switches for further
7280 information).
7282 @ifset PROEDITION
7283 Note that even though Ada 2005 is the current official version of the
7284 language, GNAT still compiles in Ada 95 mode by default, so if you are
7285 using Ada 2005 features in your program, you must use this switch (or
7286 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7287 @end ifset
7289 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7290 @cindex @option{-gnat12} (@command{gcc})
7291 @cindex @option{-gnat2012} (@command{gcc})
7292 @cindex Ada 2012 mode
7294 @noindent
7295 This switch directs the compiler to implement the Ada 2012 version of the
7296 language.
7297 Since Ada 2012 is almost completely upwards
7298 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7299 Ada 83 and Ada 95 programs
7300 may generally be compiled using this switch (see the description of the
7301 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7302 for further information).
7304 For information about the approved ``Ada Issues'' that have been incorporated
7305 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7306 Included with GNAT releases is a file @file{features-ada12} that describes
7307 the set of implemented Ada 2012 features.
7309 @item -gnatX (Enable GNAT Extensions)
7310 @cindex @option{-gnatX} (@command{gcc})
7311 @cindex Ada language extensions
7312 @cindex GNAT extensions
7314 @noindent
7315 This switch directs the compiler to implement the latest version of the
7316 language (currently Ada 2012) and also to enable certain GNAT implementation
7317 extensions that are not part of any Ada standard. For a full list of these
7318 extensions, see the GNAT reference manual.
7320 @end table
7322 @node Character Set Control
7323 @subsection Character Set Control
7324 @table @option
7325 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7326 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7328 @noindent
7329 Normally GNAT recognizes the Latin-1 character set in source program
7330 identifiers, as described in the Ada Reference Manual.
7331 This switch causes
7332 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7333 single character ^^or word^ indicating the character set, as follows:
7335 @table @code
7336 @item 1
7337 ISO 8859-1 (Latin-1) identifiers
7339 @item 2
7340 ISO 8859-2 (Latin-2) letters allowed in identifiers
7342 @item 3
7343 ISO 8859-3 (Latin-3) letters allowed in identifiers
7345 @item 4
7346 ISO 8859-4 (Latin-4) letters allowed in identifiers
7348 @item 5
7349 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7351 @item 9
7352 ISO 8859-15 (Latin-9) letters allowed in identifiers
7354 @item ^p^PC^
7355 IBM PC letters (code page 437) allowed in identifiers
7357 @item ^8^PC850^
7358 IBM PC letters (code page 850) allowed in identifiers
7360 @item ^f^FULL_UPPER^
7361 Full upper-half codes allowed in identifiers
7363 @item ^n^NO_UPPER^
7364 No upper-half codes allowed in identifiers
7366 @item ^w^WIDE^
7367 Wide-character codes (that is, codes greater than 255)
7368 allowed in identifiers
7369 @end table
7371 @xref{Foreign Language Representation}, for full details on the
7372 implementation of these character sets.
7374 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7375 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7376 Specify the method of encoding for wide characters.
7377 @var{e} is one of the following:
7379 @table @code
7381 @item ^h^HEX^
7382 Hex encoding (brackets coding also recognized)
7384 @item ^u^UPPER^
7385 Upper half encoding (brackets encoding also recognized)
7387 @item ^s^SHIFT_JIS^
7388 Shift/JIS encoding (brackets encoding also recognized)
7390 @item ^e^EUC^
7391 EUC encoding (brackets encoding also recognized)
7393 @item ^8^UTF8^
7394 UTF-8 encoding (brackets encoding also recognized)
7396 @item ^b^BRACKETS^
7397 Brackets encoding only (default value)
7398 @end table
7399 For full details on these encoding
7400 methods see @ref{Wide Character Encodings}.
7401 Note that brackets coding is always accepted, even if one of the other
7402 options is specified, so for example @option{-gnatW8} specifies that both
7403 brackets and UTF-8 encodings will be recognized. The units that are
7404 with'ed directly or indirectly will be scanned using the specified
7405 representation scheme, and so if one of the non-brackets scheme is
7406 used, it must be used consistently throughout the program. However,
7407 since brackets encoding is always recognized, it may be conveniently
7408 used in standard libraries, allowing these libraries to be used with
7409 any of the available coding schemes.
7411 Note that brackets encoding only applies to program text. Within comments,
7412 brackets are considered to be normal graphic characters, and bracket sequences
7413 are never recognized as wide characters.
7415 If no @option{-gnatW?} parameter is present, then the default
7416 representation is normally Brackets encoding only. However, if the
7417 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7418 byte order mark or BOM for UTF-8), then these three characters are
7419 skipped and the default representation for the file is set to UTF-8.
7421 Note that the wide character representation that is specified (explicitly
7422 or by default) for the main program also acts as the default encoding used
7423 for Wide_Text_IO files if not specifically overridden by a WCEM form
7424 parameter.
7426 @end table
7428 When no @option{-gnatW?} is specified, then characters (other than wide
7429 characters represented using brackets notation) are treated as 8-bit
7430 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7431 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7432 characters in the range 16#00#..16#1F# are not accepted in program text
7433 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7434 in program text, but allowed and ignored in comments. Note in particular
7435 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7436 as an end of line in this default mode. If your source program contains
7437 instances of the NEL character used as a line terminator,
7438 you must use UTF-8 encoding for the whole
7439 source program. In default mode, all lines must be ended by a standard
7440 end of line sequence (CR, CR/LF, or LF).
7442 Note that the convention of simply accepting all upper half characters in
7443 comments means that programs that use standard ASCII for program text, but
7444 UTF-8 encoding for comments are accepted in default mode, providing that the
7445 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7446 This is a common mode for many programs with foreign language comments.
7448 @node File Naming Control
7449 @subsection File Naming Control
7451 @table @option
7452 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7453 @cindex @option{-gnatk} (@command{gcc})
7454 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7455 1-999, indicates the maximum allowable length of a file name (not
7456 including the @file{.ads} or @file{.adb} extension). The default is not
7457 to enable file name krunching.
7459 For the source file naming rules, @xref{File Naming Rules}.
7460 @end table
7462 @node Subprogram Inlining Control
7463 @subsection Subprogram Inlining Control
7465 @table @option
7466 @c !sort!
7467 @item -gnatn[12]
7468 @cindex @option{-gnatn} (@command{gcc})
7469 @ifclear vms
7470 The @code{n} here is intended to suggest the first syllable of the
7471 word ``inline''.
7472 @end ifclear
7473 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7474 inlining to actually occur, optimization must be enabled and, in order
7475 to enable inlining of subprograms specified by pragma @code{Inline},
7476 you must also specify this switch.
7477 In the absence of this switch, GNAT does not attempt
7478 inlining and does not need to access the bodies of
7479 subprograms for which @code{pragma Inline} is specified if they are not
7480 in the current unit.
7482 You can optionally specify the inlining level: 1 for moderate inlining across
7483 modules, which is a good compromise between compilation times and performances
7484 at run time, or 2 for full inlining across modules, which may bring about
7485 longer compilation times. If no inlining level is specified, the compiler will
7486 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7487 @option{-Os} and 2 for @option{-O3}.
7489 If you specify this switch the compiler will access these bodies,
7490 creating an extra source dependency for the resulting object file, and
7491 where possible, the call will be inlined.
7492 For further details on when inlining is possible
7493 see @ref{Inlining of Subprograms}.
7495 @item -gnatN
7496 @cindex @option{-gnatN} (@command{gcc})
7497 This switch activates front-end inlining which also
7498 generates additional dependencies.
7500 When using a gcc-based back end (in practice this means using any version
7501 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7502 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7503 Historically front end inlining was more extensive than the gcc back end
7504 inlining, but that is no longer the case.
7505 @end table
7507 @node Auxiliary Output Control
7508 @subsection Auxiliary Output Control
7510 @table @option
7511 @item -gnatt
7512 @cindex @option{-gnatt} (@command{gcc})
7513 @cindex Writing internal trees
7514 @cindex Internal trees, writing to file
7515 Causes GNAT to write the internal tree for a unit to a file (with the
7516 extension @file{.adt}.
7517 This not normally required, but is used by separate analysis tools.
7518 Typically
7519 these tools do the necessary compilations automatically, so you should
7520 not have to specify this switch in normal operation.
7521 Note that the combination of switches @option{-gnatct}
7522 generates a tree in the form required by ASIS applications.
7524 @item -gnatu
7525 @cindex @option{-gnatu} (@command{gcc})
7526 Print a list of units required by this compilation on @file{stdout}.
7527 The listing includes all units on which the unit being compiled depends
7528 either directly or indirectly.
7530 @ifclear vms
7531 @item -pass-exit-codes
7532 @cindex @option{-pass-exit-codes} (@command{gcc})
7533 If this switch is not used, the exit code returned by @command{gcc} when
7534 compiling multiple files indicates whether all source files have
7535 been successfully used to generate object files or not.
7537 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7538 exit status and allows an integrated development environment to better
7539 react to a compilation failure. Those exit status are:
7541 @table @asis
7542 @item 5
7543 There was an error in at least one source file.
7544 @item 3
7545 At least one source file did not generate an object file.
7546 @item 2
7547 The compiler died unexpectedly (internal error for example).
7548 @item 0
7549 An object file has been generated for every source file.
7550 @end table
7551 @end ifclear
7552 @end table
7554 @node Debugging Control
7555 @subsection Debugging Control
7557 @table @option
7558 @c !sort!
7559 @cindex Debugging options
7560 @ifclear vms
7561 @item -gnatd@var{x}
7562 @cindex @option{-gnatd} (@command{gcc})
7563 Activate internal debugging switches. @var{x} is a letter or digit, or
7564 string of letters or digits, which specifies the type of debugging
7565 outputs desired. Normally these are used only for internal development
7566 or system debugging purposes. You can find full documentation for these
7567 switches in the body of the @code{Debug} unit in the compiler source
7568 file @file{debug.adb}.
7569 @end ifclear
7571 @item -gnatG[=nn]
7572 @cindex @option{-gnatG} (@command{gcc})
7573 This switch causes the compiler to generate auxiliary output containing
7574 a pseudo-source listing of the generated expanded code. Like most Ada
7575 compilers, GNAT works by first transforming the high level Ada code into
7576 lower level constructs. For example, tasking operations are transformed
7577 into calls to the tasking run-time routines. A unique capability of GNAT
7578 is to list this expanded code in a form very close to normal Ada source.
7579 This is very useful in understanding the implications of various Ada
7580 usage on the efficiency of the generated code. There are many cases in
7581 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7582 generate a lot of run-time code. By using @option{-gnatG} you can identify
7583 these cases, and consider whether it may be desirable to modify the coding
7584 approach to improve efficiency.
7586 The optional parameter @code{nn} if present after -gnatG specifies an
7587 alternative maximum line length that overrides the normal default of 72.
7588 This value is in the range 40-999999, values less than 40 being silently
7589 reset to 40. The equal sign is optional.
7591 The format of the output is very similar to standard Ada source, and is
7592 easily understood by an Ada programmer. The following special syntactic
7593 additions correspond to low level features used in the generated code that
7594 do not have any exact analogies in pure Ada source form. The following
7595 is a partial list of these special constructions. See the spec
7596 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7598 If the switch @option{-gnatL} is used in conjunction with
7599 @cindex @option{-gnatL} (@command{gcc})
7600 @option{-gnatG}, then the original source lines are interspersed
7601 in the expanded source (as comment lines with the original line number).
7603 @table @code
7604 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7605 Shows the storage pool being used for an allocator.
7607 @item at end @var{procedure-name};
7608 Shows the finalization (cleanup) procedure for a scope.
7610 @item (if @var{expr} then @var{expr} else @var{expr})
7611 Conditional expression equivalent to the @code{x?y:z} construction in C.
7613 @item @var{target}^^^(@var{source})
7614 A conversion with floating-point truncation instead of rounding.
7616 @item @var{target}?(@var{source})
7617 A conversion that bypasses normal Ada semantic checking. In particular
7618 enumeration types and fixed-point types are treated simply as integers.
7620 @item @var{target}?^^^(@var{source})
7621 Combines the above two cases.
7623 @item @var{x} #/ @var{y}
7624 @itemx @var{x} #mod @var{y}
7625 @itemx @var{x} #* @var{y}
7626 @itemx @var{x} #rem @var{y}
7627 A division or multiplication of fixed-point values which are treated as
7628 integers without any kind of scaling.
7630 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7631 Shows the storage pool associated with a @code{free} statement.
7633 @item [subtype or type declaration]
7634 Used to list an equivalent declaration for an internally generated
7635 type that is referenced elsewhere in the listing.
7637 @c @item freeze @var{type-name} @ovar{actions}
7638 @c Expanding @ovar macro inline (explanation in macro def comments)
7639 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7640 Shows the point at which @var{type-name} is frozen, with possible
7641 associated actions to be performed at the freeze point.
7643 @item reference @var{itype}
7644 Reference (and hence definition) to internal type @var{itype}.
7646 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7647 Intrinsic function call.
7649 @item @var{label-name} : label
7650 Declaration of label @var{labelname}.
7652 @item #$ @var{subprogram-name}
7653 An implicit call to a run-time support routine
7654 (to meet the requirement of H.3.1(9) in a
7655 convenient manner).
7657 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7658 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7659 @var{expr}, but handled more efficiently).
7661 @item [constraint_error]
7662 Raise the @code{Constraint_Error} exception.
7664 @item @var{expression}'reference
7665 A pointer to the result of evaluating @var{expression}.
7667 @item @var{target-type}!(@var{source-expression})
7668 An unchecked conversion of @var{source-expression} to @var{target-type}.
7670 @item [@var{numerator}/@var{denominator}]
7671 Used to represent internal real literals (that) have no exact
7672 representation in base 2-16 (for example, the result of compile time
7673 evaluation of the expression 1.0/27.0).
7674 @end table
7676 @item -gnatD[=nn]
7677 @cindex @option{-gnatD} (@command{gcc})
7678 When used in conjunction with @option{-gnatG}, this switch causes
7679 the expanded source, as described above for
7680 @option{-gnatG} to be written to files with names
7681 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7682 instead of to the standard output file. For
7683 example, if the source file name is @file{hello.adb}, then a file
7684 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7685 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7686 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7687 you to do source level debugging using the generated code which is
7688 sometimes useful for complex code, for example to find out exactly
7689 which part of a complex construction raised an exception. This switch
7690 also suppress generation of cross-reference information (see
7691 @option{-gnatx}) since otherwise the cross-reference information
7692 would refer to the @file{^.dg^.DG^} file, which would cause
7693 confusion since this is not the original source file.
7695 Note that @option{-gnatD} actually implies @option{-gnatG}
7696 automatically, so it is not necessary to give both options.
7697 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7699 If the switch @option{-gnatL} is used in conjunction with
7700 @cindex @option{-gnatL} (@command{gcc})
7701 @option{-gnatDG}, then the original source lines are interspersed
7702 in the expanded source (as comment lines with the original line number).
7704 The optional parameter @code{nn} if present after -gnatD specifies an
7705 alternative maximum line length that overrides the normal default of 72.
7706 This value is in the range 40-999999, values less than 40 being silently
7707 reset to 40. The equal sign is optional.
7709 @item -gnatr
7710 @cindex @option{-gnatr} (@command{gcc})
7711 @cindex pragma Restrictions
7712 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7713 so that violation of restrictions causes warnings rather than illegalities.
7714 This is useful during the development process when new restrictions are added
7715 or investigated. The switch also causes pragma Profile to be treated as
7716 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7717 restriction warnings rather than restrictions.
7719 @ifclear vms
7720 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7721 @cindex @option{-gnatR} (@command{gcc})
7722 This switch controls output from the compiler of a listing showing
7723 representation information for declared types and objects. For
7724 @option{-gnatR0}, no information is output (equivalent to omitting
7725 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7726 so @option{-gnatR} with no parameter has the same effect), size and alignment
7727 information is listed for declared array and record types. For
7728 @option{-gnatR2}, size and alignment information is listed for all
7729 declared types and objects. Finally @option{-gnatR3} includes symbolic
7730 expressions for values that are computed at run time for
7731 variant records. These symbolic expressions have a mostly obvious
7732 format with #n being used to represent the value of the n'th
7733 discriminant. See source files @file{repinfo.ads/adb} in the
7734 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7735 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7736 the output is to a file with the name @file{^file.rep^file_REP^} where
7737 file is the name of the corresponding source file.
7738 @end ifclear
7739 @ifset vms
7740 @item /REPRESENTATION_INFO
7741 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7742 This qualifier controls output from the compiler of a listing showing
7743 representation information for declared types and objects. For
7744 @option{/REPRESENTATION_INFO=NONE}, no information is output
7745 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7746 @option{/REPRESENTATION_INFO} without option is equivalent to
7747 @option{/REPRESENTATION_INFO=ARRAYS}.
7748 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7749 information is listed for declared array and record types. For
7750 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7751 is listed for all expression information for values that are computed
7752 at run time for variant records. These symbolic expressions have a mostly
7753 obvious format with #n being used to represent the value of the n'th
7754 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7755 @code{GNAT} sources for full details on the format of
7756 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7757 If _FILE is added at the end of an option
7758 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7759 then the output is to a file with the name @file{file_REP} where
7760 file is the name of the corresponding source file.
7761 @end ifset
7762 Note that it is possible for record components to have zero size. In
7763 this case, the component clause uses an obvious extension of permitted
7764 Ada syntax, for example @code{at 0 range 0 .. -1}.
7766 Representation information requires that code be generated (since it is the
7767 code generator that lays out complex data structures). If an attempt is made
7768 to output representation information when no code is generated, for example
7769 when a subunit is compiled on its own, then no information can be generated
7770 and the compiler outputs a message to this effect.
7772 @item -gnatS
7773 @cindex @option{-gnatS} (@command{gcc})
7774 The use of the switch @option{-gnatS} for an
7775 Ada compilation will cause the compiler to output a
7776 representation of package Standard in a form very
7777 close to standard Ada. It is not quite possible to
7778 do this entirely in standard Ada (since new
7779 numeric base types cannot be created in standard
7780 Ada), but the output is easily
7781 readable to any Ada programmer, and is useful to
7782 determine the characteristics of target dependent
7783 types in package Standard.
7785 @item -gnatx
7786 @cindex @option{-gnatx} (@command{gcc})
7787 Normally the compiler generates full cross-referencing information in
7788 the @file{ALI} file. This information is used by a number of tools,
7789 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7790 suppresses this information. This saves some space and may slightly
7791 speed up compilation, but means that these tools cannot be used.
7792 @end table
7794 @node Exception Handling Control
7795 @subsection Exception Handling Control
7797 @noindent
7798 GNAT uses two methods for handling exceptions at run-time. The
7799 @code{setjmp/longjmp} method saves the context when entering
7800 a frame with an exception handler. Then when an exception is
7801 raised, the context can be restored immediately, without the
7802 need for tracing stack frames. This method provides very fast
7803 exception propagation, but introduces significant overhead for
7804 the use of exception handlers, even if no exception is raised.
7806 The other approach is called ``zero cost'' exception handling.
7807 With this method, the compiler builds static tables to describe
7808 the exception ranges. No dynamic code is required when entering
7809 a frame containing an exception handler. When an exception is
7810 raised, the tables are used to control a back trace of the
7811 subprogram invocation stack to locate the required exception
7812 handler. This method has considerably poorer performance for
7813 the propagation of exceptions, but there is no overhead for
7814 exception handlers if no exception is raised. Note that in this
7815 mode and in the context of mixed Ada and C/C++ programming,
7816 to propagate an exception through a C/C++ code, the C/C++ code
7817 must be compiled with the @option{-funwind-tables} GCC's
7818 option.
7820 The following switches may be used to control which of the
7821 two exception handling methods is used.
7823 @table @option
7824 @c !sort!
7826 @item --RTS=sjlj
7827 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7828 This switch causes the setjmp/longjmp run-time (when available) to be used
7829 for exception handling. If the default
7830 mechanism for the target is zero cost exceptions, then
7831 this switch can be used to modify this default, and must be
7832 used for all units in the partition.
7833 This option is rarely used. One case in which it may be
7834 advantageous is if you have an application where exception
7835 raising is common and the overall performance of the
7836 application is improved by favoring exception propagation.
7838 @item --RTS=zcx
7839 @cindex @option{--RTS=zcx} (@command{gnatmake})
7840 @cindex Zero Cost Exceptions
7841 This switch causes the zero cost approach to be used
7842 for exception handling. If this is the default mechanism for the
7843 target (see below), then this switch is unneeded. If the default
7844 mechanism for the target is setjmp/longjmp exceptions, then
7845 this switch can be used to modify this default, and must be
7846 used for all units in the partition.
7847 This option can only be used if the zero cost approach
7848 is available for the target in use, otherwise it will generate an error.
7849 @end table
7851 @noindent
7852 The same option @option{--RTS} must be used both for @command{gcc}
7853 and @command{gnatbind}. Passing this option to @command{gnatmake}
7854 (@pxref{Switches for gnatmake}) will ensure the required consistency
7855 through the compilation and binding steps.
7857 @node Units to Sources Mapping Files
7858 @subsection Units to Sources Mapping Files
7860 @table @option
7862 @item -gnatem=@var{path}
7863 @cindex @option{-gnatem} (@command{gcc})
7864 A mapping file is a way to communicate to the compiler two mappings:
7865 from unit names to file names (without any directory information) and from
7866 file names to path names (with full directory information). These mappings
7867 are used by the compiler to short-circuit the path search.
7869 The use of mapping files is not required for correct operation of the
7870 compiler, but mapping files can improve efficiency, particularly when
7871 sources are read over a slow network connection. In normal operation,
7872 you need not be concerned with the format or use of mapping files,
7873 and the @option{-gnatem} switch is not a switch that you would use
7874 explicitly. It is intended primarily for use by automatic tools such as
7875 @command{gnatmake} running under the project file facility. The
7876 description here of the format of mapping files is provided
7877 for completeness and for possible use by other tools.
7879 A mapping file is a sequence of sets of three lines. In each set, the
7880 first line is the unit name, in lower case, with @code{%s} appended
7881 for specs and @code{%b} appended for bodies; the second line is the
7882 file name; and the third line is the path name.
7884 Example:
7885 @smallexample
7886    main%b
7887    main.2.ada
7888    /gnat/project1/sources/main.2.ada
7889 @end smallexample
7891 When the switch @option{-gnatem} is specified, the compiler will
7892 create in memory the two mappings from the specified file. If there is
7893 any problem (nonexistent file, truncated file or duplicate entries),
7894 no mapping will be created.
7896 Several @option{-gnatem} switches may be specified; however, only the
7897 last one on the command line will be taken into account.
7899 When using a project file, @command{gnatmake} creates a temporary
7900 mapping file and communicates it to the compiler using this switch.
7902 @end table
7904 @node Integrated Preprocessing
7905 @subsection Integrated Preprocessing
7907 @noindent
7908 GNAT sources may be preprocessed immediately before compilation.
7909 In this case, the actual
7910 text of the source is not the text of the source file, but is derived from it
7911 through a process called preprocessing. Integrated preprocessing is specified
7912 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7913 indicates, through a text file, the preprocessing data to be used.
7914 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7916 @noindent
7917 Note that when integrated preprocessing is used, the output from the
7918 preprocessor is not written to any external file. Instead it is passed
7919 internally to the compiler. If you need to preserve the result of
7920 preprocessing in a file, then you should use @command{gnatprep}
7921 to perform the desired preprocessing in stand-alone mode.
7923 @noindent
7924 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7925 used when Integrated Preprocessing is used. The reason is that preprocessing
7926 with another Preprocessing Data file without changing the sources will
7927 not trigger recompilation without this switch.
7929 @noindent
7930 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7931 always trigger recompilation for sources that are preprocessed,
7932 because @command{gnatmake} cannot compute the checksum of the source after
7933 preprocessing.
7935 @noindent
7936 The actual preprocessing function is described in details in section
7937 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7938 preprocessing is triggered and parameterized.
7940 @table @code
7942 @item -gnatep=@var{file}
7943 @cindex @option{-gnatep} (@command{gcc})
7944 This switch indicates to the compiler the file name (without directory
7945 information) of the preprocessor data file to use. The preprocessor data file
7946 should be found in the source directories. Note that when the compiler is
7947 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7948 file, if the object directory is not also a source directory, the builder needs
7949 to be called with @option{-x}.
7951 @noindent
7952 A preprocessing data file is a text file with significant lines indicating
7953 how should be preprocessed either a specific source or all sources not
7954 mentioned in other lines. A significant line is a nonempty, non-comment line.
7955 Comments are similar to Ada comments.
7957 @noindent
7958 Each significant line starts with either a literal string or the character '*'.
7959 A literal string is the file name (without directory information) of the source
7960 to preprocess. A character '*' indicates the preprocessing for all the sources
7961 that are not specified explicitly on other lines (order of the lines is not
7962 significant). It is an error to have two lines with the same file name or two
7963 lines starting with the character '*'.
7965 @noindent
7966 After the file name or the character '*', another optional literal string
7967 indicating the file name of the definition file to be used for preprocessing
7968 (@pxref{Form of Definitions File}). The definition files are found by the
7969 compiler in one of the source directories. In some cases, when compiling
7970 a source in a directory other than the current directory, if the definition
7971 file is in the current directory, it may be necessary to add the current
7972 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7973 the compiler would not find the definition file.
7975 @noindent
7976 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7977 be found. Those ^switches^switches^ are:
7979 @table @code
7981 @item -b
7982 Causes both preprocessor lines and the lines deleted by
7983 preprocessing to be replaced by blank lines, preserving the line number.
7984 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7985 it cancels the effect of @option{-c}.
7987 @item -c
7988 Causes both preprocessor lines and the lines deleted
7989 by preprocessing to be retained as comments marked
7990 with the special string ``@code{--! }''.
7992 @item -Dsymbol=value
7993 Define or redefine a symbol, associated with value. A symbol is an Ada
7994 identifier, or an Ada reserved word, with the exception of @code{if},
7995 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7996 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7997 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7998 same name defined in a definition file.
8000 @item -s
8001 Causes a sorted list of symbol names and values to be
8002 listed on the standard output file.
8004 @item -u
8005 Causes undefined symbols to be treated as having the value @code{FALSE}
8006 in the context
8007 of a preprocessor test. In the absence of this option, an undefined symbol in
8008 a @code{#if} or @code{#elsif} test will be treated as an error.
8010 @end table
8012 @noindent
8013 Examples of valid lines in a preprocessor data file:
8015 @smallexample
8016   "toto.adb"  "prep.def" -u
8017   --  preprocess "toto.adb", using definition file "prep.def",
8018   --  undefined symbol are False.
8020   * -c -DVERSION=V101
8021   --  preprocess all other sources without a definition file;
8022   --  suppressed lined are commented; symbol VERSION has the value V101.
8024   "titi.adb" "prep2.def" -s
8025   --  preprocess "titi.adb", using definition file "prep2.def";
8026   --  list all symbols with their values.
8027 @end smallexample
8029 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
8030 @cindex @option{-gnateD} (@command{gcc})
8031 Define or redefine a preprocessing symbol, associated with value. If no value
8032 is given on the command line, then the value of the symbol is @code{True}.
8033 A symbol is an identifier, following normal Ada (case-insensitive)
8034 rules for its syntax, and value is any sequence (including an empty sequence)
8035 of characters from the set (letters, digits, period, underline).
8036 Ada reserved words may be used as symbols, with the exceptions of @code{if},
8037 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
8039 @noindent
8040 A symbol declared with this ^switch^switch^ on the command line replaces a
8041 symbol with the same name either in a definition file or specified with a
8042 ^switch^switch^ -D in the preprocessor data file.
8044 @noindent
8045 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
8047 @item -gnateG
8048 When integrated preprocessing is performed and the preprocessor modifies
8049 the source text, write the result of this preprocessing into a file
8050 <source>^.prep^_prep^.
8052 @end table
8054 @node Code Generation Control
8055 @subsection Code Generation Control
8057 @noindent
8059 The GCC technology provides a wide range of target dependent
8060 @option{-m} switches for controlling
8061 details of code generation with respect to different versions of
8062 architectures. This includes variations in instruction sets (e.g.@:
8063 different members of the power pc family), and different requirements
8064 for optimal arrangement of instructions (e.g.@: different members of
8065 the x86 family). The list of available @option{-m} switches may be
8066 found in the GCC documentation.
8068 Use of these @option{-m} switches may in some cases result in improved
8069 code performance.
8071 The @value{EDITION} technology is tested and qualified without any
8072 @option{-m} switches,
8073 so generally the most reliable approach is to avoid the use of these
8074 switches. However, we generally expect most of these switches to work
8075 successfully with @value{EDITION}, and many customers have reported successful
8076 use of these options.
8078 Our general advice is to avoid the use of @option{-m} switches unless
8079 special needs lead to requirements in this area. In particular,
8080 there is no point in using @option{-m} switches to improve performance
8081 unless you actually see a performance improvement.
8083 @ifset vms
8084 @node Return Codes
8085 @subsection Return Codes
8086 @cindex Return Codes
8087 @cindex @option{/RETURN_CODES=VMS}
8089 @noindent
8090 On VMS, GNAT compiled programs return POSIX-style codes by default,
8091 e.g.@: @option{/RETURN_CODES=POSIX}.
8093 To enable VMS style return codes, use GNAT BIND and LINK with the option
8094 @option{/RETURN_CODES=VMS}. For example:
8096 @smallexample
8097 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
8098 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
8099 @end smallexample
8101 @noindent
8102 Programs built with /RETURN_CODES=VMS are suitable to be called in
8103 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
8104 are suitable for spawning with appropriate GNAT RTL routines.
8106 @end ifset
8108 @node Search Paths and the Run-Time Library (RTL)
8109 @section Search Paths and the Run-Time Library (RTL)
8111 @noindent
8112 With the GNAT source-based library system, the compiler must be able to
8113 find source files for units that are needed by the unit being compiled.
8114 Search paths are used to guide this process.
8116 The compiler compiles one source file whose name must be given
8117 explicitly on the command line. In other words, no searching is done
8118 for this file. To find all other source files that are needed (the most
8119 common being the specs of units), the compiler examines the following
8120 directories, in the following order:
8122 @enumerate
8123 @item
8124 The directory containing the source file of the main unit being compiled
8125 (the file name on the command line).
8127 @item
8128 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
8129 @command{gcc} command line, in the order given.
8131 @item
8132 @findex ADA_PRJ_INCLUDE_FILE
8133 Each of the directories listed in the text file whose name is given
8134 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
8136 @noindent
8137 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8138 driver when project files are used. It should not normally be set
8139 by other means.
8141 @item
8142 @findex ADA_INCLUDE_PATH
8143 Each of the directories listed in the value of the
8144 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
8145 @ifclear vms
8146 Construct this value
8147 exactly as the @env{PATH} environment variable: a list of directory
8148 names separated by colons (semicolons when working with the NT version).
8149 @end ifclear
8150 @ifset vms
8151 Normally, define this value as a logical name containing a comma separated
8152 list of directory names.
8154 This variable can also be defined by means of an environment string
8155 (an argument to the HP C exec* set of functions).
8157 Logical Name:
8158 @smallexample
8159 DEFINE ANOTHER_PATH FOO:[BAG]
8160 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8161 @end smallexample
8163 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8164 first, followed by the standard Ada
8165 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
8166 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8167 (Text_IO, Sequential_IO, etc)
8168 instead of the standard Ada packages. Thus, in order to get the standard Ada
8169 packages by default, ADA_INCLUDE_PATH must be redefined.
8170 @end ifset
8172 @item
8173 The content of the @file{ada_source_path} file which is part of the GNAT
8174 installation tree and is used to store standard libraries such as the
8175 GNAT Run Time Library (RTL) source files.
8176 @ifclear vms
8177 @ref{Installing a library}
8178 @end ifclear
8179 @end enumerate
8181 @noindent
8182 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
8183 inhibits the use of the directory
8184 containing the source file named in the command line. You can still
8185 have this directory on your search path, but in this case it must be
8186 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8188 Specifying the switch @option{-nostdinc}
8189 inhibits the search of the default location for the GNAT Run Time
8190 Library (RTL) source files.
8192 The compiler outputs its object files and ALI files in the current
8193 working directory.
8194 @ifclear vms
8195 Caution: The object file can be redirected with the @option{-o} switch;
8196 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8197 so the @file{ALI} file will not go to the right place. Therefore, you should
8198 avoid using the @option{-o} switch.
8199 @end ifclear
8201 @findex System.IO
8202 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8203 children make up the GNAT RTL, together with the simple @code{System.IO}
8204 package used in the @code{"Hello World"} example. The sources for these units
8205 are needed by the compiler and are kept together in one directory. Not
8206 all of the bodies are needed, but all of the sources are kept together
8207 anyway. In a normal installation, you need not specify these directory
8208 names when compiling or binding. Either the environment variables or
8209 the built-in defaults cause these files to be found.
8211 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8212 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8213 consisting of child units of @code{GNAT}. This is a collection of generally
8214 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8215 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8217 Besides simplifying access to the RTL, a major use of search paths is
8218 in compiling sources from multiple directories. This can make
8219 development environments much more flexible.
8221 @node Order of Compilation Issues
8222 @section Order of Compilation Issues
8224 @noindent
8225 If, in our earlier example, there was a spec for the @code{hello}
8226 procedure, it would be contained in the file @file{hello.ads}; yet this
8227 file would not have to be explicitly compiled. This is the result of the
8228 model we chose to implement library management. Some of the consequences
8229 of this model are as follows:
8231 @itemize @bullet
8232 @item
8233 There is no point in compiling specs (except for package
8234 specs with no bodies) because these are compiled as needed by clients. If
8235 you attempt a useless compilation, you will receive an error message.
8236 It is also useless to compile subunits because they are compiled as needed
8237 by the parent.
8239 @item
8240 There are no order of compilation requirements: performing a
8241 compilation never obsoletes anything. The only way you can obsolete
8242 something and require recompilations is to modify one of the
8243 source files on which it depends.
8245 @item
8246 There is no library as such, apart from the ALI files
8247 (@pxref{The Ada Library Information Files}, for information on the format
8248 of these files). For now we find it convenient to create separate ALI files,
8249 but eventually the information therein may be incorporated into the object
8250 file directly.
8252 @item
8253 When you compile a unit, the source files for the specs of all units
8254 that it @code{with}'s, all its subunits, and the bodies of any generics it
8255 instantiates must be available (reachable by the search-paths mechanism
8256 described above), or you will receive a fatal error message.
8257 @end itemize
8259 @node Examples
8260 @section Examples
8262 @noindent
8263 The following are some typical Ada compilation command line examples:
8265 @table @code
8266 @item $ gcc -c xyz.adb
8267 Compile body in file @file{xyz.adb} with all default options.
8269 @ifclear vms
8270 @item $ gcc -c -O2 -gnata xyz-def.adb
8271 @end ifclear
8272 @ifset vms
8273 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8274 @end ifset
8276 Compile the child unit package in file @file{xyz-def.adb} with extensive
8277 optimizations, and pragma @code{Assert}/@code{Debug} statements
8278 enabled.
8280 @item $ gcc -c -gnatc abc-def.adb
8281 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8282 mode.
8283 @end table
8285 @node Binding Using gnatbind
8286 @chapter Binding Using @code{gnatbind}
8287 @findex gnatbind
8289 @menu
8290 * Running gnatbind::
8291 * Switches for gnatbind::
8292 * Command-Line Access::
8293 * Search Paths for gnatbind::
8294 * Examples of gnatbind Usage::
8295 @end menu
8297 @noindent
8298 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8299 to bind compiled GNAT objects.
8301 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8302 driver (see @ref{The GNAT Driver and Project Files}).
8304 The @code{gnatbind} program performs four separate functions:
8306 @enumerate
8307 @item
8308 Checks that a program is consistent, in accordance with the rules in
8309 Chapter 10 of the Ada Reference Manual. In particular, error
8310 messages are generated if a program uses inconsistent versions of a
8311 given unit.
8313 @item
8314 Checks that an acceptable order of elaboration exists for the program
8315 and issues an error message if it cannot find an order of elaboration
8316 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8318 @item
8319 Generates a main program incorporating the given elaboration order.
8320 This program is a small Ada package (body and spec) that
8321 must be subsequently compiled
8322 using the GNAT compiler. The necessary compilation step is usually
8323 performed automatically by @command{gnatlink}. The two most important
8324 functions of this program
8325 are to call the elaboration routines of units in an appropriate order
8326 and to call the main program.
8328 @item
8329 Determines the set of object files required by the given main program.
8330 This information is output in the forms of comments in the generated program,
8331 to be read by the @command{gnatlink} utility used to link the Ada application.
8332 @end enumerate
8334 @node Running gnatbind
8335 @section Running @code{gnatbind}
8337 @noindent
8338 The form of the @code{gnatbind} command is
8340 @smallexample
8341 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8342 @c Expanding @ovar macro inline (explanation in macro def comments)
8343 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8344 @end smallexample
8346 @noindent
8347 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8348 unit body. @code{gnatbind} constructs an Ada
8349 package in two files whose names are
8350 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8351 For example, if given the
8352 parameter @file{hello.ali}, for a main program contained in file
8353 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8354 and @file{b~hello.adb}.
8356 When doing consistency checking, the binder takes into consideration
8357 any source files it can locate. For example, if the binder determines
8358 that the given main program requires the package @code{Pack}, whose
8359 @file{.ALI}
8360 file is @file{pack.ali} and whose corresponding source spec file is
8361 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8362 (using the same search path conventions as previously described for the
8363 @command{gcc} command). If it can locate this source file, it checks that
8364 the time stamps
8365 or source checksums of the source and its references to in @file{ALI} files
8366 match. In other words, any @file{ALI} files that mentions this spec must have
8367 resulted from compiling this version of the source file (or in the case
8368 where the source checksums match, a version close enough that the
8369 difference does not matter).
8371 @cindex Source files, use by binder
8372 The effect of this consistency checking, which includes source files, is
8373 that the binder ensures that the program is consistent with the latest
8374 version of the source files that can be located at bind time. Editing a
8375 source file without compiling files that depend on the source file cause
8376 error messages to be generated by the binder.
8378 For example, suppose you have a main program @file{hello.adb} and a
8379 package @code{P}, from file @file{p.ads} and you perform the following
8380 steps:
8382 @enumerate
8383 @item
8384 Enter @code{gcc -c hello.adb} to compile the main program.
8386 @item
8387 Enter @code{gcc -c p.ads} to compile package @code{P}.
8389 @item
8390 Edit file @file{p.ads}.
8392 @item
8393 Enter @code{gnatbind hello}.
8394 @end enumerate
8396 @noindent
8397 At this point, the file @file{p.ali} contains an out-of-date time stamp
8398 because the file @file{p.ads} has been edited. The attempt at binding
8399 fails, and the binder generates the following error messages:
8401 @smallexample
8402 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8403 error: "p.ads" has been modified and must be recompiled
8404 @end smallexample
8406 @noindent
8407 Now both files must be recompiled as indicated, and then the bind can
8408 succeed, generating a main program. You need not normally be concerned
8409 with the contents of this file, but for reference purposes a sample
8410 binder output file is given in @ref{Example of Binder Output File}.
8412 In most normal usage, the default mode of @command{gnatbind} which is to
8413 generate the main package in Ada, as described in the previous section.
8414 In particular, this means that any Ada programmer can read and understand
8415 the generated main program. It can also be debugged just like any other
8416 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8417 @command{gnatbind} and @command{gnatlink}.
8419 @node Switches for gnatbind
8420 @section Switches for @command{gnatbind}
8422 @noindent
8423 The following switches are available with @code{gnatbind}; details will
8424 be presented in subsequent sections.
8426 @menu
8427 * Consistency-Checking Modes::
8428 * Binder Error Message Control::
8429 * Elaboration Control::
8430 * Output Control::
8431 * Dynamic Allocation Control::
8432 * Binding with Non-Ada Main Programs::
8433 * Binding Programs with No Main Subprogram::
8434 @end menu
8436 @table @option
8437 @c !sort!
8439 @item --version
8440 @cindex @option{--version} @command{gnatbind}
8441 Display Copyright and version, then exit disregarding all other options.
8443 @item --help
8444 @cindex @option{--help} @command{gnatbind}
8445 If @option{--version} was not used, display usage, then exit disregarding
8446 all other options.
8448 @item -a
8449 @cindex @option{-a} @command{gnatbind}
8450 Indicates that, if supported by the platform, the adainit procedure should
8451 be treated as an initialisation routine by the linker (a constructor). This
8452 is intended to be used by the Project Manager to automatically initialize
8453 shared Stand-Alone Libraries.
8455 @item ^-aO^/OBJECT_SEARCH^
8456 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8457 Specify directory to be searched for ALI files.
8459 @item ^-aI^/SOURCE_SEARCH^
8460 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8461 Specify directory to be searched for source file.
8463 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8464 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8465 Output ALI list (to standard output or to the named file).
8467 @item ^-b^/REPORT_ERRORS=BRIEF^
8468 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8469 Generate brief messages to @file{stderr} even if verbose mode set.
8471 @item ^-c^/NOOUTPUT^
8472 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8473 Check only, no generation of binder output file.
8475 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8476 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8477 This switch can be used to change the default task stack size value
8478 to a specified size @var{nn}, which is expressed in bytes by default, or
8479 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8480 with @var{m}.
8481 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8482 in effect, to completing all task specs with
8483 @smallexample @c ada
8484    pragma Storage_Size (nn);
8485 @end smallexample
8486 When they do not already have such a pragma.
8488 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8489 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8490 This switch can be used to change the default secondary stack size value
8491 to a specified size @var{nn}, which is expressed in bytes by default, or
8492 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8493 with @var{m}.
8495 The secondary stack is used to deal with functions that return a variable
8496 sized result, for example a function returning an unconstrained
8497 String. There are two ways in which this secondary stack is allocated.
8499 For most targets, the secondary stack is growing on demand and is allocated
8500 as a chain of blocks in the heap. The -D option is not very
8501 relevant. It only give some control over the size of the allocated
8502 blocks (whose size is the minimum of the default secondary stack size value,
8503 and the actual size needed for the current allocation request).
8505 For certain targets, notably VxWorks 653,
8506 the secondary stack is allocated by carving off a fixed ratio chunk of the
8507 primary task stack. The -D option is used to define the
8508 size of the environment task's secondary stack.
8510 @item ^-e^/ELABORATION_DEPENDENCIES^
8511 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8512 Output complete list of elaboration-order dependencies.
8514 @item ^-E^/STORE_TRACEBACKS^
8515 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8516 Store tracebacks in exception occurrences when the target supports it.
8517 @ignore
8518 @c The following may get moved to an appendix
8519 This option is currently supported on the following targets:
8520 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8521 @end ignore
8522 See also the packages @code{GNAT.Traceback} and
8523 @code{GNAT.Traceback.Symbolic} for more information.
8524 @ifclear vms
8525 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8526 @command{gcc} option.
8527 @end ifclear
8529 @item ^-F^/FORCE_ELABS_FLAGS^
8530 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8531 Force the checks of elaboration flags. @command{gnatbind} does not normally
8532 generate checks of elaboration flags for the main executable, except when
8533 a Stand-Alone Library is used. However, there are cases when this cannot be
8534 detected by gnatbind. An example is importing an interface of a Stand-Alone
8535 Library through a pragma Import and only specifying through a linker switch
8536 this Stand-Alone Library. This switch is used to guarantee that elaboration
8537 flag checks are generated.
8539 @item ^-h^/HELP^
8540 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8541 Output usage (help) information
8543 @item ^-H32^/32_MALLOC^
8544 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8545 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8546 For further details see @ref{Dynamic Allocation Control}.
8548 @item ^-H64^/64_MALLOC^
8549 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8550 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8551 @cindex @code{__gnat_malloc}
8552 For further details see @ref{Dynamic Allocation Control}.
8554 @item ^-I^/SEARCH^
8555 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8556 Specify directory to be searched for source and ALI files.
8558 @item ^-I-^/NOCURRENT_DIRECTORY^
8559 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8560 Do not look for sources in the current directory where @code{gnatbind} was
8561 invoked, and do not look for ALI files in the directory containing the
8562 ALI file named in the @code{gnatbind} command line.
8564 @item ^-l^/ORDER_OF_ELABORATION^
8565 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8566 Output chosen elaboration order.
8568 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8569 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8570 Bind the units for library building. In this case the adainit and
8571 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8572 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8573 ^@var{xxx}final^@var{XXX}FINAL^.
8574 Implies ^-n^/NOCOMPILE^.
8575 @ifclear vms
8576 (@xref{GNAT and Libraries}, for more details.)
8577 @end ifclear
8578 @ifset vms
8579 On OpenVMS, these init and final procedures are exported in uppercase
8580 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8581 the init procedure will be "TOTOINIT" and the exported name of the final
8582 procedure will be "TOTOFINAL".
8583 @end ifset
8585 @item ^-Mxyz^/RENAME_MAIN=xyz^
8586 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8587 Rename generated main program from main to xyz. This option is
8588 supported on cross environments only.
8590 @item ^-m^/ERROR_LIMIT=^@var{n}
8591 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8592 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8593 in the range 1..999999. The default value if no switch is
8594 given is 9999. If the number of warnings reaches this limit, then a
8595 message is output and further warnings are suppressed, the bind
8596 continues in this case. If the number of errors reaches this
8597 limit, then a message is output and the bind is abandoned.
8598 A value of zero means that no limit is enforced. The equal
8599 sign is optional.
8601 @ifset unw
8602 Furthermore, under Windows, the sources pointed to by the libraries path
8603 set in the registry are not searched for.
8604 @end ifset
8606 @item ^-n^/NOMAIN^
8607 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8608 No main program.
8610 @item -nostdinc
8611 @cindex @option{-nostdinc} (@command{gnatbind})
8612 Do not look for sources in the system default directory.
8614 @item -nostdlib
8615 @cindex @option{-nostdlib} (@command{gnatbind})
8616 Do not look for library files in the system default directory.
8618 @item --RTS=@var{rts-path}
8619 @cindex @option{--RTS} (@code{gnatbind})
8620 Specifies the default location of the runtime library. Same meaning as the
8621 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8623 @item ^-o ^/OUTPUT=^@var{file}
8624 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8625 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8626 Note that if this option is used, then linking must be done manually,
8627 gnatlink cannot be used.
8629 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8630 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8631 Output object list (to standard output or to the named file).
8633 @item ^-p^/PESSIMISTIC_ELABORATION^
8634 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8635 Pessimistic (worst-case) elaboration order
8637 @item ^-P^-P^
8638 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8639 Generate binder file suitable for CodePeer.
8641 @item ^-R^-R^
8642 @cindex @option{^-R^-R^} (@command{gnatbind})
8643 Output closure source list.
8645 @item ^-s^/READ_SOURCES=ALL^
8646 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8647 Require all source files to be present.
8649 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8650 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8651 Specifies the value to be used when detecting uninitialized scalar
8652 objects with pragma Initialize_Scalars.
8653 The @var{xxx} ^string specified with the switch^option^ may be either
8654 @itemize @bullet
8655 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8656 @item ``@option{^lo^LOW^}'' for the lowest possible value
8657 @item ``@option{^hi^HIGH^}'' for the highest possible value
8658 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8659 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8660 @end itemize
8662 In addition, you can specify @option{-Sev} to indicate that the value is
8663 to be set at run time. In this case, the program will look for an environment
8664 @cindex GNAT_INIT_SCALARS
8665 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8666 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8667 If no environment variable is found, or if it does not have a valid value,
8668 then the default is @option{in} (invalid values).
8670 @ifclear vms
8671 @item -static
8672 @cindex @option{-static} (@code{gnatbind})
8673 Link against a static GNAT run time.
8675 @item -shared
8676 @cindex @option{-shared} (@code{gnatbind})
8677 Link against a shared GNAT run time when available.
8678 @end ifclear
8680 @item ^-t^/NOTIME_STAMP_CHECK^
8681 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8682 Tolerate time stamp and other consistency errors
8684 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8685 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8686 Set the time slice value to @var{n} milliseconds. If the system supports
8687 the specification of a specific time slice value, then the indicated value
8688 is used. If the system does not support specific time slice values, but
8689 does support some general notion of round-robin scheduling, then any
8690 nonzero value will activate round-robin scheduling.
8692 A value of zero is treated specially. It turns off time
8693 slicing, and in addition, indicates to the tasking run time that the
8694 semantics should match as closely as possible the Annex D
8695 requirements of the Ada RM, and in particular sets the default
8696 scheduling policy to @code{FIFO_Within_Priorities}.
8698 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8699 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8700 Enable dynamic stack usage, with @var{n} results stored and displayed
8701 at program termination. A result is generated when a task
8702 terminates. Results that can't be stored are displayed on the fly, at
8703 task termination. This option is currently not supported on Itanium
8704 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8706 @item ^-v^/REPORT_ERRORS=VERBOSE^
8707 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8708 Verbose mode. Write error messages, header, summary output to
8709 @file{stdout}.
8711 @ifclear vms
8712 @item -w@var{x}
8713 @cindex @option{-w} (@code{gnatbind})
8714 Warning mode (@var{x}=s/e for suppress/treat as error)
8715 @end ifclear
8717 @ifset vms
8718 @item /WARNINGS=NORMAL
8719 @cindex @option{/WARNINGS} (@code{gnatbind})
8720 Normal warnings mode. Warnings are issued but ignored
8722 @item /WARNINGS=SUPPRESS
8723 @cindex @option{/WARNINGS} (@code{gnatbind})
8724 All warning messages are suppressed
8726 @item /WARNINGS=ERROR
8727 @cindex @option{/WARNINGS} (@code{gnatbind})
8728 Warning messages are treated as fatal errors
8729 @end ifset
8731 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8732 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8733 Override default wide character encoding for standard Text_IO files.
8735 @item ^-x^/READ_SOURCES=NONE^
8736 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8737 Exclude source files (check object consistency only).
8739 @ifset vms
8740 @item /READ_SOURCES=AVAILABLE
8741 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8742 Default mode, in which sources are checked for consistency only if
8743 they are available.
8744 @end ifset
8746 @item ^-y^/ENABLE_LEAP_SECONDS^
8747 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8748 Enable leap seconds support in @code{Ada.Calendar} and its children.
8750 @item ^-z^/ZERO_MAIN^
8751 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8752 No main subprogram.
8753 @end table
8755 @ifclear vms
8756 @noindent
8757 You may obtain this listing of switches by running @code{gnatbind} with
8758 no arguments.
8759 @end ifclear
8761 @node Consistency-Checking Modes
8762 @subsection Consistency-Checking Modes
8764 @noindent
8765 As described earlier, by default @code{gnatbind} checks
8766 that object files are consistent with one another and are consistent
8767 with any source files it can locate. The following switches control binder
8768 access to sources.
8770 @table @option
8771 @c !sort!
8772 @item ^-s^/READ_SOURCES=ALL^
8773 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8774 Require source files to be present. In this mode, the binder must be
8775 able to locate all source files that are referenced, in order to check
8776 their consistency. In normal mode, if a source file cannot be located it
8777 is simply ignored. If you specify this switch, a missing source
8778 file is an error.
8780 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8781 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8782 Override default wide character encoding for standard Text_IO files.
8783 Normally the default wide character encoding method used for standard
8784 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8785 the main source input (see description of switch
8786 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8787 use of this switch for the binder (which has the same set of
8788 possible arguments) overrides this default as specified.
8790 @item ^-x^/READ_SOURCES=NONE^
8791 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8792 Exclude source files. In this mode, the binder only checks that ALI
8793 files are consistent with one another. Source files are not accessed.
8794 The binder runs faster in this mode, and there is still a guarantee that
8795 the resulting program is self-consistent.
8796 If a source file has been edited since it was last compiled, and you
8797 specify this switch, the binder will not detect that the object
8798 file is out of date with respect to the source file. Note that this is the
8799 mode that is automatically used by @command{gnatmake} because in this
8800 case the checking against sources has already been performed by
8801 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8803 @ifset vms
8804 @item /READ_SOURCES=AVAILABLE
8805 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8806 This is the default mode in which source files are checked if they are
8807 available, and ignored if they are not available.
8808 @end ifset
8809 @end table
8811 @node Binder Error Message Control
8812 @subsection Binder Error Message Control
8814 @noindent
8815 The following switches provide control over the generation of error
8816 messages from the binder:
8818 @table @option
8819 @c !sort!
8820 @item ^-v^/REPORT_ERRORS=VERBOSE^
8821 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8822 Verbose mode. In the normal mode, brief error messages are generated to
8823 @file{stderr}. If this switch is present, a header is written
8824 to @file{stdout} and any error messages are directed to @file{stdout}.
8825 All that is written to @file{stderr} is a brief summary message.
8827 @item ^-b^/REPORT_ERRORS=BRIEF^
8828 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8829 Generate brief error messages to @file{stderr} even if verbose mode is
8830 specified. This is relevant only when used with the
8831 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8833 @ifclear vms
8834 @item -m@var{n}
8835 @cindex @option{-m} (@code{gnatbind})
8836 Limits the number of error messages to @var{n}, a decimal integer in the
8837 range 1-999. The binder terminates immediately if this limit is reached.
8839 @item -M@var{xxx}
8840 @cindex @option{-M} (@code{gnatbind})
8841 Renames the generated main program from @code{main} to @code{xxx}.
8842 This is useful in the case of some cross-building environments, where
8843 the actual main program is separate from the one generated
8844 by @code{gnatbind}.
8845 @end ifclear
8847 @item ^-ws^/WARNINGS=SUPPRESS^
8848 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8849 @cindex Warnings
8850 Suppress all warning messages.
8852 @item ^-we^/WARNINGS=ERROR^
8853 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8854 Treat any warning messages as fatal errors.
8856 @ifset vms
8857 @item /WARNINGS=NORMAL
8858 Standard mode with warnings generated, but warnings do not get treated
8859 as errors.
8860 @end ifset
8862 @item ^-t^/NOTIME_STAMP_CHECK^
8863 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8864 @cindex Time stamp checks, in binder
8865 @cindex Binder consistency checks
8866 @cindex Consistency checks, in binder
8867 The binder performs a number of consistency checks including:
8869 @itemize @bullet
8870 @item
8871 Check that time stamps of a given source unit are consistent
8872 @item
8873 Check that checksums of a given source unit are consistent
8874 @item
8875 Check that consistent versions of @code{GNAT} were used for compilation
8876 @item
8877 Check consistency of configuration pragmas as required
8878 @end itemize
8880 @noindent
8881 Normally failure of such checks, in accordance with the consistency
8882 requirements of the Ada Reference Manual, causes error messages to be
8883 generated which abort the binder and prevent the output of a binder
8884 file and subsequent link to obtain an executable.
8886 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8887 into warnings, so that
8888 binding and linking can continue to completion even in the presence of such
8889 errors. The result may be a failed link (due to missing symbols), or a
8890 non-functional executable which has undefined semantics.
8891 @emph{This means that
8892 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8893 with extreme care.}
8894 @end table
8896 @node Elaboration Control
8897 @subsection Elaboration Control
8899 @noindent
8900 The following switches provide additional control over the elaboration
8901 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8903 @table @option
8904 @item ^-p^/PESSIMISTIC_ELABORATION^
8905 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8906 Normally the binder attempts to choose an elaboration order that is
8907 likely to minimize the likelihood of an elaboration order error resulting
8908 in raising a @code{Program_Error} exception. This switch reverses the
8909 action of the binder, and requests that it deliberately choose an order
8910 that is likely to maximize the likelihood of an elaboration error.
8911 This is useful in ensuring portability and avoiding dependence on
8912 accidental fortuitous elaboration ordering.
8914 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8915 switch if dynamic
8916 elaboration checking is used (@option{-gnatE} switch used for compilation).
8917 This is because in the default static elaboration mode, all necessary
8918 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8919 These implicit pragmas are still respected by the binder in
8920 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8921 safe elaboration order is assured.
8923 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8924 production use; it is more for debugging/experimental use.
8925 @end table
8927 @node Output Control
8928 @subsection Output Control
8930 @noindent
8931 The following switches allow additional control over the output
8932 generated by the binder.
8934 @table @option
8935 @c !sort!
8937 @item ^-c^/NOOUTPUT^
8938 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8939 Check only. Do not generate the binder output file. In this mode the
8940 binder performs all error checks but does not generate an output file.
8942 @item ^-e^/ELABORATION_DEPENDENCIES^
8943 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8944 Output complete list of elaboration-order dependencies, showing the
8945 reason for each dependency. This output can be rather extensive but may
8946 be useful in diagnosing problems with elaboration order. The output is
8947 written to @file{stdout}.
8949 @item ^-h^/HELP^
8950 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8951 Output usage information. The output is written to @file{stdout}.
8953 @item ^-K^/LINKER_OPTION_LIST^
8954 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8955 Output linker options to @file{stdout}. Includes library search paths,
8956 contents of pragmas Ident and Linker_Options, and libraries added
8957 by @code{gnatbind}.
8959 @item ^-l^/ORDER_OF_ELABORATION^
8960 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8961 Output chosen elaboration order. The output is written to @file{stdout}.
8963 @item ^-O^/OBJECT_LIST^
8964 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8965 Output full names of all the object files that must be linked to provide
8966 the Ada component of the program. The output is written to @file{stdout}.
8967 This list includes the files explicitly supplied and referenced by the user
8968 as well as implicitly referenced run-time unit files. The latter are
8969 omitted if the corresponding units reside in shared libraries. The
8970 directory names for the run-time units depend on the system configuration.
8972 @item ^-o ^/OUTPUT=^@var{file}
8973 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8974 Set name of output file to @var{file} instead of the normal
8975 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8976 binder generated body filename.
8977 Note that if this option is used, then linking must be done manually.
8978 It is not possible to use gnatlink in this case, since it cannot locate
8979 the binder file.
8981 @item ^-r^/RESTRICTION_LIST^
8982 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8983 Generate list of @code{pragma Restrictions} that could be applied to
8984 the current unit. This is useful for code audit purposes, and also may
8985 be used to improve code generation in some cases.
8987 @end table
8989 @node Dynamic Allocation Control
8990 @subsection Dynamic Allocation Control
8992 @noindent
8993 The heap control switches -- @option{-H32} and @option{-H64} --
8994 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8995 They only affect compiler-generated allocations via @code{__gnat_malloc};
8996 explicit calls to @code{malloc} and related functions from the C
8997 run-time library are unaffected.
8999 @table @option
9000 @item -H32
9001 Allocate memory on 32-bit heap
9003 @item -H64
9004 Allocate memory on 64-bit heap.  This is the default
9005 unless explicitly overridden by a @code{'Size} clause on the access type.
9006 @end table
9008 @ifset vms
9009 @noindent
9010 See also @ref{Access types and 32/64-bit allocation}.
9011 @end ifset
9012 @ifclear vms
9013 @noindent
9014 These switches are only effective on VMS platforms.
9015 @end ifclear
9018 @node Binding with Non-Ada Main Programs
9019 @subsection Binding with Non-Ada Main Programs
9021 @noindent
9022 In our description so far we have assumed that the main
9023 program is in Ada, and that the task of the binder is to generate a
9024 corresponding function @code{main} that invokes this Ada main
9025 program. GNAT also supports the building of executable programs where
9026 the main program is not in Ada, but some of the called routines are
9027 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
9028 The following switch is used in this situation:
9030 @table @option
9031 @item ^-n^/NOMAIN^
9032 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
9033 No main program. The main program is not in Ada.
9034 @end table
9036 @noindent
9037 In this case, most of the functions of the binder are still required,
9038 but instead of generating a main program, the binder generates a file
9039 containing the following callable routines:
9041 @table @code
9042 @item adainit
9043 @findex adainit
9044 You must call this routine to initialize the Ada part of the program by
9045 calling the necessary elaboration routines. A call to @code{adainit} is
9046 required before the first call to an Ada subprogram.
9048 Note that it is assumed that the basic execution environment must be setup
9049 to be appropriate for Ada execution at the point where the first Ada
9050 subprogram is called. In particular, if the Ada code will do any
9051 floating-point operations, then the FPU must be setup in an appropriate
9052 manner. For the case of the x86, for example, full precision mode is
9053 required. The procedure GNAT.Float_Control.Reset may be used to ensure
9054 that the FPU is in the right state.
9056 @item adafinal
9057 @findex adafinal
9058 You must call this routine to perform any library-level finalization
9059 required by the Ada subprograms. A call to @code{adafinal} is required
9060 after the last call to an Ada subprogram, and before the program
9061 terminates.
9062 @end table
9064 @noindent
9065 If the @option{^-n^/NOMAIN^} switch
9066 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
9067 @cindex Binder, multiple input files
9068 is given, more than one ALI file may appear on
9069 the command line for @code{gnatbind}. The normal @dfn{closure}
9070 calculation is performed for each of the specified units. Calculating
9071 the closure means finding out the set of units involved by tracing
9072 @code{with} references. The reason it is necessary to be able to
9073 specify more than one ALI file is that a given program may invoke two or
9074 more quite separate groups of Ada units.
9076 The binder takes the name of its output file from the last specified ALI
9077 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
9078 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
9079 The output is an Ada unit in source form that can be compiled with GNAT.
9080 This compilation occurs automatically as part of the @command{gnatlink}
9081 processing.
9083 Currently the GNAT run time requires a FPU using 80 bits mode
9084 precision. Under targets where this is not the default it is required to
9085 call GNAT.Float_Control.Reset before using floating point numbers (this
9086 include float computation, float input and output) in the Ada code. A
9087 side effect is that this could be the wrong mode for the foreign code
9088 where floating point computation could be broken after this call.
9090 @node Binding Programs with No Main Subprogram
9091 @subsection Binding Programs with No Main Subprogram
9093 @noindent
9094 It is possible to have an Ada program which does not have a main
9095 subprogram. This program will call the elaboration routines of all the
9096 packages, then the finalization routines.
9098 The following switch is used to bind programs organized in this manner:
9100 @table @option
9101 @item ^-z^/ZERO_MAIN^
9102 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
9103 Normally the binder checks that the unit name given on the command line
9104 corresponds to a suitable main subprogram. When this switch is used,
9105 a list of ALI files can be given, and the execution of the program
9106 consists of elaboration of these units in an appropriate order. Note
9107 that the default wide character encoding method for standard Text_IO
9108 files is always set to Brackets if this switch is set (you can use
9109 the binder switch
9110 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
9111 @end table
9113 @node Command-Line Access
9114 @section Command-Line Access
9116 @noindent
9117 The package @code{Ada.Command_Line} provides access to the command-line
9118 arguments and program name. In order for this interface to operate
9119 correctly, the two variables
9121 @smallexample
9122 @group
9123 int gnat_argc;
9124 char **gnat_argv;
9125 @end group
9126 @end smallexample
9128 @noindent
9129 @findex gnat_argv
9130 @findex gnat_argc
9131 are declared in one of the GNAT library routines. These variables must
9132 be set from the actual @code{argc} and @code{argv} values passed to the
9133 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
9134 generates the C main program to automatically set these variables.
9135 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
9136 set these variables. If they are not set, the procedures in
9137 @code{Ada.Command_Line} will not be available, and any attempt to use
9138 them will raise @code{Constraint_Error}. If command line access is
9139 required, your main program must set @code{gnat_argc} and
9140 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
9143 @node Search Paths for gnatbind
9144 @section Search Paths for @code{gnatbind}
9146 @noindent
9147 The binder takes the name of an ALI file as its argument and needs to
9148 locate source files as well as other ALI files to verify object consistency.
9150 For source files, it follows exactly the same search rules as @command{gcc}
9151 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
9152 directories searched are:
9154 @enumerate
9155 @item
9156 The directory containing the ALI file named in the command line, unless
9157 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
9159 @item
9160 All directories specified by @option{^-I^/SEARCH^}
9161 switches on the @code{gnatbind}
9162 command line, in the order given.
9164 @item
9165 @findex ADA_PRJ_OBJECTS_FILE
9166 Each of the directories listed in the text file whose name is given
9167 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
9169 @noindent
9170 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
9171 driver when project files are used. It should not normally be set
9172 by other means.
9174 @item
9175 @findex ADA_OBJECTS_PATH
9176 Each of the directories listed in the value of the
9177 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
9178 @ifset unw
9179 Construct this value
9180 exactly as the @env{PATH} environment variable: a list of directory
9181 names separated by colons (semicolons when working with the NT version
9182 of GNAT).
9183 @end ifset
9184 @ifset vms
9185 Normally, define this value as a logical name containing a comma separated
9186 list of directory names.
9188 This variable can also be defined by means of an environment string
9189 (an argument to the HP C exec* set of functions).
9191 Logical Name:
9192 @smallexample
9193 DEFINE ANOTHER_PATH FOO:[BAG]
9194 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9195 @end smallexample
9197 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9198 first, followed by the standard Ada
9199 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9200 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9201 (Text_IO, Sequential_IO, etc)
9202 instead of the standard Ada packages. Thus, in order to get the standard Ada
9203 packages by default, ADA_OBJECTS_PATH must be redefined.
9204 @end ifset
9206 @item
9207 The content of the @file{ada_object_path} file which is part of the GNAT
9208 installation tree and is used to store standard libraries such as the
9209 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9210 specified.
9211 @ifclear vms
9212 @ref{Installing a library}
9213 @end ifclear
9214 @end enumerate
9216 @noindent
9217 In the binder the switch @option{^-I^/SEARCH^}
9218 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9219 is used to specify both source and
9220 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9221 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9222 instead if you want to specify
9223 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9224 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9225 if you want to specify library paths
9226 only. This means that for the binder
9227 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9228 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9229 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9230 The binder generates the bind file (a C language source file) in the
9231 current working directory.
9233 @findex Ada
9234 @findex System
9235 @findex Interfaces
9236 @findex GNAT
9237 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9238 children make up the GNAT Run-Time Library, together with the package
9239 GNAT and its children, which contain a set of useful additional
9240 library functions provided by GNAT. The sources for these units are
9241 needed by the compiler and are kept together in one directory. The ALI
9242 files and object files generated by compiling the RTL are needed by the
9243 binder and the linker and are kept together in one directory, typically
9244 different from the directory containing the sources. In a normal
9245 installation, you need not specify these directory names when compiling
9246 or binding. Either the environment variables or the built-in defaults
9247 cause these files to be found.
9249 Besides simplifying access to the RTL, a major use of search paths is
9250 in compiling sources from multiple directories. This can make
9251 development environments much more flexible.
9253 @node Examples of gnatbind Usage
9254 @section Examples of @code{gnatbind} Usage
9256 @noindent
9257 This section contains a number of examples of using the GNAT binding
9258 utility @code{gnatbind}.
9260 @table @code
9261 @item gnatbind hello
9262 The main program @code{Hello} (source program in @file{hello.adb}) is
9263 bound using the standard switch settings. The generated main program is
9264 @file{b~hello.adb}. This is the normal, default use of the binder.
9266 @ifclear vms
9267 @item gnatbind hello -o mainprog.adb
9268 @end ifclear
9269 @ifset vms
9270 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9271 @end ifset
9272 The main program @code{Hello} (source program in @file{hello.adb}) is
9273 bound using the standard switch settings. The generated main program is
9274 @file{mainprog.adb} with the associated spec in
9275 @file{mainprog.ads}. Note that you must specify the body here not the
9276 spec. Note that if this option is used, then linking must be done manually,
9277 since gnatlink will not be able to find the generated file.
9278 @end table
9280 @c ------------------------------------
9281 @node Linking Using gnatlink
9282 @chapter Linking Using @command{gnatlink}
9283 @c ------------------------------------
9284 @findex gnatlink
9286 @noindent
9287 This chapter discusses @command{gnatlink}, a tool that links
9288 an Ada program and builds an executable file. This utility
9289 invokes the system linker ^(via the @command{gcc} command)^^
9290 with a correct list of object files and library references.
9291 @command{gnatlink} automatically determines the list of files and
9292 references for the Ada part of a program. It uses the binder file
9293 generated by the @command{gnatbind} to determine this list.
9295 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9296 driver (see @ref{The GNAT Driver and Project Files}).
9298 @menu
9299 * Running gnatlink::
9300 * Switches for gnatlink::
9301 @end menu
9303 @node Running gnatlink
9304 @section Running @command{gnatlink}
9306 @noindent
9307 The form of the @command{gnatlink} command is
9309 @smallexample
9310 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9311 @c            @ovar{non-Ada objects} @ovar{linker options}
9312 @c Expanding @ovar macro inline (explanation in macro def comments)
9313 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9314            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9316 @end smallexample
9318 @noindent
9319 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9320 non-Ada objects
9321 or linker options) may be in any order, provided that no non-Ada object may
9322 be mistaken for a main @file{ALI} file.
9323 Any file name @file{F} without the @file{.ali}
9324 extension will be taken as the main @file{ALI} file if a file exists
9325 whose name is the concatenation of @file{F} and @file{.ali}.
9327 @noindent
9328 @file{@var{mainprog}.ali} references the ALI file of the main program.
9329 The @file{.ali} extension of this file can be omitted. From this
9330 reference, @command{gnatlink} locates the corresponding binder file
9331 @file{b~@var{mainprog}.adb} and, using the information in this file along
9332 with the list of non-Ada objects and linker options, constructs a
9333 linker command file to create the executable.
9335 The arguments other than the @command{gnatlink} switches and the main
9336 @file{ALI} file are passed to the linker uninterpreted.
9337 They typically include the names of
9338 object files for units written in other languages than Ada and any library
9339 references required to resolve references in any of these foreign language
9340 units, or in @code{Import} pragmas in any Ada units.
9342 @var{linker options} is an optional list of linker specific
9343 switches.
9344 The default linker called by gnatlink is @command{gcc} which in
9345 turn calls the appropriate system linker.
9347 One useful option for the linker is @option{-s}: it reduces the size of the
9348 executable by removing all symbol table and relocation information from the
9349 executable.
9351 Standard options for the linker such as @option{-lmy_lib} or
9352 @option{-Ldir} can be added as is.
9353 For options that are not recognized by
9354 @command{gcc} as linker options, use the @command{gcc} switches
9355 @option{-Xlinker} or @option{-Wl,}.
9357 Refer to the GCC documentation for
9358 details.
9360 Here is an example showing how to generate a linker map:
9362 @smallexample
9363 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9364 @end smallexample
9366 Using @var{linker options} it is possible to set the program stack and
9367 heap size.
9368 @ifset unw
9369 See @ref{Setting Stack Size from gnatlink} and
9370 @ref{Setting Heap Size from gnatlink}.
9371 @end ifset
9373 @command{gnatlink} determines the list of objects required by the Ada
9374 program and prepends them to the list of objects passed to the linker.
9375 @command{gnatlink} also gathers any arguments set by the use of
9376 @code{pragma Linker_Options} and adds them to the list of arguments
9377 presented to the linker.
9379 @ifset vms
9380 @command{gnatlink} accepts the following types of extra files on the command
9381 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9382 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9383 handled according to their extension.
9384 @end ifset
9386 @node Switches for gnatlink
9387 @section Switches for @command{gnatlink}
9389 @noindent
9390 The following switches are available with the @command{gnatlink} utility:
9392 @table @option
9393 @c !sort!
9395 @item --version
9396 @cindex @option{--version} @command{gnatlink}
9397 Display Copyright and version, then exit disregarding all other options.
9399 @item --help
9400 @cindex @option{--help} @command{gnatlink}
9401 If @option{--version} was not used, display usage, then exit disregarding
9402 all other options.
9404 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9405 @cindex Command line length
9406 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9407 On some targets, the command line length is limited, and @command{gnatlink}
9408 will generate a separate file for the linker if the list of object files
9409 is too long.
9410 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9411 to be generated even if
9412 the limit is not exceeded. This is useful in some cases to deal with
9413 special situations where the command line length is exceeded.
9415 @item ^-g^/DEBUG^
9416 @cindex Debugging information, including
9417 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9418 The option to include debugging information causes the Ada bind file (in
9419 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9420 @option{^-g^/DEBUG^}.
9421 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9422 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9423 Without @option{^-g^/DEBUG^}, the binder removes these files by
9424 default. The same procedure apply if a C bind file was generated using
9425 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9426 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9428 @item ^-n^/NOCOMPILE^
9429 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9430 Do not compile the file generated by the binder. This may be used when
9431 a link is rerun with different options, but there is no need to recompile
9432 the binder file.
9434 @item ^-v^/VERBOSE^
9435 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9436 Causes additional information to be output, including a full list of the
9437 included object files. This switch option is most useful when you want
9438 to see what set of object files are being used in the link step.
9440 @item ^-v -v^/VERBOSE/VERBOSE^
9441 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9442 Very verbose mode. Requests that the compiler operate in verbose mode when
9443 it compiles the binder file, and that the system linker run in verbose mode.
9445 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9446 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9447 @var{exec-name} specifies an alternate name for the generated
9448 executable program. If this switch is omitted, the executable has the same
9449 name as the main unit. For example, @code{gnatlink try.ali} creates
9450 an executable called @file{^try^TRY.EXE^}.
9452 @ifclear vms
9453 @item -b @var{target}
9454 @cindex @option{-b} (@command{gnatlink})
9455 Compile your program to run on @var{target}, which is the name of a
9456 system configuration. You must have a GNAT cross-compiler built if
9457 @var{target} is not the same as your host system.
9459 @item -B@var{dir}
9460 @cindex @option{-B} (@command{gnatlink})
9461 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9462 from @var{dir} instead of the default location. Only use this switch
9463 when multiple versions of the GNAT compiler are available.
9464 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9465 for further details. You would normally use the @option{-b} or
9466 @option{-V} switch instead.
9468 @item -M
9469 When linking an executable, create a map file. The name of the map file
9470 has the same name as the executable with extension ".map".
9472 @item -M=mapfile
9473 When linking an executable, create a map file. The name of the map file is
9474 "mapfile".
9476 @item --GCC=@var{compiler_name}
9477 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9478 Program used for compiling the binder file. The default is
9479 @command{gcc}. You need to use quotes around @var{compiler_name} if
9480 @code{compiler_name} contains spaces or other separator characters.
9481 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9482 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9483 inserted after your command name. Thus in the above example the compiler
9484 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9485 A limitation of this syntax is that the name and path name of the executable
9486 itself must not include any embedded spaces. If the compiler executable is
9487 different from the default one (gcc or <prefix>-gcc), then the back-end
9488 switches in the ALI file are not used to compile the binder generated source.
9489 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9490 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9491 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9492 is taken into account. However, all the additional switches are also taken
9493 into account. Thus,
9494 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9495 @option{--GCC="bar -x -y -z -t"}.
9497 @item --LINK=@var{name}
9498 @cindex @option{--LINK=} (@command{gnatlink})
9499 @var{name} is the name of the linker to be invoked. This is especially
9500 useful in mixed language programs since languages such as C++ require
9501 their own linker to be used. When this switch is omitted, the default
9502 name for the linker is @command{gcc}. When this switch is used, the
9503 specified linker is called instead of @command{gcc} with exactly the same
9504 parameters that would have been passed to @command{gcc} so if the desired
9505 linker requires different parameters it is necessary to use a wrapper
9506 script that massages the parameters before invoking the real linker. It
9507 may be useful to control the exact invocation by using the verbose
9508 switch.
9510 @end ifclear
9512 @ifset vms
9513 @item /DEBUG=TRACEBACK
9514 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9515 This qualifier causes sufficient information to be included in the
9516 executable file to allow a traceback, but does not include the full
9517 symbol information needed by the debugger.
9519 @item /IDENTIFICATION="<string>"
9520 @code{"<string>"} specifies the string to be stored in the image file
9521 identification field in the image header.
9522 It overrides any pragma @code{Ident} specified string.
9524 @item /NOINHIBIT-EXEC
9525 Generate the executable file even if there are linker warnings.
9527 @item /NOSTART_FILES
9528 Don't link in the object file containing the ``main'' transfer address.
9529 Used when linking with a foreign language main program compiled with an
9530 HP compiler.
9532 @item /STATIC
9533 Prefer linking with object libraries over sharable images, even without
9534 /DEBUG.
9535 @end ifset
9537 @end table
9539 @node The GNAT Make Program gnatmake
9540 @chapter The GNAT Make Program @command{gnatmake}
9541 @findex gnatmake
9543 @menu
9544 * Running gnatmake::
9545 * Switches for gnatmake::
9546 * Mode Switches for gnatmake::
9547 * Notes on the Command Line::
9548 * How gnatmake Works::
9549 * Examples of gnatmake Usage::
9550 @end menu
9551 @noindent
9552 A typical development cycle when working on an Ada program consists of
9553 the following steps:
9555 @enumerate
9556 @item
9557 Edit some sources to fix bugs.
9559 @item
9560 Add enhancements.
9562 @item
9563 Compile all sources affected.
9565 @item
9566 Rebind and relink.
9568 @item
9569 Test.
9570 @end enumerate
9572 @noindent
9573 The third step can be tricky, because not only do the modified files
9574 @cindex Dependency rules
9575 have to be compiled, but any files depending on these files must also be
9576 recompiled. The dependency rules in Ada can be quite complex, especially
9577 in the presence of overloading, @code{use} clauses, generics and inlined
9578 subprograms.
9580 @command{gnatmake} automatically takes care of the third and fourth steps
9581 of this process. It determines which sources need to be compiled,
9582 compiles them, and binds and links the resulting object files.
9584 Unlike some other Ada make programs, the dependencies are always
9585 accurately recomputed from the new sources. The source based approach of
9586 the GNAT compilation model makes this possible. This means that if
9587 changes to the source program cause corresponding changes in
9588 dependencies, they will always be tracked exactly correctly by
9589 @command{gnatmake}.
9591 @node Running gnatmake
9592 @section Running @command{gnatmake}
9594 @noindent
9595 The usual form of the @command{gnatmake} command is
9597 @smallexample
9598 @c $ gnatmake @ovar{switches} @var{file_name}
9599 @c       @ovar{file_names} @ovar{mode_switches}
9600 @c Expanding @ovar macro inline (explanation in macro def comments)
9601 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9602       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9603 @end smallexample
9605 @noindent
9606 The only required argument is one @var{file_name}, which specifies
9607 a compilation unit that is a main program. Several @var{file_names} can be
9608 specified: this will result in several executables being built.
9609 If @code{switches} are present, they can be placed before the first
9610 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9611 If @var{mode_switches} are present, they must always be placed after
9612 the last @var{file_name} and all @code{switches}.
9614 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9615 extension may be omitted from the @var{file_name} arguments. However, if
9616 you are using non-standard extensions, then it is required that the
9617 extension be given. A relative or absolute directory path can be
9618 specified in a @var{file_name}, in which case, the input source file will
9619 be searched for in the specified directory only. Otherwise, the input
9620 source file will first be searched in the directory where
9621 @command{gnatmake} was invoked and if it is not found, it will be search on
9622 the source path of the compiler as described in
9623 @ref{Search Paths and the Run-Time Library (RTL)}.
9625 All @command{gnatmake} output (except when you specify
9626 @option{^-M^/DEPENDENCIES_LIST^}) is to
9627 @file{stderr}. The output produced by the
9628 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9629 @file{stdout}.
9631 @node Switches for gnatmake
9632 @section Switches for @command{gnatmake}
9634 @noindent
9635 You may specify any of the following switches to @command{gnatmake}:
9637 @table @option
9638 @c !sort!
9640 @item --version
9641 @cindex @option{--version} @command{gnatmake}
9642 Display Copyright and version, then exit disregarding all other options.
9644 @item --help
9645 @cindex @option{--help} @command{gnatmake}
9646 If @option{--version} was not used, display usage, then exit disregarding
9647 all other options.
9649 @ifclear vms
9650 @item --GCC=@var{compiler_name}
9651 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9652 Program used for compiling. The default is `@command{gcc}'. You need to use
9653 quotes around @var{compiler_name} if @code{compiler_name} contains
9654 spaces or other separator characters. As an example @option{--GCC="foo -x
9655 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9656 compiler. A limitation of this syntax is that the name and path name of
9657 the executable itself must not include any embedded spaces. Note that
9658 switch @option{-c} is always inserted after your command name. Thus in the
9659 above example the compiler command that will be used by @command{gnatmake}
9660 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9661 used, only the last @var{compiler_name} is taken into account. However,
9662 all the additional switches are also taken into account. Thus,
9663 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9664 @option{--GCC="bar -x -y -z -t"}.
9666 @item --GNATBIND=@var{binder_name}
9667 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9668 Program used for binding. The default is `@code{gnatbind}'. You need to
9669 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9670 or other separator characters. As an example @option{--GNATBIND="bar -x
9671 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9672 binder. Binder switches that are normally appended by @command{gnatmake}
9673 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9674 A limitation of this syntax is that the name and path name of the executable
9675 itself must not include any embedded spaces.
9677 @item --GNATLINK=@var{linker_name}
9678 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9679 Program used for linking. The default is `@command{gnatlink}'. You need to
9680 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9681 or other separator characters. As an example @option{--GNATLINK="lan -x
9682 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9683 linker. Linker switches that are normally appended by @command{gnatmake} to
9684 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9685 A limitation of this syntax is that the name and path name of the executable
9686 itself must not include any embedded spaces.
9688 @end ifclear
9690 @item ^--subdirs^/SUBDIRS^=subdir
9691 Actual object directory of each project file is the subdirectory subdir of the
9692 object directory specified or defaulted in the project file.
9694 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9695 Disallow simultaneous compilations in the same object directory when
9696 project files are used.
9698 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9699 By default, shared library projects are not allowed to import static library
9700 projects. When this switch is used on the command line, this restriction is
9701 relaxed.
9703 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9704 Specify a source info file. This switch is active only when project files
9705 are used. If the source info file is specified as a relative path, then it is
9706 relative to the object directory of the main project. If the source info file
9707 does not exist, then after the Project Manager has successfully parsed and
9708 processed the project files and found the sources, it creates the source info
9709 file. If the source info file already exists and can be read successfully,
9710 then the Project Manager will get all the needed information about the sources
9711 from the source info file and will not look for them. This reduces the time
9712 to process the project files, especially when looking for sources that take a
9713 long time. If the source info file exists but cannot be parsed successfully,
9714 the Project Manager will attempt to recreate it. If the Project Manager fails
9715 to create the source info file, a message is issued, but gnatmake does not
9716 fail. @command{gnatmake} "trusts" the source info file. This means that
9717 if the source files have changed (addition, deletion, moving to a different
9718 source directory), then the source info file need to be deleted and recreated.
9720 @ifclear vms
9721 @item --create-map-file
9722 When linking an executable, create a map file. The name of the map file
9723 has the same name as the executable with extension ".map".
9725 @item --create-map-file=mapfile
9726 When linking an executable, create a map file. The name of the map file is
9727 "mapfile".
9729 @end ifclear
9731 @item ^-a^/ALL_FILES^
9732 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9733 Consider all files in the make process, even the GNAT internal system
9734 files (for example, the predefined Ada library files), as well as any
9735 locked files. Locked files are files whose ALI file is write-protected.
9736 By default,
9737 @command{gnatmake} does not check these files,
9738 because the assumption is that the GNAT internal files are properly up
9739 to date, and also that any write protected ALI files have been properly
9740 installed. Note that if there is an installation problem, such that one
9741 of these files is not up to date, it will be properly caught by the
9742 binder.
9743 You may have to specify this switch if you are working on GNAT
9744 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9745 in conjunction with @option{^-f^/FORCE_COMPILE^}
9746 if you need to recompile an entire application,
9747 including run-time files, using special configuration pragmas,
9748 such as a @code{Normalize_Scalars} pragma.
9750 By default
9751 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9752 internal files with
9753 @ifclear vms
9754 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9755 @end ifclear
9756 @ifset vms
9757 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9758 @end ifset
9760 @item ^-b^/ACTIONS=BIND^
9761 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9762 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9763 compilation and binding, but no link.
9764 Can be combined with @option{^-l^/ACTIONS=LINK^}
9765 to do binding and linking. When not combined with
9766 @option{^-c^/ACTIONS=COMPILE^}
9767 all the units in the closure of the main program must have been previously
9768 compiled and must be up to date. The root unit specified by @var{file_name}
9769 may be given without extension, with the source extension or, if no GNAT
9770 Project File is specified, with the ALI file extension.
9772 @item ^-c^/ACTIONS=COMPILE^
9773 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9774 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9775 is also specified. Do not perform linking, except if both
9776 @option{^-b^/ACTIONS=BIND^} and
9777 @option{^-l^/ACTIONS=LINK^} are also specified.
9778 If the root unit specified by @var{file_name} is not a main unit, this is the
9779 default. Otherwise @command{gnatmake} will attempt binding and linking
9780 unless all objects are up to date and the executable is more recent than
9781 the objects.
9783 @item ^-C^/MAPPING^
9784 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9785 Use a temporary mapping file. A mapping file is a way to communicate
9786 to the compiler two mappings: from unit names to file names (without
9787 any directory information) and from file names to path names (with
9788 full directory information). A mapping file can make the compiler's
9789 file searches faster, especially if there are many source directories,
9790 or the sources are read over a slow network connection. If
9791 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9792 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9793 is initially populated based on the project file. If
9794 @option{^-C^/MAPPING^} is used without
9795 @option{^-P^/PROJECT_FILE^},
9796 the mapping file is initially empty. Each invocation of the compiler
9797 will add any newly accessed sources to the mapping file.
9799 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9800 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9801 Use a specific mapping file. The file, specified as a path name (absolute or
9802 relative) by this switch, should already exist, otherwise the switch is
9803 ineffective. The specified mapping file will be communicated to the compiler.
9804 This switch is not compatible with a project file
9805 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9806 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9808 @item ^-d^/DISPLAY_PROGRESS^
9809 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9810 Display progress for each source, up to date or not, as a single line
9812 @smallexample
9813 completed x out of y (zz%)
9814 @end smallexample
9816 If the file needs to be compiled this is displayed after the invocation of
9817 the compiler. These lines are displayed even in quiet output mode.
9819 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9820 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9821 Put all object files and ALI file in directory @var{dir}.
9822 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9823 and ALI files go in the current working directory.
9825 This switch cannot be used when using a project file.
9827 @item -eInnn
9828 @cindex @option{-eI} (@command{gnatmake})
9829 Indicates that the main source is a multi-unit source and the rank of the unit
9830 in the source file is nnn. nnn needs to be a positive number and a valid
9831 index in the source. This switch cannot be used when @command{gnatmake} is
9832 invoked for several mains.
9834 @ifclear vms
9835 @item -eL
9836 @cindex @option{-eL} (@command{gnatmake})
9837 @cindex symbolic links
9838 Follow all symbolic links when processing project files.
9839 This should be used if your project uses symbolic links for files or
9840 directories, but is not needed in other cases.
9842 @cindex naming scheme
9843 This also assumes that no directory matches the naming scheme for files (for
9844 instance that you do not have a directory called "sources.ads" when using the
9845 default GNAT naming scheme).
9847 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9848 save a lot of system calls (several per source file and object file), which
9849 can result in a significant speed up to load and manipulate a project file,
9850 especially when using source files from a remote system.
9852 @end ifclear
9854 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9855 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9856 Output the commands for the compiler, the binder and the linker
9857 on ^standard output^SYS$OUTPUT^,
9858 instead of ^standard error^SYS$ERROR^.
9860 @item ^-f^/FORCE_COMPILE^
9861 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9862 Force recompilations. Recompile all sources, even though some object
9863 files may be up to date, but don't recompile predefined or GNAT internal
9864 files or locked files (files with a write-protected ALI file),
9865 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9867 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9868 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9869 When using project files, if some errors or warnings are detected during
9870 parsing and verbose mode is not in effect (no use of switch
9871 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9872 file, rather than its simple file name.
9874 @item ^-g^/DEBUG^
9875 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9876 Enable debugging. This switch is simply passed to the compiler and to the
9877 linker.
9879 @item ^-i^/IN_PLACE^
9880 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9881 In normal mode, @command{gnatmake} compiles all object files and ALI files
9882 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9883 then instead object files and ALI files that already exist are overwritten
9884 in place. This means that once a large project is organized into separate
9885 directories in the desired manner, then @command{gnatmake} will automatically
9886 maintain and update this organization. If no ALI files are found on the
9887 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9888 the new object and ALI files are created in the
9889 directory containing the source being compiled. If another organization
9890 is desired, where objects and sources are kept in different directories,
9891 a useful technique is to create dummy ALI files in the desired directories.
9892 When detecting such a dummy file, @command{gnatmake} will be forced to
9893 recompile the corresponding source file, and it will be put the resulting
9894 object and ALI files in the directory where it found the dummy file.
9896 @item ^-j^/PROCESSES=^@var{n}
9897 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9898 @cindex Parallel make
9899 Use @var{n} processes to carry out the (re)compilations. On a
9900 multiprocessor machine compilations will occur in parallel. In the
9901 event of compilation errors, messages from various compilations might
9902 get interspersed (but @command{gnatmake} will give you the full ordered
9903 list of failing compiles at the end). If this is problematic, rerun
9904 the make process with n set to 1 to get a clean list of messages.
9906 @item ^-k^/CONTINUE_ON_ERROR^
9907 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9908 Keep going. Continue as much as possible after a compilation error. To
9909 ease the programmer's task in case of compilation errors, the list of
9910 sources for which the compile fails is given when @command{gnatmake}
9911 terminates.
9913 If @command{gnatmake} is invoked with several @file{file_names} and with this
9914 switch, if there are compilation errors when building an executable,
9915 @command{gnatmake} will not attempt to build the following executables.
9917 @item ^-l^/ACTIONS=LINK^
9918 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9919 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9920 and linking. Linking will not be performed if combined with
9921 @option{^-c^/ACTIONS=COMPILE^}
9922 but not with @option{^-b^/ACTIONS=BIND^}.
9923 When not combined with @option{^-b^/ACTIONS=BIND^}
9924 all the units in the closure of the main program must have been previously
9925 compiled and must be up to date, and the main program needs to have been bound.
9926 The root unit specified by @var{file_name}
9927 may be given without extension, with the source extension or, if no GNAT
9928 Project File is specified, with the ALI file extension.
9930 @item ^-m^/MINIMAL_RECOMPILATION^
9931 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9932 Specify that the minimum necessary amount of recompilations
9933 be performed. In this mode @command{gnatmake} ignores time
9934 stamp differences when the only
9935 modifications to a source file consist in adding/removing comments,
9936 empty lines, spaces or tabs. This means that if you have changed the
9937 comments in a source file or have simply reformatted it, using this
9938 switch will tell @command{gnatmake} not to recompile files that depend on it
9939 (provided other sources on which these files depend have undergone no
9940 semantic modifications). Note that the debugging information may be
9941 out of date with respect to the sources if the @option{-m} switch causes
9942 a compilation to be switched, so the use of this switch represents a
9943 trade-off between compilation time and accurate debugging information.
9945 @item ^-M^/DEPENDENCIES_LIST^
9946 @cindex Dependencies, producing list
9947 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9948 Check if all objects are up to date. If they are, output the object
9949 dependences to @file{stdout} in a form that can be directly exploited in
9950 a @file{Makefile}. By default, each source file is prefixed with its
9951 (relative or absolute) directory name. This name is whatever you
9952 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9953 and @option{^-I^/SEARCH^} switches. If you use
9954 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9955 @option{^-q^/QUIET^}
9956 (see below), only the source file names,
9957 without relative paths, are output. If you just specify the
9958 @option{^-M^/DEPENDENCIES_LIST^}
9959 switch, dependencies of the GNAT internal system files are omitted. This
9960 is typically what you want. If you also specify
9961 the @option{^-a^/ALL_FILES^} switch,
9962 dependencies of the GNAT internal files are also listed. Note that
9963 dependencies of the objects in external Ada libraries (see switch
9964 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9965 are never reported.
9967 @item ^-n^/DO_OBJECT_CHECK^
9968 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9969 Don't compile, bind, or link. Checks if all objects are up to date.
9970 If they are not, the full name of the first file that needs to be
9971 recompiled is printed.
9972 Repeated use of this option, followed by compiling the indicated source
9973 file, will eventually result in recompiling all required units.
9975 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9976 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9977 Output executable name. The name of the final executable program will be
9978 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9979 name for the executable will be the name of the input file in appropriate form
9980 for an executable file on the host system.
9982 This switch cannot be used when invoking @command{gnatmake} with several
9983 @file{file_names}.
9985 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9986 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9987 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9988 automatically missing object directories, library directories and exec
9989 directories.
9991 @item ^-P^/PROJECT_FILE=^@var{project}
9992 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9993 Use project file @var{project}. Only one such switch can be used.
9994 @xref{gnatmake and Project Files}.
9996 @item ^-q^/QUIET^
9997 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9998 Quiet. When this flag is not set, the commands carried out by
9999 @command{gnatmake} are displayed.
10001 @item ^-s^/SWITCH_CHECK/^
10002 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
10003 Recompile if compiler switches have changed since last compilation.
10004 All compiler switches but -I and -o are taken into account in the
10005 following way:
10006 orders between different ``first letter'' switches are ignored, but
10007 orders between same switches are taken into account. For example,
10008 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
10009 is equivalent to @option{-O -g}.
10011 This switch is recommended when Integrated Preprocessing is used.
10013 @item ^-u^/UNIQUE^
10014 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
10015 Unique. Recompile at most the main files. It implies -c. Combined with
10016 -f, it is equivalent to calling the compiler directly. Note that using
10017 ^-u^/UNIQUE^ with a project file and no main has a special meaning
10018 (@pxref{Project Files and Main Subprograms}).
10020 @item ^-U^/ALL_PROJECTS^
10021 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
10022 When used without a project file or with one or several mains on the command
10023 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
10024 on the command line, all sources of all project files are checked and compiled
10025 if not up to date, and libraries are rebuilt, if necessary.
10027 @item ^-v^/REASONS^
10028 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
10029 Verbose. Display the reason for all recompilations @command{gnatmake}
10030 decides are necessary, with the highest verbosity level.
10032 @item ^-vl^/LOW_VERBOSITY^
10033 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
10034 Verbosity level Low. Display fewer lines than in verbosity Medium.
10036 @item ^-vm^/MEDIUM_VERBOSITY^
10037 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
10038 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
10040 @item ^-vh^/HIGH_VERBOSITY^
10041 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
10042 Verbosity level High. Equivalent to ^-v^/REASONS^.
10044 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
10045 Indicate the verbosity of the parsing of GNAT project files.
10046 @xref{Switches Related to Project Files}.
10048 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
10049 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
10050 Indicate that sources that are not part of any Project File may be compiled.
10051 Normally, when using Project Files, only sources that are part of a Project
10052 File may be compile. When this switch is used, a source outside of all Project
10053 Files may be compiled. The ALI file and the object file will be put in the
10054 object directory of the main Project. The compilation switches used will only
10055 be those specified on the command line. Even when
10056 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
10057 command line need to be sources of a project file.
10059 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
10060 Indicate that external variable @var{name} has the value @var{value}.
10061 The Project Manager will use this value for occurrences of
10062 @code{external(name)} when parsing the project file.
10063 @xref{Switches Related to Project Files}.
10065 @item ^-z^/NOMAIN^
10066 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
10067 No main subprogram. Bind and link the program even if the unit name
10068 given on the command line is a package name. The resulting executable
10069 will execute the elaboration routines of the package and its closure,
10070 then the finalization routines.
10072 @end table
10074 @table @asis
10075 @item @command{gcc} @asis{switches}
10076 @ifclear vms
10077 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
10078 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
10079 @end ifclear
10080 @ifset vms
10081 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
10082 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
10083 automatically treated as a compiler switch, and passed on to all
10084 compilations that are carried out.
10085 @end ifset
10086 @end table
10088 @noindent
10089 Source and library search path switches:
10091 @table @option
10092 @c !sort!
10093 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
10094 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
10095 When looking for source files also look in directory @var{dir}.
10096 The order in which source files search is undertaken is
10097 described in @ref{Search Paths and the Run-Time Library (RTL)}.
10099 @item ^-aL^/SKIP_MISSING=^@var{dir}
10100 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
10101 Consider @var{dir} as being an externally provided Ada library.
10102 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
10103 files have been located in directory @var{dir}. This allows you to have
10104 missing bodies for the units in @var{dir} and to ignore out of date bodies
10105 for the same units. You still need to specify
10106 the location of the specs for these units by using the switches
10107 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
10108 or @option{^-I^/SEARCH=^@var{dir}}.
10109 Note: this switch is provided for compatibility with previous versions
10110 of @command{gnatmake}. The easier method of causing standard libraries
10111 to be excluded from consideration is to write-protect the corresponding
10112 ALI files.
10114 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
10115 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
10116 When searching for library and object files, look in directory
10117 @var{dir}. The order in which library files are searched is described in
10118 @ref{Search Paths for gnatbind}.
10120 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
10121 @cindex Search paths, for @command{gnatmake}
10122 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
10123 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
10124 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10126 @item ^-I^/SEARCH=^@var{dir}
10127 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
10128 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
10129 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10131 @item ^-I-^/NOCURRENT_DIRECTORY^
10132 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
10133 @cindex Source files, suppressing search
10134 Do not look for source files in the directory containing the source
10135 file named in the command line.
10136 Do not look for ALI or object files in the directory
10137 where @command{gnatmake} was invoked.
10139 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
10140 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
10141 @cindex Linker libraries
10142 Add directory @var{dir} to the list of directories in which the linker
10143 will search for libraries. This is equivalent to
10144 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
10145 @ifclear vms
10146 Furthermore, under Windows, the sources pointed to by the libraries path
10147 set in the registry are not searched for.
10148 @end ifclear
10150 @item -nostdinc
10151 @cindex @option{-nostdinc} (@command{gnatmake})
10152 Do not look for source files in the system default directory.
10154 @item -nostdlib
10155 @cindex @option{-nostdlib} (@command{gnatmake})
10156 Do not look for library files in the system default directory.
10158 @item --RTS=@var{rts-path}
10159 @cindex @option{--RTS} (@command{gnatmake})
10160 Specifies the default location of the runtime library. GNAT looks for the
10161 runtime
10162 in the following directories, and stops as soon as a valid runtime is found
10163 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
10164 @file{ada_object_path} present):
10166 @itemize @bullet
10167 @item <current directory>/$rts_path
10169 @item <default-search-dir>/$rts_path
10171 @item <default-search-dir>/rts-$rts_path
10172 @end itemize
10174 @noindent
10175 The selected path is handled like a normal RTS path.
10177 @end table
10179 @node Mode Switches for gnatmake
10180 @section Mode Switches for @command{gnatmake}
10182 @noindent
10183 The mode switches (referred to as @code{mode_switches}) allow the
10184 inclusion of switches that are to be passed to the compiler itself, the
10185 binder or the linker. The effect of a mode switch is to cause all
10186 subsequent switches up to the end of the switch list, or up to the next
10187 mode switch, to be interpreted as switches to be passed on to the
10188 designated component of GNAT.
10190 @table @option
10191 @c !sort!
10192 @item -cargs @var{switches}
10193 @cindex @option{-cargs} (@command{gnatmake})
10194 Compiler switches. Here @var{switches} is a list of switches
10195 that are valid switches for @command{gcc}. They will be passed on to
10196 all compile steps performed by @command{gnatmake}.
10198 @item -bargs @var{switches}
10199 @cindex @option{-bargs} (@command{gnatmake})
10200 Binder switches. Here @var{switches} is a list of switches
10201 that are valid switches for @code{gnatbind}. They will be passed on to
10202 all bind steps performed by @command{gnatmake}.
10204 @item -largs @var{switches}
10205 @cindex @option{-largs} (@command{gnatmake})
10206 Linker switches. Here @var{switches} is a list of switches
10207 that are valid switches for @command{gnatlink}. They will be passed on to
10208 all link steps performed by @command{gnatmake}.
10210 @item -margs @var{switches}
10211 @cindex @option{-margs} (@command{gnatmake})
10212 Make switches. The switches are directly interpreted by @command{gnatmake},
10213 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10214 or @option{-largs}.
10215 @end table
10217 @node Notes on the Command Line
10218 @section Notes on the Command Line
10220 @noindent
10221 This section contains some additional useful notes on the operation
10222 of the @command{gnatmake} command.
10224 @itemize @bullet
10225 @item
10226 @cindex Recompilation, by @command{gnatmake}
10227 If @command{gnatmake} finds no ALI files, it recompiles the main program
10228 and all other units required by the main program.
10229 This means that @command{gnatmake}
10230 can be used for the initial compile, as well as during subsequent steps of
10231 the development cycle.
10233 @item
10234 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10235 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10236 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10237 warning.
10239 @item
10240 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10241 is used to specify both source and
10242 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10243 instead if you just want to specify
10244 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10245 if you want to specify library paths
10246 only.
10248 @item
10249 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10250 This may conveniently be used to exclude standard libraries from
10251 consideration and in particular it means that the use of the
10252 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10253 unless @option{^-a^/ALL_FILES^} is also specified.
10255 @item
10256 @command{gnatmake} has been designed to make the use of Ada libraries
10257 particularly convenient. Assume you have an Ada library organized
10258 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10259 of your Ada compilation units,
10260 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10261 specs of these units, but no bodies. Then to compile a unit
10262 stored in @code{main.adb}, which uses this Ada library you would just type
10264 @smallexample
10265 @ifclear vms
10266 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
10267 @end ifclear
10268 @ifset vms
10269 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10270            /SKIP_MISSING=@i{[OBJ_DIR]} main
10271 @end ifset
10272 @end smallexample
10274 @item
10275 Using @command{gnatmake} along with the
10276 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10277 switch provides a mechanism for avoiding unnecessary recompilations. Using
10278 this switch,
10279 you can update the comments/format of your
10280 source files without having to recompile everything. Note, however, that
10281 adding or deleting lines in a source files may render its debugging
10282 info obsolete. If the file in question is a spec, the impact is rather
10283 limited, as that debugging info will only be useful during the
10284 elaboration phase of your program. For bodies the impact can be more
10285 significant. In all events, your debugger will warn you if a source file
10286 is more recent than the corresponding object, and alert you to the fact
10287 that the debugging information may be out of date.
10288 @end itemize
10290 @node How gnatmake Works
10291 @section How @command{gnatmake} Works
10293 @noindent
10294 Generally @command{gnatmake} automatically performs all necessary
10295 recompilations and you don't need to worry about how it works. However,
10296 it may be useful to have some basic understanding of the @command{gnatmake}
10297 approach and in particular to understand how it uses the results of
10298 previous compilations without incorrectly depending on them.
10300 First a definition: an object file is considered @dfn{up to date} if the
10301 corresponding ALI file exists and if all the source files listed in the
10302 dependency section of this ALI file have time stamps matching those in
10303 the ALI file. This means that neither the source file itself nor any
10304 files that it depends on have been modified, and hence there is no need
10305 to recompile this file.
10307 @command{gnatmake} works by first checking if the specified main unit is up
10308 to date. If so, no compilations are required for the main unit. If not,
10309 @command{gnatmake} compiles the main program to build a new ALI file that
10310 reflects the latest sources. Then the ALI file of the main unit is
10311 examined to find all the source files on which the main program depends,
10312 and @command{gnatmake} recursively applies the above procedure on all these
10313 files.
10315 This process ensures that @command{gnatmake} only trusts the dependencies
10316 in an existing ALI file if they are known to be correct. Otherwise it
10317 always recompiles to determine a new, guaranteed accurate set of
10318 dependencies. As a result the program is compiled ``upside down'' from what may
10319 be more familiar as the required order of compilation in some other Ada
10320 systems. In particular, clients are compiled before the units on which
10321 they depend. The ability of GNAT to compile in any order is critical in
10322 allowing an order of compilation to be chosen that guarantees that
10323 @command{gnatmake} will recompute a correct set of new dependencies if
10324 necessary.
10326 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10327 imported by several of the executables, it will be recompiled at most once.
10329 Note: when using non-standard naming conventions
10330 (@pxref{Using Other File Names}), changing through a configuration pragmas
10331 file the version of a source and invoking @command{gnatmake} to recompile may
10332 have no effect, if the previous version of the source is still accessible
10333 by @command{gnatmake}. It may be necessary to use the switch
10334 ^-f^/FORCE_COMPILE^.
10336 @node Examples of gnatmake Usage
10337 @section Examples of @command{gnatmake} Usage
10339 @table @code
10340 @item gnatmake hello.adb
10341 Compile all files necessary to bind and link the main program
10342 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10343 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10345 @item gnatmake main1 main2 main3
10346 Compile all files necessary to bind and link the main programs
10347 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10348 (containing unit @code{Main2}) and @file{main3.adb}
10349 (containing unit @code{Main3}) and bind and link the resulting object files
10350 to generate three executable files @file{^main1^MAIN1.EXE^},
10351 @file{^main2^MAIN2.EXE^}
10352 and @file{^main3^MAIN3.EXE^}.
10354 @ifclear vms
10355 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10356 @end ifclear
10358 @ifset vms
10359 @item gnatmake Main_Unit /QUIET
10360 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10361 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10362 @end ifset
10363 Compile all files necessary to bind and link the main program unit
10364 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10365 be done with optimization level 2 and the order of elaboration will be
10366 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10367 displaying commands it is executing.
10368 @end table
10370 @c *************************
10371 @node Improving Performance
10372 @chapter Improving Performance
10373 @cindex Improving performance
10375 @noindent
10376 This chapter presents several topics related to program performance.
10377 It first describes some of the tradeoffs that need to be considered
10378 and some of the techniques for making your program run faster.
10379 It then documents the @command{gnatelim} tool and unused subprogram/data
10380 elimination feature, which can reduce the size of program executables.
10382 @ifnottex
10383 @menu
10384 * Performance Considerations::
10385 * Text_IO Suggestions::
10386 * Reducing Size of Ada Executables with gnatelim::
10387 * Reducing Size of Executables with unused subprogram/data elimination::
10388 @end menu
10389 @end ifnottex
10391 @c *****************************
10392 @node Performance Considerations
10393 @section Performance Considerations
10395 @noindent
10396 The GNAT system provides a number of options that allow a trade-off
10397 between
10399 @itemize @bullet
10400 @item
10401 performance of the generated code
10403 @item
10404 speed of compilation
10406 @item
10407 minimization of dependences and recompilation
10409 @item
10410 the degree of run-time checking.
10411 @end itemize
10413 @noindent
10414 The defaults (if no options are selected) aim at improving the speed
10415 of compilation and minimizing dependences, at the expense of performance
10416 of the generated code:
10418 @itemize @bullet
10419 @item
10420 no optimization
10422 @item
10423 no inlining of subprogram calls
10425 @item
10426 all run-time checks enabled except overflow and elaboration checks
10427 @end itemize
10429 @noindent
10430 These options are suitable for most program development purposes. This
10431 chapter describes how you can modify these choices, and also provides
10432 some guidelines on debugging optimized code.
10434 @menu
10435 * Controlling Run-Time Checks::
10436 * Use of Restrictions::
10437 * Optimization Levels::
10438 * Debugging Optimized Code::
10439 * Inlining of Subprograms::
10440 * Vectorization of loops::
10441 * Other Optimization Switches::
10442 * Optimization and Strict Aliasing::
10444 @ifset vms
10445 * Coverage Analysis::
10446 @end ifset
10447 @end menu
10449 @node Controlling Run-Time Checks
10450 @subsection Controlling Run-Time Checks
10452 @noindent
10453 By default, GNAT generates all run-time checks, except integer overflow
10454 checks, stack overflow checks, and checks for access before elaboration on
10455 subprogram calls. The latter are not required in default mode, because all
10456 necessary checking is done at compile time.
10457 @cindex @option{-gnatp} (@command{gcc})
10458 @cindex @option{-gnato} (@command{gcc})
10459 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10460 be modified. @xref{Run-Time Checks}.
10462 Our experience is that the default is suitable for most development
10463 purposes.
10465 We treat integer overflow specially because these
10466 are quite expensive and in our experience are not as important as other
10467 run-time checks in the development process. Note that division by zero
10468 is not considered an overflow check, and divide by zero checks are
10469 generated where required by default.
10471 Elaboration checks are off by default, and also not needed by default, since
10472 GNAT uses a static elaboration analysis approach that avoids the need for
10473 run-time checking. This manual contains a full chapter discussing the issue
10474 of elaboration checks, and if the default is not satisfactory for your use,
10475 you should read this chapter.
10477 For validity checks, the minimal checks required by the Ada Reference
10478 Manual (for case statements and assignments to array elements) are on
10479 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10480 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10481 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10482 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10483 are also suppressed entirely if @option{-gnatp} is used.
10485 @cindex Overflow checks
10486 @cindex Checks, overflow
10487 @findex Suppress
10488 @findex Unsuppress
10489 @cindex pragma Suppress
10490 @cindex pragma Unsuppress
10491 Note that the setting of the switches controls the default setting of
10492 the checks. They may be modified using either @code{pragma Suppress} (to
10493 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10494 checks) in the program source.
10496 @node Use of Restrictions
10497 @subsection Use of Restrictions
10499 @noindent
10500 The use of pragma Restrictions allows you to control which features are
10501 permitted in your program. Apart from the obvious point that if you avoid
10502 relatively expensive features like finalization (enforceable by the use
10503 of pragma Restrictions (No_Finalization), the use of this pragma does not
10504 affect the generated code in most cases.
10506 One notable exception to this rule is that the possibility of task abort
10507 results in some distributed overhead, particularly if finalization or
10508 exception handlers are used. The reason is that certain sections of code
10509 have to be marked as non-abortable.
10511 If you use neither the @code{abort} statement, nor asynchronous transfer
10512 of control (@code{select @dots{} then abort}), then this distributed overhead
10513 is removed, which may have a general positive effect in improving
10514 overall performance.  Especially code involving frequent use of tasking
10515 constructs and controlled types will show much improved performance.
10516 The relevant restrictions pragmas are
10518 @smallexample @c ada
10519    pragma Restrictions (No_Abort_Statements);
10520    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10521 @end smallexample
10523 @noindent
10524 It is recommended that these restriction pragmas be used if possible. Note
10525 that this also means that you can write code without worrying about the
10526 possibility of an immediate abort at any point.
10528 @node Optimization Levels
10529 @subsection Optimization Levels
10530 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10532 @noindent
10533 Without any optimization ^option,^qualifier,^
10534 the compiler's goal is to reduce the cost of
10535 compilation and to make debugging produce the expected results.
10536 Statements are independent: if you stop the program with a breakpoint between
10537 statements, you can then assign a new value to any variable or change
10538 the program counter to any other statement in the subprogram and get exactly
10539 the results you would expect from the source code.
10541 Turning on optimization makes the compiler attempt to improve the
10542 performance and/or code size at the expense of compilation time and
10543 possibly the ability to debug the program.
10545 If you use multiple
10546 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10547 the last such option is the one that is effective.
10549 @noindent
10550 The default is optimization off. This results in the fastest compile
10551 times, but GNAT makes absolutely no attempt to optimize, and the
10552 generated programs are considerably larger and slower than when
10553 optimization is enabled. You can use the
10554 @ifclear vms
10555 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10556 @option{-O2}, @option{-O3}, and @option{-Os})
10557 @end ifclear
10558 @ifset vms
10559 @code{OPTIMIZE} qualifier
10560 @end ifset
10561 to @command{gcc} to control the optimization level:
10563 @table @option
10564 @item ^-O0^/OPTIMIZE=NONE^
10565 No optimization (the default);
10566 generates unoptimized code but has
10567 the fastest compilation time.
10569 Note that many other compilers do fairly extensive optimization
10570 even if ``no optimization'' is specified. With gcc, it is
10571 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10572 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10573 really does mean no optimization at all. This difference between
10574 gcc and other compilers should be kept in mind when doing
10575 performance comparisons.
10577 @item ^-O1^/OPTIMIZE=SOME^
10578 Moderate optimization;
10579 optimizes reasonably well but does not
10580 degrade compilation time significantly.
10582 @item ^-O2^/OPTIMIZE=ALL^
10583 @ifset vms
10584 @itemx /OPTIMIZE=DEVELOPMENT
10585 @end ifset
10586 Full optimization;
10587 generates highly optimized code and has
10588 the slowest compilation time.
10590 @item ^-O3^/OPTIMIZE=INLINING^
10591 Full optimization as in @option{-O2};
10592 also uses more aggressive automatic inlining of subprograms within a unit
10593 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10595 @item ^-Os^/OPTIMIZE=SPACE^
10596 Optimize space usage (code and data) of resulting program.
10597 @end table
10599 @noindent
10600 Higher optimization levels perform more global transformations on the
10601 program and apply more expensive analysis algorithms in order to generate
10602 faster and more compact code. The price in compilation time, and the
10603 resulting improvement in execution time,
10604 both depend on the particular application and the hardware environment.
10605 You should experiment to find the best level for your application.
10607 Since the precise set of optimizations done at each level will vary from
10608 release to release (and sometime from target to target), it is best to think
10609 of the optimization settings in general terms.
10610 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10611 the GNU Compiler Collection (GCC)}, for details about
10612 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10613 individually enable or disable specific optimizations.
10615 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10616 been tested extensively at all optimization levels. There are some bugs
10617 which appear only with optimization turned on, but there have also been
10618 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10619 level of optimization does not improve the reliability of the code
10620 generator, which in practice is highly reliable at all optimization
10621 levels.
10623 Note regarding the use of @option{-O3}: The use of this optimization level
10624 is generally discouraged with GNAT, since it often results in larger
10625 executables which may run more slowly. See further discussion of this point
10626 in @ref{Inlining of Subprograms}.
10628 @node Debugging Optimized Code
10629 @subsection Debugging Optimized Code
10630 @cindex Debugging optimized code
10631 @cindex Optimization and debugging
10633 @noindent
10634 Although it is possible to do a reasonable amount of debugging at
10635 @ifclear vms
10636 nonzero optimization levels,
10637 the higher the level the more likely that
10638 @end ifclear
10639 @ifset vms
10640 @option{/OPTIMIZE} settings other than @code{NONE},
10641 such settings will make it more likely that
10642 @end ifset
10643 source-level constructs will have been eliminated by optimization.
10644 For example, if a loop is strength-reduced, the loop
10645 control variable may be completely eliminated and thus cannot be
10646 displayed in the debugger.
10647 This can only happen at @option{-O2} or @option{-O3}.
10648 Explicit temporary variables that you code might be eliminated at
10649 ^level^setting^ @option{-O1} or higher.
10651 The use of the @option{^-g^/DEBUG^} switch,
10652 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10653 which is needed for source-level debugging,
10654 affects the size of the program executable on disk,
10655 and indeed the debugging information can be quite large.
10656 However, it has no effect on the generated code (and thus does not
10657 degrade performance)
10659 Since the compiler generates debugging tables for a compilation unit before
10660 it performs optimizations, the optimizing transformations may invalidate some
10661 of the debugging data.  You therefore need to anticipate certain
10662 anomalous situations that may arise while debugging optimized code.
10663 These are the most common cases:
10665 @enumerate
10666 @item
10667 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10668 commands show
10669 the PC bouncing back and forth in the code.  This may result from any of
10670 the following optimizations:
10672 @itemize @bullet
10673 @item
10674 @i{Common subexpression elimination:} using a single instance of code for a
10675 quantity that the source computes several times.  As a result you
10676 may not be able to stop on what looks like a statement.
10678 @item
10679 @i{Invariant code motion:} moving an expression that does not change within a
10680 loop, to the beginning of the loop.
10682 @item
10683 @i{Instruction scheduling:} moving instructions so as to
10684 overlap loads and stores (typically) with other code, or in
10685 general to move computations of values closer to their uses. Often
10686 this causes you to pass an assignment statement without the assignment
10687 happening and then later bounce back to the statement when the
10688 value is actually needed.  Placing a breakpoint on a line of code
10689 and then stepping over it may, therefore, not always cause all the
10690 expected side-effects.
10691 @end itemize
10693 @item
10694 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10695 two identical pieces of code are merged and the program counter suddenly
10696 jumps to a statement that is not supposed to be executed, simply because
10697 it (and the code following) translates to the same thing as the code
10698 that @emph{was} supposed to be executed.  This effect is typically seen in
10699 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10700 a @code{break} in a C @code{^switch^switch^} statement.
10702 @item
10703 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10704 There are various reasons for this effect:
10706 @itemize @bullet
10707 @item
10708 In a subprogram prologue, a parameter may not yet have been moved to its
10709 ``home''.
10711 @item
10712 A variable may be dead, and its register re-used.  This is
10713 probably the most common cause.
10715 @item
10716 As mentioned above, the assignment of a value to a variable may
10717 have been moved.
10719 @item
10720 A variable may be eliminated entirely by value propagation or
10721 other means.  In this case, GCC may incorrectly generate debugging
10722 information for the variable
10723 @end itemize
10725 @noindent
10726 In general, when an unexpected value appears for a local variable or parameter
10727 you should first ascertain if that value was actually computed by
10728 your program, as opposed to being incorrectly reported by the debugger.
10729 Record fields or
10730 array elements in an object designated by an access value
10731 are generally less of a problem, once you have ascertained that the access
10732 value is sensible.
10733 Typically, this means checking variables in the preceding code and in the
10734 calling subprogram to verify that the value observed is explainable from other
10735 values (one must apply the procedure recursively to those
10736 other values); or re-running the code and stopping a little earlier
10737 (perhaps before the call) and stepping to better see how the variable obtained
10738 the value in question; or continuing to step @emph{from} the point of the
10739 strange value to see if code motion had simply moved the variable's
10740 assignments later.
10741 @end enumerate
10743 @noindent
10744 In light of such anomalies, a recommended technique is to use @option{-O0}
10745 early in the software development cycle, when extensive debugging capabilities
10746 are most needed, and then move to @option{-O1} and later @option{-O2} as
10747 the debugger becomes less critical.
10748 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10749 a release management issue.
10750 @ifclear vms
10751 Note that if you use @option{-g} you can then use the @command{strip} program
10752 on the resulting executable,
10753 which removes both debugging information and global symbols.
10754 @end ifclear
10756 @node Inlining of Subprograms
10757 @subsection Inlining of Subprograms
10759 @noindent
10760 A call to a subprogram in the current unit is inlined if all the
10761 following conditions are met:
10763 @itemize @bullet
10764 @item
10765 The optimization level is at least @option{-O1}.
10767 @item
10768 The called subprogram is suitable for inlining: It must be small enough
10769 and not contain something that @command{gcc} cannot support in inlined
10770 subprograms.
10772 @item
10773 @cindex pragma Inline
10774 @findex Inline
10775 Any one of the following applies: @code{pragma Inline} is applied to the
10776 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10777 subprogram is local to the unit and called once from within it; the
10778 subprogram is small and optimization level @option{-O2} is specified;
10779 optimization level @option{-O3} is specified.
10780 @end itemize
10782 @noindent
10783 Calls to subprograms in @code{with}'ed units are normally not inlined.
10784 To achieve actual inlining (that is, replacement of the call by the code
10785 in the body of the subprogram), the following conditions must all be true:
10787 @itemize @bullet
10788 @item
10789 The optimization level is at least @option{-O1}.
10791 @item
10792 The called subprogram is suitable for inlining: It must be small enough
10793 and not contain something that @command{gcc} cannot support in inlined
10794 subprograms.
10796 @item
10797 The call appears in a body (not in a package spec).
10799 @item
10800 There is a @code{pragma Inline} for the subprogram.
10802 @item
10803 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10804 @end itemize
10806 Even if all these conditions are met, it may not be possible for
10807 the compiler to inline the call, due to the length of the body,
10808 or features in the body that make it impossible for the compiler
10809 to do the inlining.
10811 Note that specifying the @option{-gnatn} switch causes additional
10812 compilation dependencies. Consider the following:
10814 @smallexample @c ada
10815 @cartouche
10816 package R is
10817    procedure Q;
10818    pragma Inline (Q);
10819 end R;
10820 package body R is
10821    @dots{}
10822 end R;
10824 with R;
10825 procedure Main is
10826 begin
10827    @dots{}
10828    R.Q;
10829 end Main;
10830 @end cartouche
10831 @end smallexample
10833 @noindent
10834 With the default behavior (no @option{-gnatn} switch specified), the
10835 compilation of the @code{Main} procedure depends only on its own source,
10836 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10837 means that editing the body of @code{R} does not require recompiling
10838 @code{Main}.
10840 On the other hand, the call @code{R.Q} is not inlined under these
10841 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10842 is compiled, the call will be inlined if the body of @code{Q} is small
10843 enough, but now @code{Main} depends on the body of @code{R} in
10844 @file{r.adb} as well as on the spec. This means that if this body is edited,
10845 the main program must be recompiled. Note that this extra dependency
10846 occurs whether or not the call is in fact inlined by @command{gcc}.
10848 The use of front end inlining with @option{-gnatN} generates similar
10849 additional dependencies.
10851 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10852 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10853 can be used to prevent
10854 all inlining. This switch overrides all other conditions and ensures
10855 that no inlining occurs. The extra dependences resulting from
10856 @option{-gnatn} will still be active, even if
10857 this switch is used to suppress the resulting inlining actions.
10859 @cindex @option{-fno-inline-functions} (@command{gcc})
10860 Note: The @option{-fno-inline-functions} switch can be used to prevent
10861 automatic inlining of subprograms if @option{-O3} is used.
10863 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10864 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10865 automatic inlining of small subprograms if @option{-O2} is used.
10867 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10868 Note: The @option{-fno-inline-functions-called-once} switch
10869 can be used to prevent inlining of subprograms local to the unit
10870 and called once from within it if @option{-O1} is used.
10872 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10873 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10874 specified in lieu of it, @option{-gnatn} being translated into one of them
10875 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10876 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10877 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10878 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10879 full inlining across modules. If you have used pragma @code{Inline} in appropriate cases, then it is usually much better to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which has the additional
10880 effect of inlining subprograms you did not think should be inlined. We have
10881 found that the use of @option{-O3} may slow down the compilation and increase
10882 the code size by performing excessive inlining, leading to increased
10883 instruction cache pressure from the increased code size and thus minor
10884 performance improvements. So the bottom line here is that you should not
10885 automatically assume that @option{-O3} is better than @option{-O2}, and
10886 indeed you should use @option{-O3} only if tests show that it actually
10887 improves performance for your program.
10889 @node Vectorization of loops
10890 @subsection Vectorization of loops
10891 @cindex Optimization Switches
10893 You can take advantage of the auto-vectorizer present in the @command{gcc}
10894 back end to vectorize loops with GNAT.  The corresponding command line switch
10895 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10896 and other aggressive optimizations helpful for vectorization also are enabled
10897 by default at this level, using @option{-O3} directly is recommended.
10899 You also need to make sure that the target architecture features a supported
10900 SIMD instruction set.  For example, for the x86 architecture, you should at
10901 least specify @option{-msse2} to get significant vectorization (but you don't
10902 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10903 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10905 The preferred loop form for vectorization is the @code{for} iteration scheme.
10906 Loops with a @code{while} iteration scheme can also be vectorized if they are
10907 very simple, but the vectorizer will quickly give up otherwise.  With either
10908 iteration scheme, the flow of control must be straight, in particular no
10909 @code{exit} statement may appear in the loop body.  The loop may however
10910 contain a single nested loop, if it can be vectorized when considered alone:
10912 @smallexample @c ada
10913 @cartouche
10914    A : array (1..4, 1..4) of Long_Float;
10915    S : array (1..4) of Long_Float;
10917    procedure Sum is
10918    begin
10919       for I in A'Range(1) loop
10920          for J in A'Range(2) loop
10921             S (I) := S (I) + A (I, J);
10922          end loop;
10923       end loop;
10924    end Sum;
10925 @end cartouche
10926 @end smallexample
10928 The vectorizable operations depend on the targeted SIMD instruction set, but
10929 the adding and some of the multiplying operators are generally supported, as
10930 well as the logical operators for modular types.  Note that, in the former
10931 case, enabling overflow checks, for example with @option{-gnato}, totally
10932 disables vectorization.  The other checks are not supposed to have the same
10933 definitive effect, although compiling with @option{-gnatp} might well reveal
10934 cases where some checks do thwart vectorization.
10936 Type conversions may also prevent vectorization if they involve semantics that
10937 are not directly supported by the code generator or the SIMD instruction set.
10938 A typical example is direct conversion from floating-point to integer types.
10939 The solution in this case is to use the following idiom:
10941 @smallexample @c ada
10942    Integer (S'Truncation (F))
10943 @end smallexample
10945 @noindent
10946 if @code{S} is the subtype of floating-point object @code{F}.
10948 In most cases, the vectorizable loops are loops that iterate over arrays.
10949 All kinds of array types are supported, i.e. constrained array types with
10950 static bounds:
10952 @smallexample @c ada
10953    type Array_Type is array (1 .. 4) of Long_Float;
10954 @end smallexample
10956 @noindent
10957 constrained array types with dynamic bounds:
10959 @smallexample @c ada
10960    type Array_Type is array (1 .. Q.N) of Long_Float;
10962    type Array_Type is array (Q.K .. 4) of Long_Float;
10964    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10965 @end smallexample
10967 @noindent
10968 or unconstrained array types:
10970 @smallexample @c ada
10971   type Array_Type is array (Positive range <>) of Long_Float;
10972 @end smallexample
10974 @noindent
10975 The quality of the generated code decreases when the dynamic aspect of the
10976 array type increases, the worst code being generated for unconstrained array
10977 types.  This is so because, the less information the compiler has about the
10978 bounds of the array, the more fallback code it needs to generate in order to
10979 fix things up at run time.
10981 It is possible to specify that a given loop should be subject to vectorization
10982 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10984 @smallexample @c ada
10985   pragma Loop_Optimize (Vector);
10986 @end smallexample
10988 @noindent
10989 placed immediately within the loop will convey the appropriate hint to the
10990 compiler for this loop.
10992 You can obtain information about the vectorization performed by the compiler
10993 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10994 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10995 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10997 @node Other Optimization Switches
10998 @subsection Other Optimization Switches
10999 @cindex Optimization Switches
11001 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
11002 @command{gcc} optimization switches are potentially usable. These switches
11003 have not been extensively tested with GNAT but can generally be expected
11004 to work. Examples of switches in this category are @option{-funroll-loops}
11005 and the various target-specific @option{-m} options (in particular, it has
11006 been observed that @option{-march=xxx} can significantly improve performance
11007 on appropriate machines). For full details of these switches, see
11008 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
11009 the GNU Compiler Collection (GCC)}.
11011 @node Optimization and Strict Aliasing
11012 @subsection Optimization and Strict Aliasing
11013 @cindex Aliasing
11014 @cindex Strict Aliasing
11015 @cindex No_Strict_Aliasing
11017 @noindent
11018 The strong typing capabilities of Ada allow an optimizer to generate
11019 efficient code in situations where other languages would be forced to
11020 make worst case assumptions preventing such optimizations. Consider
11021 the following example:
11023 @smallexample @c ada
11024 @cartouche
11025 procedure R is
11026    type Int1 is new Integer;
11027    type Int2 is new Integer;
11028    type Int1A is access Int1;
11029    type Int2A is access Int2;
11030    Int1V : Int1A;
11031    Int2V : Int2A;
11032    @dots{}
11034 begin
11035    @dots{}
11036    for J in Data'Range loop
11037       if Data (J) = Int1V.all then
11038          Int2V.all := Int2V.all + 1;
11039       end if;
11040    end loop;
11041    @dots{}
11042 end R;
11043 @end cartouche
11044 @end smallexample
11046 @noindent
11047 In this example, since the variable @code{Int1V} can only access objects
11048 of type @code{Int1}, and @code{Int2V} can only access objects of type
11049 @code{Int2}, there is no possibility that the assignment to
11050 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
11051 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
11052 for all iterations of the loop and avoid the extra memory reference
11053 required to dereference it each time through the loop.
11055 This kind of optimization, called strict aliasing analysis, is
11056 triggered by specifying an optimization level of @option{-O2} or
11057 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
11058 when access values are involved.
11060 However, although this optimization is always correct in terms of
11061 the formal semantics of the Ada Reference Manual, difficulties can
11062 arise if features like @code{Unchecked_Conversion} are used to break
11063 the typing system. Consider the following complete program example:
11065 @smallexample @c ada
11066 @cartouche
11067 package p1 is
11068    type int1 is new integer;
11069    type int2 is new integer;
11070    type a1 is access int1;
11071    type a2 is access int2;
11072 end p1;
11074 with p1; use p1;
11075 package p2 is
11076    function to_a2 (Input : a1) return a2;
11077 end p2;
11079 with Unchecked_Conversion;
11080 package body p2 is
11081    function to_a2 (Input : a1) return a2 is
11082       function to_a2u is
11083         new Unchecked_Conversion (a1, a2);
11084    begin
11085       return to_a2u (Input);
11086    end to_a2;
11087 end p2;
11089 with p2; use p2;
11090 with p1; use p1;
11091 with Text_IO; use Text_IO;
11092 procedure m is
11093    v1 : a1 := new int1;
11094    v2 : a2 := to_a2 (v1);
11095 begin
11096    v1.all := 1;
11097    v2.all := 0;
11098    put_line (int1'image (v1.all));
11099 end;
11100 @end cartouche
11101 @end smallexample
11103 @noindent
11104 This program prints out 0 in @option{-O0} or @option{-O1}
11105 mode, but it prints out 1 in @option{-O2} mode. That's
11106 because in strict aliasing mode, the compiler can and
11107 does assume that the assignment to @code{v2.all} could not
11108 affect the value of @code{v1.all}, since different types
11109 are involved.
11111 This behavior is not a case of non-conformance with the standard, since
11112 the Ada RM specifies that an unchecked conversion where the resulting
11113 bit pattern is not a correct value of the target type can result in an
11114 abnormal value and attempting to reference an abnormal value makes the
11115 execution of a program erroneous.  That's the case here since the result
11116 does not point to an object of type @code{int2}.  This means that the
11117 effect is entirely unpredictable.
11119 However, although that explanation may satisfy a language
11120 lawyer, in practice an applications programmer expects an
11121 unchecked conversion involving pointers to create true
11122 aliases and the behavior of printing 1 seems plain wrong.
11123 In this case, the strict aliasing optimization is unwelcome.
11125 Indeed the compiler recognizes this possibility, and the
11126 unchecked conversion generates a warning:
11128 @smallexample
11129 p2.adb:5:07: warning: possible aliasing problem with type "a2"
11130 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
11131 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
11132 @end smallexample
11134 @noindent
11135 Unfortunately the problem is recognized when compiling the body of
11136 package @code{p2}, but the actual "bad" code is generated while
11137 compiling the body of @code{m} and this latter compilation does not see
11138 the suspicious @code{Unchecked_Conversion}.
11140 As implied by the warning message, there are approaches you can use to
11141 avoid the unwanted strict aliasing optimization in a case like this.
11143 One possibility is to simply avoid the use of @option{-O2}, but
11144 that is a bit drastic, since it throws away a number of useful
11145 optimizations that do not involve strict aliasing assumptions.
11147 A less drastic approach is to compile the program using the
11148 option @option{-fno-strict-aliasing}. Actually it is only the
11149 unit containing the dereferencing of the suspicious pointer
11150 that needs to be compiled. So in this case, if we compile
11151 unit @code{m} with this switch, then we get the expected
11152 value of zero printed. Analyzing which units might need
11153 the switch can be painful, so a more reasonable approach
11154 is to compile the entire program with options @option{-O2}
11155 and @option{-fno-strict-aliasing}. If the performance is
11156 satisfactory with this combination of options, then the
11157 advantage is that the entire issue of possible "wrong"
11158 optimization due to strict aliasing is avoided.
11160 To avoid the use of compiler switches, the configuration
11161 pragma @code{No_Strict_Aliasing} with no parameters may be
11162 used to specify that for all access types, the strict
11163 aliasing optimization should be suppressed.
11165 However, these approaches are still overkill, in that they causes
11166 all manipulations of all access values to be deoptimized. A more
11167 refined approach is to concentrate attention on the specific
11168 access type identified as problematic.
11170 First, if a careful analysis of uses of the pointer shows
11171 that there are no possible problematic references, then
11172 the warning can be suppressed by bracketing the
11173 instantiation of @code{Unchecked_Conversion} to turn
11174 the warning off:
11176 @smallexample @c ada
11177    pragma Warnings (Off);
11178    function to_a2u is
11179      new Unchecked_Conversion (a1, a2);
11180    pragma Warnings (On);
11181 @end smallexample
11183 @noindent
11184 Of course that approach is not appropriate for this particular
11185 example, since indeed there is a problematic reference. In this
11186 case we can take one of two other approaches.
11188 The first possibility is to move the instantiation of unchecked
11189 conversion to the unit in which the type is declared. In
11190 this example, we would move the instantiation of
11191 @code{Unchecked_Conversion} from the body of package
11192 @code{p2} to the spec of package @code{p1}. Now the
11193 warning disappears. That's because any use of the
11194 access type knows there is a suspicious unchecked
11195 conversion, and the strict aliasing optimization
11196 is automatically suppressed for the type.
11198 If it is not practical to move the unchecked conversion to the same unit
11199 in which the destination access type is declared (perhaps because the
11200 source type is not visible in that unit), you may use pragma
11201 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11202 same declarative sequence as the declaration of the access type:
11204 @smallexample @c ada
11205    type a2 is access int2;
11206    pragma No_Strict_Aliasing (a2);
11207 @end smallexample
11209 @noindent
11210 Here again, the compiler now knows that the strict aliasing optimization
11211 should be suppressed for any reference to type @code{a2} and the
11212 expected behavior is obtained.
11214 Finally, note that although the compiler can generate warnings for
11215 simple cases of unchecked conversions, there are tricker and more
11216 indirect ways of creating type incorrect aliases which the compiler
11217 cannot detect. Examples are the use of address overlays and unchecked
11218 conversions involving composite types containing access types as
11219 components. In such cases, no warnings are generated, but there can
11220 still be aliasing problems. One safe coding practice is to forbid the
11221 use of address clauses for type overlaying, and to allow unchecked
11222 conversion only for primitive types. This is not really a significant
11223 restriction since any possible desired effect can be achieved by
11224 unchecked conversion of access values.
11226 The aliasing analysis done in strict aliasing mode can certainly
11227 have significant benefits. We have seen cases of large scale
11228 application code where the time is increased by up to 5% by turning
11229 this optimization off. If you have code that includes significant
11230 usage of unchecked conversion, you might want to just stick with
11231 @option{-O1} and avoid the entire issue. If you get adequate
11232 performance at this level of optimization level, that's probably
11233 the safest approach. If tests show that you really need higher
11234 levels of optimization, then you can experiment with @option{-O2}
11235 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11236 has on size and speed of the code. If you really need to use
11237 @option{-O2} with strict aliasing in effect, then you should
11238 review any uses of unchecked conversion of access types,
11239 particularly if you are getting the warnings described above.
11241 @ifset vms
11242 @node Coverage Analysis
11243 @subsection Coverage Analysis
11245 @noindent
11246 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11247 the user to determine the distribution of execution time across a program,
11248 @pxref{Profiling} for details of usage.
11249 @end ifset
11252 @node Text_IO Suggestions
11253 @section @code{Text_IO} Suggestions
11254 @cindex @code{Text_IO} and performance
11256 @noindent
11257 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11258 the requirement of maintaining page and line counts. If performance
11259 is critical, a recommendation is to use @code{Stream_IO} instead of
11260 @code{Text_IO} for volume output, since this package has less overhead.
11262 If @code{Text_IO} must be used, note that by default output to the standard
11263 output and standard error files is unbuffered (this provides better
11264 behavior when output statements are used for debugging, or if the
11265 progress of a program is observed by tracking the output, e.g. by
11266 using the Unix @command{tail -f} command to watch redirected output.
11268 If you are generating large volumes of output with @code{Text_IO} and
11269 performance is an important factor, use a designated file instead
11270 of the standard output file, or change the standard output file to
11271 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11275 @node Reducing Size of Ada Executables with gnatelim
11276 @section Reducing Size of Ada Executables with @code{gnatelim}
11277 @findex gnatelim
11279 @noindent
11280 This section describes @command{gnatelim}, a tool which detects unused
11281 subprograms and helps the compiler to create a smaller executable for your
11282 program.
11284 @menu
11285 * About gnatelim::
11286 * Running gnatelim::
11287 * Processing Precompiled Libraries::
11288 * Correcting the List of Eliminate Pragmas::
11289 * Making Your Executables Smaller::
11290 * Summary of the gnatelim Usage Cycle::
11291 @end menu
11293 @node About gnatelim
11294 @subsection About @code{gnatelim}
11296 @noindent
11297 When a program shares a set of Ada
11298 packages with other programs, it may happen that this program uses
11299 only a fraction of the subprograms defined in these packages. The code
11300 created for these unused subprograms increases the size of the executable.
11302 @code{gnatelim} tracks unused subprograms in an Ada program and
11303 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11304 subprograms that are declared but never called. By placing the list of
11305 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11306 recompiling your program, you may decrease the size of its executable,
11307 because the compiler will not generate the code for 'eliminated' subprograms.
11308 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11309 information about this pragma.
11311 @code{gnatelim} needs as its input data the name of the main subprogram.
11313 If a set of source files is specified as @code{gnatelim} arguments, it
11314 treats these files as a complete set of sources making up a program to
11315 analyse, and analyses only these sources.
11317 After a full successful build of the main subprogram @code{gnatelim} can be
11318 called without  specifying sources to analyse, in this case it computes
11319 the source closure of the main unit from the @file{ALI} files.
11321 The following command will create the set of @file{ALI} files needed for
11322 @code{gnatelim}:
11324 @smallexample
11325 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11326 @end smallexample
11328 Note that @code{gnatelim} does not need object files.
11330 @node Running gnatelim
11331 @subsection Running @code{gnatelim}
11333 @noindent
11334 @code{gnatelim} has the following command-line interface:
11336 @smallexample
11337 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11338 @end smallexample
11340 @noindent
11341 @var{main_unit_name} should be a name of a source file that contains the main
11342 subprogram of a program (partition).
11344 Each @var{filename} is the name (including the extension) of a source
11345 file to process. ``Wildcards'' are allowed, and
11346 the file name may contain path information.
11348 @samp{@var{gcc_switches}} is a list of switches for
11349 @command{gcc}. They will be passed on to all compiler invocations made by
11350 @command{gnatelim} to generate the ASIS trees. Here you can provide
11351 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11352 use the @option{-gnatec} switch to set the configuration file,
11353 use the @option{-gnat05} switch if sources should be compiled in
11354 Ada 2005 mode etc.
11356 @code{gnatelim} has the following switches:
11358 @table @option
11359 @c !sort!
11360 @item ^-files^/FILES^=@var{filename}
11361 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11362 Take the argument source files from the specified file. This file should be an
11363 ordinary text file containing file names separated by spaces or
11364 line breaks. You can use this switch more than once in the same call to
11365 @command{gnatelim}. You also can combine this switch with
11366 an explicit list of files.
11368 @item ^-log^/LOG^
11369 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11370 Duplicate all the output sent to @file{stderr} into a log file. The log file
11371 is named @file{gnatelim.log} and is located in the current directory.
11373 @item ^-log^/LOGFILE^=@var{filename}
11374 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11375 Duplicate all the output sent to @file{stderr} into a specified log file.
11377 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11378 @item ^--no-elim-dispatch^/NO_DISPATCH^
11379 Do not generate pragmas for dispatching operations.
11381 @item ^--ignore^/IGNORE^=@var{filename}
11382 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11383 Do not generate pragmas for subprograms declared in the sources
11384 listed in a specified file
11386 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11387 @item ^-o^/OUTPUT^=@var{report_file}
11388 Put @command{gnatelim} output into a specified file. If this file already exists,
11389 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11390 into @file{stderr}
11392 @item ^-q^/QUIET^
11393 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11394 Quiet mode: by default @code{gnatelim} outputs to the standard error
11395 stream the number of program units left to be processed. This option turns
11396 this trace off.
11398 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11399 @item ^-t^/TIME^
11400 Print out execution time.
11402 @item ^-v^/VERBOSE^
11403 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11404 Verbose mode: @code{gnatelim} version information is printed as Ada
11405 comments to the standard output stream. Also, in addition to the number of
11406 program units left @code{gnatelim} will output the name of the current unit
11407 being processed.
11409 @item ^-wq^/WARNINGS=QUIET^
11410 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11411 Quiet warning mode - some warnings are suppressed. In particular warnings that
11412 indicate that the analysed set of sources is incomplete to make up a
11413 partition and that some subprogram bodies are missing are not generated.
11414 @end table
11416 @noindent
11417 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11418 driver (see @ref{The GNAT Driver and Project Files}).
11420 @node Processing Precompiled Libraries
11421 @subsection Processing Precompiled Libraries
11423 @noindent
11424 If some program uses a precompiled Ada library, it can be processed by
11425 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11426 Eliminate pragma for a subprogram if the body of this subprogram has not
11427 been analysed, this is a typical case for subprograms from precompiled
11428 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11429 warnings about missing source files and non-analyzed subprogram bodies
11430 that can be generated when processing precompiled Ada libraries.
11432 @node Correcting the List of Eliminate Pragmas
11433 @subsection Correcting the List of Eliminate Pragmas
11435 @noindent
11436 In some rare cases @code{gnatelim} may try to eliminate
11437 subprograms that are actually called in the program. In this case, the
11438 compiler will generate an error message of the form:
11440 @smallexample
11441 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11442 @end smallexample
11444 @noindent
11445 You will need to manually remove the wrong @code{Eliminate} pragmas from
11446 the configuration file indicated in the error message. You should recompile
11447 your program from scratch after that, because you need a consistent
11448 configuration file(s) during the entire compilation.
11450 @node Making Your Executables Smaller
11451 @subsection Making Your Executables Smaller
11453 @noindent
11454 In order to get a smaller executable for your program you now have to
11455 recompile the program completely with the configuration file containing
11456 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11457 @file{gnat.adc} file located in your current directory, just do:
11459 @smallexample
11460 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11461 @end smallexample
11463 @noindent
11464 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11465 recompile everything
11466 with the set of pragmas @code{Eliminate} that you have obtained with
11467 @command{gnatelim}).
11469 Be aware that the set of @code{Eliminate} pragmas is specific to each
11470 program. It is not recommended to merge sets of @code{Eliminate}
11471 pragmas created for different programs in one configuration file.
11473 @node Summary of the gnatelim Usage Cycle
11474 @subsection Summary of the @code{gnatelim} Usage Cycle
11476 @noindent
11477 Here is a quick summary of the steps to be taken in order to reduce
11478 the size of your executables with @code{gnatelim}. You may use
11479 other GNAT options to control the optimization level,
11480 to produce the debugging information, to set search path, etc.
11482 @enumerate
11483 @item
11484 Create a complete set of @file{ALI} files (if the program has not been
11485 built already)
11487 @smallexample
11488 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11489 @end smallexample
11491 @item
11492 Generate a list of @code{Eliminate} pragmas in default configuration file
11493 @file{gnat.adc} in the current directory
11494 @smallexample
11495 @ifset vms
11496 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11497 @end ifset
11498 @ifclear vms
11499 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11500 @end ifclear
11501 @end smallexample
11503 @item
11504 Recompile the application
11506 @smallexample
11507 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11508 @end smallexample
11510 @end enumerate
11512 @node Reducing Size of Executables with unused subprogram/data elimination
11513 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11514 @findex unused subprogram/data elimination
11516 @noindent
11517 This section describes how you can eliminate unused subprograms and data from
11518 your executable just by setting options at compilation time.
11520 @menu
11521 * About unused subprogram/data elimination::
11522 * Compilation options::
11523 * Example of unused subprogram/data elimination::
11524 @end menu
11526 @node About unused subprogram/data elimination
11527 @subsection About unused subprogram/data elimination
11529 @noindent
11530 By default, an executable contains all code and data of its composing objects
11531 (directly linked or coming from statically linked libraries), even data or code
11532 never used by this executable.
11534 This feature will allow you to eliminate such unused code from your
11535 executable, making it smaller (in disk and in memory).
11537 This functionality is available on all Linux platforms except for the IA-64
11538 architecture and on all cross platforms using the ELF binary file format.
11539 In both cases GNU binutils version 2.16 or later are required to enable it.
11541 @node Compilation options
11542 @subsection Compilation options
11544 @noindent
11545 The operation of eliminating the unused code and data from the final executable
11546 is directly performed by the linker.
11548 In order to do this, it has to work with objects compiled with the
11549 following options:
11550 @option{-ffunction-sections} @option{-fdata-sections}.
11551 @cindex @option{-ffunction-sections} (@command{gcc})
11552 @cindex @option{-fdata-sections} (@command{gcc})
11553 These options are usable with C and Ada files.
11554 They will place respectively each
11555 function or data in a separate section in the resulting object file.
11557 Once the objects and static libraries are created with these options, the
11558 linker can perform the dead code elimination. You can do this by setting
11559 the @option{-Wl,--gc-sections} option to gcc command or in the
11560 @option{-largs} section of @command{gnatmake}. This will perform a
11561 garbage collection of code and data never referenced.
11563 If the linker performs a partial link (@option{-r} ld linker option), then you
11564 will need to provide one or several entry point using the
11565 @option{-e} / @option{--entry} ld option.
11567 Note that objects compiled without the @option{-ffunction-sections} and
11568 @option{-fdata-sections} options can still be linked with the executable.
11569 However, no dead code elimination will be performed on those objects (they will
11570 be linked as is).
11572 The GNAT static library is now compiled with -ffunction-sections and
11573 -fdata-sections on some platforms. This allows you to eliminate the unused code
11574 and data of the GNAT library from your executable.
11576 @node Example of unused subprogram/data elimination
11577 @subsection Example of unused subprogram/data elimination
11579 @noindent
11580 Here is a simple example:
11582 @smallexample @c ada
11583 with Aux;
11585 procedure Test is
11586 begin
11587    Aux.Used (10);
11588 end Test;
11590 package Aux is
11591    Used_Data   : Integer;
11592    Unused_Data : Integer;
11594    procedure Used   (Data : Integer);
11595    procedure Unused (Data : Integer);
11596 end Aux;
11598 package body Aux is
11599    procedure Used (Data : Integer) is
11600    begin
11601       Used_Data := Data;
11602    end Used;
11604    procedure Unused (Data : Integer) is
11605    begin
11606       Unused_Data := Data;
11607    end Unused;
11608 end Aux;
11609 @end smallexample
11611 @noindent
11612 @code{Unused} and @code{Unused_Data} are never referenced in this code
11613 excerpt, and hence they may be safely removed from the final executable.
11615 @smallexample
11616 $ gnatmake test
11618 $ nm test | grep used
11619 020015f0 T aux__unused
11620 02005d88 B aux__unused_data
11621 020015cc T aux__used
11622 02005d84 B aux__used_data
11624 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11625      -largs -Wl,--gc-sections
11627 $ nm test | grep used
11628 02005350 T aux__used
11629 0201ffe0 B aux__used_data
11630 @end smallexample
11632 @noindent
11633 It can be observed that the procedure @code{Unused} and the object
11634 @code{Unused_Data} are removed by the linker when using the
11635 appropriate options.
11637 @c ********************************
11638 @node Renaming Files Using gnatchop
11639 @chapter Renaming Files Using @code{gnatchop}
11640 @findex gnatchop
11642 @noindent
11643 This chapter discusses how to handle files with multiple units by using
11644 the @code{gnatchop} utility. This utility is also useful in renaming
11645 files to meet the standard GNAT default file naming conventions.
11647 @menu
11648 * Handling Files with Multiple Units::
11649 * Operating gnatchop in Compilation Mode::
11650 * Command Line for gnatchop::
11651 * Switches for gnatchop::
11652 * Examples of gnatchop Usage::
11653 @end menu
11655 @node Handling Files with Multiple Units
11656 @section Handling Files with Multiple Units
11658 @noindent
11659 The basic compilation model of GNAT requires that a file submitted to the
11660 compiler have only one unit and there be a strict correspondence
11661 between the file name and the unit name.
11663 The @code{gnatchop} utility allows both of these rules to be relaxed,
11664 allowing GNAT to process files which contain multiple compilation units
11665 and files with arbitrary file names. @code{gnatchop}
11666 reads the specified file and generates one or more output files,
11667 containing one unit per file. The unit and the file name correspond,
11668 as required by GNAT.
11670 If you want to permanently restructure a set of ``foreign'' files so that
11671 they match the GNAT rules, and do the remaining development using the
11672 GNAT structure, you can simply use @command{gnatchop} once, generate the
11673 new set of files and work with them from that point on.
11675 Alternatively, if you want to keep your files in the ``foreign'' format,
11676 perhaps to maintain compatibility with some other Ada compilation
11677 system, you can set up a procedure where you use @command{gnatchop} each
11678 time you compile, regarding the source files that it writes as temporary
11679 files that you throw away.
11681 Note that if your file containing multiple units starts with a byte order
11682 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11683 will each start with a copy of this BOM, meaning that they can be compiled
11684 automatically in UTF-8 mode without needing to specify an explicit encoding.
11686 @node Operating gnatchop in Compilation Mode
11687 @section Operating gnatchop in Compilation Mode
11689 @noindent
11690 The basic function of @code{gnatchop} is to take a file with multiple units
11691 and split it into separate files. The boundary between files is reasonably
11692 clear, except for the issue of comments and pragmas. In default mode, the
11693 rule is that any pragmas between units belong to the previous unit, except
11694 that configuration pragmas always belong to the following unit. Any comments
11695 belong to the following unit. These rules
11696 almost always result in the right choice of
11697 the split point without needing to mark it explicitly and most users will
11698 find this default to be what they want. In this default mode it is incorrect to
11699 submit a file containing only configuration pragmas, or one that ends in
11700 configuration pragmas, to @code{gnatchop}.
11702 However, using a special option to activate ``compilation mode'',
11703 @code{gnatchop}
11704 can perform another function, which is to provide exactly the semantics
11705 required by the RM for handling of configuration pragmas in a compilation.
11706 In the absence of configuration pragmas (at the main file level), this
11707 option has no effect, but it causes such configuration pragmas to be handled
11708 in a quite different manner.
11710 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11711 only configuration pragmas, then this file is appended to the
11712 @file{gnat.adc} file in the current directory. This behavior provides
11713 the required behavior described in the RM for the actions to be taken
11714 on submitting such a file to the compiler, namely that these pragmas
11715 should apply to all subsequent compilations in the same compilation
11716 environment. Using GNAT, the current directory, possibly containing a
11717 @file{gnat.adc} file is the representation
11718 of a compilation environment. For more information on the
11719 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11721 Second, in compilation mode, if @code{gnatchop}
11722 is given a file that starts with
11723 configuration pragmas, and contains one or more units, then these
11724 configuration pragmas are prepended to each of the chopped files. This
11725 behavior provides the required behavior described in the RM for the
11726 actions to be taken on compiling such a file, namely that the pragmas
11727 apply to all units in the compilation, but not to subsequently compiled
11728 units.
11730 Finally, if configuration pragmas appear between units, they are appended
11731 to the previous unit. This results in the previous unit being illegal,
11732 since the compiler does not accept configuration pragmas that follow
11733 a unit. This provides the required RM behavior that forbids configuration
11734 pragmas other than those preceding the first compilation unit of a
11735 compilation.
11737 For most purposes, @code{gnatchop} will be used in default mode. The
11738 compilation mode described above is used only if you need exactly
11739 accurate behavior with respect to compilations, and you have files
11740 that contain multiple units and configuration pragmas. In this
11741 circumstance the use of @code{gnatchop} with the compilation mode
11742 switch provides the required behavior, and is for example the mode
11743 in which GNAT processes the ACVC tests.
11745 @node Command Line for gnatchop
11746 @section Command Line for @code{gnatchop}
11748 @noindent
11749 The @code{gnatchop} command has the form:
11751 @smallexample
11752 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11753 @c      @ovar{directory}
11754 @c Expanding @ovar macro inline (explanation in macro def comments)
11755 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11756       @r{[}@var{directory}@r{]}
11757 @end smallexample
11759 @noindent
11760 The only required argument is the file name of the file to be chopped.
11761 There are no restrictions on the form of this file name. The file itself
11762 contains one or more Ada units, in normal GNAT format, concatenated
11763 together. As shown, more than one file may be presented to be chopped.
11765 When run in default mode, @code{gnatchop} generates one output file in
11766 the current directory for each unit in each of the files.
11768 @var{directory}, if specified, gives the name of the directory to which
11769 the output files will be written. If it is not specified, all files are
11770 written to the current directory.
11772 For example, given a
11773 file called @file{hellofiles} containing
11775 @smallexample @c ada
11776 @group
11777 @cartouche
11778 procedure hello;
11780 with Text_IO; use Text_IO;
11781 procedure hello is
11782 begin
11783    Put_Line ("Hello");
11784 end hello;
11785 @end cartouche
11786 @end group
11787 @end smallexample
11789 @noindent
11790 the command
11792 @smallexample
11793 $ gnatchop ^hellofiles^HELLOFILES.^
11794 @end smallexample
11796 @noindent
11797 generates two files in the current directory, one called
11798 @file{hello.ads} containing the single line that is the procedure spec,
11799 and the other called @file{hello.adb} containing the remaining text. The
11800 original file is not affected. The generated files can be compiled in
11801 the normal manner.
11803 @noindent
11804 When gnatchop is invoked on a file that is empty or that contains only empty
11805 lines and/or comments, gnatchop will not fail, but will not produce any
11806 new sources.
11808 For example, given a
11809 file called @file{toto.txt} containing
11811 @smallexample @c ada
11812 @group
11813 @cartouche
11814 --  Just a comment
11815 @end cartouche
11816 @end group
11817 @end smallexample
11819 @noindent
11820 the command
11822 @smallexample
11823 $ gnatchop ^toto.txt^TOT.TXT^
11824 @end smallexample
11826 @noindent
11827 will not produce any new file and will result in the following warnings:
11829 @smallexample
11830 toto.txt:1:01: warning: empty file, contains no compilation units
11831 no compilation units found
11832 no source files written
11833 @end smallexample
11835 @node Switches for gnatchop
11836 @section Switches for @code{gnatchop}
11838 @noindent
11839 @command{gnatchop} recognizes the following switches:
11841 @table @option
11842 @c !sort!
11844 @item --version
11845 @cindex @option{--version} @command{gnatchop}
11846 Display Copyright and version, then exit disregarding all other options.
11848 @item --help
11849 @cindex @option{--help} @command{gnatchop}
11850 If @option{--version} was not used, display usage, then exit disregarding
11851 all other options.
11853 @item ^-c^/COMPILATION^
11854 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11855 Causes @code{gnatchop} to operate in compilation mode, in which
11856 configuration pragmas are handled according to strict RM rules. See
11857 previous section for a full description of this mode.
11859 @ifclear vms
11860 @item -gnat@var{xxx}
11861 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11862 used to parse the given file. Not all @var{xxx} options make sense,
11863 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11864 process a source file that uses Latin-2 coding for identifiers.
11865 @end ifclear
11867 @item ^-h^/HELP^
11868 Causes @code{gnatchop} to generate a brief help summary to the standard
11869 output file showing usage information.
11871 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11872 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11873 Limit generated file names to the specified number @code{mm}
11874 of characters.
11875 This is useful if the
11876 resulting set of files is required to be interoperable with systems
11877 which limit the length of file names.
11878 @ifset vms
11879 If no value is given, or
11880 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11881 a default of 39, suitable for OpenVMS Alpha
11882 Systems, is assumed
11883 @end ifset
11884 @ifclear vms
11885 No space is allowed between the @option{-k} and the numeric value. The numeric
11886 value may be omitted in which case a default of @option{-k8},
11887 suitable for use
11888 with DOS-like file systems, is used. If no @option{-k} switch
11889 is present then
11890 there is no limit on the length of file names.
11891 @end ifclear
11893 @item ^-p^/PRESERVE^
11894 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11895 Causes the file ^modification^creation^ time stamp of the input file to be
11896 preserved and used for the time stamp of the output file(s). This may be
11897 useful for preserving coherency of time stamps in an environment where
11898 @code{gnatchop} is used as part of a standard build process.
11900 @item ^-q^/QUIET^
11901 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11902 Causes output of informational messages indicating the set of generated
11903 files to be suppressed. Warnings and error messages are unaffected.
11905 @item ^-r^/REFERENCE^
11906 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11907 @findex Source_Reference
11908 Generate @code{Source_Reference} pragmas. Use this switch if the output
11909 files are regarded as temporary and development is to be done in terms
11910 of the original unchopped file. This switch causes
11911 @code{Source_Reference} pragmas to be inserted into each of the
11912 generated files to refers back to the original file name and line number.
11913 The result is that all error messages refer back to the original
11914 unchopped file.
11915 In addition, the debugging information placed into the object file (when
11916 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11917 specified)
11918 also refers back to this original file so that tools like profilers and
11919 debuggers will give information in terms of the original unchopped file.
11921 If the original file to be chopped itself contains
11922 a @code{Source_Reference}
11923 pragma referencing a third file, then gnatchop respects
11924 this pragma, and the generated @code{Source_Reference} pragmas
11925 in the chopped file refer to the original file, with appropriate
11926 line numbers. This is particularly useful when @code{gnatchop}
11927 is used in conjunction with @code{gnatprep} to compile files that
11928 contain preprocessing statements and multiple units.
11930 @item ^-v^/VERBOSE^
11931 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11932 Causes @code{gnatchop} to operate in verbose mode. The version
11933 number and copyright notice are output, as well as exact copies of
11934 the gnat1 commands spawned to obtain the chop control information.
11936 @item ^-w^/OVERWRITE^
11937 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11938 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11939 fatal error if there is already a file with the same name as a
11940 file it would otherwise output, in other words if the files to be
11941 chopped contain duplicated units. This switch bypasses this
11942 check, and causes all but the last instance of such duplicated
11943 units to be skipped.
11945 @ifclear vms
11946 @item --GCC=@var{xxxx}
11947 @cindex @option{--GCC=} (@code{gnatchop})
11948 Specify the path of the GNAT parser to be used. When this switch is used,
11949 no attempt is made to add the prefix to the GNAT parser executable.
11950 @end ifclear
11951 @end table
11953 @node Examples of gnatchop Usage
11954 @section Examples of @code{gnatchop} Usage
11956 @table @code
11957 @ifset vms
11958 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11959 @end ifset
11960 @ifclear vms
11961 @item gnatchop -w hello_s.ada prerelease/files
11962 @end ifclear
11964 Chops the source file @file{hello_s.ada}. The output files will be
11965 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11966 overwriting any
11967 files with matching names in that directory (no files in the current
11968 directory are modified).
11970 @item gnatchop ^archive^ARCHIVE.^
11971 Chops the source file @file{^archive^ARCHIVE.^}
11972 into the current directory. One
11973 useful application of @code{gnatchop} is in sending sets of sources
11974 around, for example in email messages. The required sources are simply
11975 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11976 command), and then
11977 @command{gnatchop} is used at the other end to reconstitute the original
11978 file names.
11980 @item gnatchop file1 file2 file3 direc
11981 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11982 the resulting files in the directory @file{direc}. Note that if any units
11983 occur more than once anywhere within this set of files, an error message
11984 is generated, and no files are written. To override this check, use the
11985 @option{^-w^/OVERWRITE^} switch,
11986 in which case the last occurrence in the last file will
11987 be the one that is output, and earlier duplicate occurrences for a given
11988 unit will be skipped.
11989 @end table
11991 @node Configuration Pragmas
11992 @chapter Configuration Pragmas
11993 @cindex Configuration pragmas
11994 @cindex Pragmas, configuration
11996 @noindent
11997 Configuration pragmas include those pragmas described as
11998 such in the Ada Reference Manual, as well as
11999 implementation-dependent pragmas that are configuration pragmas.
12000 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
12001 for details on these additional GNAT-specific configuration pragmas.
12002 Most notably, the pragma @code{Source_File_Name}, which allows
12003 specifying non-default names for source files, is a configuration
12004 pragma. The following is a complete list of configuration pragmas
12005 recognized by GNAT:
12007 @smallexample
12008    Ada_83
12009    Ada_95
12010    Ada_05
12011    Ada_2005
12012    Ada_12
12013    Ada_2012
12014    Annotate
12015    Assertion_Policy
12016    Assume_No_Invalid_Values
12017    C_Pass_By_Copy
12018    Check_Name
12019    Check_Policy
12020    Compile_Time_Error
12021    Compile_Time_Warning
12022    Compiler_Unit
12023    Component_Alignment
12024    Convention_Identifier
12025    Debug_Policy
12026    Detect_Blocking
12027    Default_Storage_Pool
12028    Discard_Names
12029    Elaboration_Checks
12030    Eliminate
12031    Extend_System
12032    Extensions_Allowed
12033    External_Name_Casing
12034    Fast_Math
12035    Favor_Top_Level
12036    Float_Representation
12037    Implicit_Packing
12038    Initialize_Scalars
12039    Interrupt_State
12040    License
12041    Locking_Policy
12042    Long_Float
12043    No_Run_Time
12044    No_Strict_Aliasing
12045    Normalize_Scalars
12046    Optimize_Alignment
12047    Persistent_BSS
12048    Polling
12049    Priority_Specific_Dispatching
12050    Profile
12051    Profile_Warnings
12052    Propagate_Exceptions
12053    Queuing_Policy
12054    Ravenscar
12055    Restricted_Run_Time
12056    Restrictions
12057    Restrictions_Warnings
12058    Reviewable
12059    Short_Circuit_And_Or
12060    Source_File_Name
12061    Source_File_Name_Project
12062    Style_Checks
12063    Suppress
12064    Suppress_Exception_Locations
12065    Task_Dispatching_Policy
12066    Universal_Data
12067    Unsuppress
12068    Use_VADS_Size
12069    Validity_Checks
12070    Warnings
12071    Wide_Character_Encoding
12073 @end smallexample
12075 @menu
12076 * Handling of Configuration Pragmas::
12077 * The Configuration Pragmas Files::
12078 @end menu
12080 @node Handling of Configuration Pragmas
12081 @section Handling of Configuration Pragmas
12083 Configuration pragmas may either appear at the start of a compilation
12084 unit, or they can appear in a configuration pragma file to apply to
12085 all compilations performed in a given compilation environment.
12087 GNAT also provides the @code{gnatchop} utility to provide an automatic
12088 way to handle configuration pragmas following the semantics for
12089 compilations (that is, files with multiple units), described in the RM.
12090 See @ref{Operating gnatchop in Compilation Mode} for details.
12091 However, for most purposes, it will be more convenient to edit the
12092 @file{gnat.adc} file that contains configuration pragmas directly,
12093 as described in the following section.
12095 In the case of @code{Restrictions} pragmas appearing as configuration
12096 pragmas in individual compilation units, the exact handling depends on
12097 the type of restriction.
12099 Restrictions that require partition-wide consistency (like
12100 @code{No_Tasking}) are
12101 recognized wherever they appear
12102 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12103 unit. This makes sense since the binder will in any case insist on seeing
12104 consistent use, so any unit not conforming to any restrictions that are
12105 anywhere in the partition will be rejected, and you might as well find
12106 that out at compile time rather than at bind time.
12108 For restrictions that do not require partition-wide consistency, e.g.
12109 SPARK or No_Implementation_Attributes, in general the restriction applies
12110 only to the unit in which the pragma appears, and not to any other units.
12112 The exception is No_Elaboration_Code which always applies to the entire
12113 object file from a compilation, i.e. to the body, spec, and all subunits.
12114 This restriction can be specified in a configuration pragma file, or it
12115 can be on the body and/or the spec (in eithe case it applies to all the
12116 relevant units). It can appear on a subunit only if it has previously
12117 appeared in the body of spec.
12119 @node The Configuration Pragmas Files
12120 @section The Configuration Pragmas Files
12121 @cindex @file{gnat.adc}
12123 @noindent
12124 In GNAT a compilation environment is defined by the current
12125 directory at the time that a compile command is given. This current
12126 directory is searched for a file whose name is @file{gnat.adc}. If
12127 this file is present, it is expected to contain one or more
12128 configuration pragmas that will be applied to the current compilation.
12129 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12130 considered.
12132 Configuration pragmas may be entered into the @file{gnat.adc} file
12133 either by running @code{gnatchop} on a source file that consists only of
12134 configuration pragmas, or more conveniently  by
12135 direct editing of the @file{gnat.adc} file, which is a standard format
12136 source file.
12138 In addition to @file{gnat.adc}, additional files containing configuration
12139 pragmas may be applied to the current compilation using the switch
12140 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12141 contains only configuration pragmas. These configuration pragmas are
12142 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12143 is present and switch @option{-gnatA} is not used).
12145 It is allowed to specify several switches @option{-gnatec}, all of which
12146 will be taken into account.
12148 If you are using project file, a separate mechanism is provided using
12149 project attributes, see @ref{Specifying Configuration Pragmas} for more
12150 details.
12152 @ifset vms
12153 Of special interest to GNAT OpenVMS Alpha is the following
12154 configuration pragma:
12156 @smallexample @c ada
12157 @cartouche
12158 pragma Extend_System (Aux_DEC);
12159 @end cartouche
12160 @end smallexample
12162 @noindent
12163 In the presence of this pragma, GNAT adds to the definition of the
12164 predefined package SYSTEM all the additional types and subprograms that are
12165 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12166 @end ifset
12168 @node Handling Arbitrary File Naming Conventions Using gnatname
12169 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
12170 @cindex Arbitrary File Naming Conventions
12172 @menu
12173 * Arbitrary File Naming Conventions::
12174 * Running gnatname::
12175 * Switches for gnatname::
12176 * Examples of gnatname Usage::
12177 @end menu
12179 @node Arbitrary File Naming Conventions
12180 @section Arbitrary File Naming Conventions
12182 @noindent
12183 The GNAT compiler must be able to know the source file name of a compilation
12184 unit.  When using the standard GNAT default file naming conventions
12185 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12186 does not need additional information.
12188 @noindent
12189 When the source file names do not follow the standard GNAT default file naming
12190 conventions, the GNAT compiler must be given additional information through
12191 a configuration pragmas file (@pxref{Configuration Pragmas})
12192 or a project file.
12193 When the non-standard file naming conventions are well-defined,
12194 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12195 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12196 if the file naming conventions are irregular or arbitrary, a number
12197 of pragma @code{Source_File_Name} for individual compilation units
12198 must be defined.
12199 To help maintain the correspondence between compilation unit names and
12200 source file names within the compiler,
12201 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12202 set of files.
12204 @node Running gnatname
12205 @section Running @code{gnatname}
12207 @noindent
12208 The usual form of the @code{gnatname} command is
12210 @smallexample
12211 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12212 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12213 @c Expanding @ovar macro inline (explanation in macro def comments)
12214 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12215       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12216 @end smallexample
12218 @noindent
12219 All of the arguments are optional. If invoked without any argument,
12220 @code{gnatname} will display its usage.
12222 @noindent
12223 When used with at least one naming pattern, @code{gnatname} will attempt to
12224 find all the compilation units in files that follow at least one of the
12225 naming patterns. To find these compilation units,
12226 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12227 regular files.
12229 @noindent
12230 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12231 Each Naming Pattern is enclosed between double quotes (or single
12232 quotes on Windows).
12233 A Naming Pattern is a regular expression similar to the wildcard patterns
12234 used in file names by the Unix shells or the DOS prompt.
12236 @noindent
12237 @code{gnatname} may be called with several sections of directories/patterns.
12238 Sections are separated by switch @code{--and}. In each section, there must be
12239 at least one pattern. If no directory is specified in a section, the current
12240 directory (or the project directory is @code{-P} is used) is implied.
12241 The options other that the directory switches and the patterns apply globally
12242 even if they are in different sections.
12244 @noindent
12245 Examples of Naming Patterns are
12247 @smallexample
12248    "*.[12].ada"
12249    "*.ad[sb]*"
12250    "body_*"    "spec_*"
12251 @end smallexample
12253 @noindent
12254 For a more complete description of the syntax of Naming Patterns,
12255 see the second kind of regular expressions described in @file{g-regexp.ads}
12256 (the ``Glob'' regular expressions).
12258 @noindent
12259 When invoked with no switch @code{-P}, @code{gnatname} will create a
12260 configuration pragmas file @file{gnat.adc} in the current working directory,
12261 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12262 unit.
12264 @node Switches for gnatname
12265 @section Switches for @code{gnatname}
12267 @noindent
12268 Switches for @code{gnatname} must precede any specified Naming Pattern.
12270 @noindent
12271 You may specify any of the following switches to @code{gnatname}:
12273 @table @option
12274 @c !sort!
12276 @item --version
12277 @cindex @option{--version} @command{gnatname}
12278 Display Copyright and version, then exit disregarding all other options.
12280 @item --help
12281 @cindex @option{--help} @command{gnatname}
12282 If @option{--version} was not used, display usage, then exit disregarding
12283 all other options.
12285 @item --and
12286 Start another section of directories/patterns.
12288 @item ^-c^/CONFIG_FILE=^@file{file}
12289 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12290 Create a configuration pragmas file @file{file} (instead of the default
12291 @file{gnat.adc}).
12292 @ifclear vms
12293 There may be zero, one or more space between @option{-c} and
12294 @file{file}.
12295 @end ifclear
12296 @file{file} may include directory information. @file{file} must be
12297 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12298 When a switch @option{^-c^/CONFIG_FILE^} is
12299 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12301 @item ^-d^/SOURCE_DIRS=^@file{dir}
12302 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12303 Look for source files in directory @file{dir}. There may be zero, one or more
12304 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12305 When a switch @option{^-d^/SOURCE_DIRS^}
12306 is specified, the current working directory will not be searched for source
12307 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12308 or @option{^-D^/DIR_FILES^} switch.
12309 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12310 If @file{dir} is a relative path, it is relative to the directory of
12311 the configuration pragmas file specified with switch
12312 @option{^-c^/CONFIG_FILE^},
12313 or to the directory of the project file specified with switch
12314 @option{^-P^/PROJECT_FILE^} or,
12315 if neither switch @option{^-c^/CONFIG_FILE^}
12316 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12317 current working directory. The directory
12318 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12320 @item ^-D^/DIRS_FILE=^@file{file}
12321 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12322 Look for source files in all directories listed in text file @file{file}.
12323 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12324 and @file{file}.
12325 @file{file} must be an existing, readable text file.
12326 Each nonempty line in @file{file} must be a directory.
12327 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12328 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12329 @file{file}.
12331 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12332 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12333 Foreign patterns. Using this switch, it is possible to add sources of languages
12334 other than Ada to the list of sources of a project file.
12335 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12336 For example,
12337 @smallexample
12338 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12339 @end smallexample
12340 @noindent
12341 will look for Ada units in all files with the @file{.ada} extension,
12342 and will add to the list of file for project @file{prj.gpr} the C files
12343 with extension @file{.^c^C^}.
12345 @item ^-h^/HELP^
12346 @cindex @option{^-h^/HELP^} (@code{gnatname})
12347 Output usage (help) information. The output is written to @file{stdout}.
12349 @item ^-P^/PROJECT_FILE=^@file{proj}
12350 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12351 Create or update project file @file{proj}. There may be zero, one or more space
12352 between @option{-P} and @file{proj}. @file{proj} may include directory
12353 information. @file{proj} must be writable.
12354 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12355 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12356 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12358 @item ^-v^/VERBOSE^
12359 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12360 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12361 This includes name of the file written, the name of the directories to search
12362 and, for each file in those directories whose name matches at least one of
12363 the Naming Patterns, an indication of whether the file contains a unit,
12364 and if so the name of the unit.
12366 @item ^-v -v^/VERBOSE /VERBOSE^
12367 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12368 Very Verbose mode. In addition to the output produced in verbose mode,
12369 for each file in the searched directories whose name matches none of
12370 the Naming Patterns, an indication is given that there is no match.
12372 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12373 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12374 Excluded patterns. Using this switch, it is possible to exclude some files
12375 that would match the name patterns. For example,
12376 @smallexample
12377 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12378 @end smallexample
12379 @noindent
12380 will look for Ada units in all files with the @file{.ada} extension,
12381 except those whose names end with @file{_nt.ada}.
12383 @end table
12385 @node Examples of gnatname Usage
12386 @section Examples of @code{gnatname} Usage
12388 @ifset vms
12389 @smallexample
12390 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12391 @end smallexample
12392 @end ifset
12394 @ifclear vms
12395 @smallexample
12396 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12397 @end smallexample
12398 @end ifclear
12400 @noindent
12401 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12402 and be writable. In addition, the directory
12403 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12404 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12406 @ifclear vms
12407 Note the optional spaces after @option{-c} and @option{-d}.
12408 @end ifclear
12410 @smallexample
12411 @ifclear vms
12412 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12413   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12414 @end ifclear
12415 @ifset vms
12416 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12417   /EXCLUDED_PATTERN=*_nt_body.ada
12418   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12419   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12420 @end ifset
12421 @end smallexample
12423 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12424 even in conjunction with one or several switches
12425 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12426 are used in this example.
12428 @c *****************************************
12429 @c * G N A T  P r o j e c t  M a n a g e r *
12430 @c *****************************************
12432 @c ------ macros for projects.texi
12433 @c These macros are needed when building the gprbuild documentation, but
12434 @c should have no effect in the gnat user's guide
12436 @macro CODESAMPLE{TXT}
12437 @smallexample
12438 @group
12439 \TXT\
12440 @end group
12441 @end smallexample
12442 @end macro
12444 @macro PROJECTFILE{TXT}
12445 @CODESAMPLE{\TXT\}
12446 @end macro
12448 @c simulates a newline when in a @CODESAMPLE
12449 @macro NL{}
12450 @end macro
12452 @macro TIP{TXT}
12453 @quotation
12454 @noindent
12455 \TXT\
12456 @end quotation
12457 @end macro
12459 @macro TIPHTML{TXT}
12460 \TXT\
12461 @end macro
12463 @macro IMPORTANT{TXT}
12464 @quotation
12465 @noindent
12466 \TXT\
12467 @end quotation
12469 @end macro
12471 @macro NOTE{TXT}
12472 @quotation
12473 @noindent
12474 \TXT\
12475 @end quotation
12476 @end macro
12478 @include projects.texi
12480 @c *****************************************
12481 @c * Cross-referencing tools
12482 @c *****************************************
12484 @node The Cross-Referencing Tools gnatxref and gnatfind
12485 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12486 @findex gnatxref
12487 @findex gnatfind
12489 @noindent
12490 The compiler generates cross-referencing information (unless
12491 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12492 This information indicates where in the source each entity is declared and
12493 referenced. Note that entities in package Standard are not included, but
12494 entities in all other predefined units are included in the output.
12496 Before using any of these two tools, you need to compile successfully your
12497 application, so that GNAT gets a chance to generate the cross-referencing
12498 information.
12500 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12501 information to provide the user with the capability to easily locate the
12502 declaration and references to an entity. These tools are quite similar,
12503 the difference being that @code{gnatfind} is intended for locating
12504 definitions and/or references to a specified entity or entities, whereas
12505 @code{gnatxref} is oriented to generating a full report of all
12506 cross-references.
12508 To use these tools, you must not compile your application using the
12509 @option{-gnatx} switch on the @command{gnatmake} command line
12510 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12511 information will not be generated.
12513 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12514 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12516 @menu
12517 * Switches for gnatxref::
12518 * Switches for gnatfind::
12519 * Project Files for gnatxref and gnatfind::
12520 * Regular Expressions in gnatfind and gnatxref::
12521 * Examples of gnatxref Usage::
12522 * Examples of gnatfind Usage::
12523 @end menu
12525 @node Switches for gnatxref
12526 @section @code{gnatxref} Switches
12528 @noindent
12529 The command invocation for @code{gnatxref} is:
12530 @smallexample
12531 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12532 @c Expanding @ovar macro inline (explanation in macro def comments)
12533 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12534 @end smallexample
12536 @noindent
12537 where
12539 @table @var
12540 @item sourcefile1
12541 @itemx sourcefile2
12542 identifies the source files for which a report is to be generated. The
12543 ``with''ed units will be processed too. You must provide at least one file.
12545 These file names are considered to be regular expressions, so for instance
12546 specifying @file{source*.adb} is the same as giving every file in the current
12547 directory whose name starts with @file{source} and whose extension is
12548 @file{adb}.
12550 You shouldn't specify any directory name, just base names. @command{gnatxref}
12551 and @command{gnatfind} will be able to locate these files by themselves using
12552 the source path. If you specify directories, no result is produced.
12554 @end table
12556 @noindent
12557 The switches can be:
12558 @table @option
12559 @c !sort!
12560 @item --version
12561 @cindex @option{--version} @command{gnatxref}
12562 Display Copyright and version, then exit disregarding all other options.
12564 @item --help
12565 @cindex @option{--help} @command{gnatxref}
12566 If @option{--version} was not used, display usage, then exit disregarding
12567 all other options.
12569 @item ^-a^/ALL_FILES^
12570 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12571 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12572 the read-only files found in the library search path. Otherwise, these files
12573 will be ignored. This option can be used to protect Gnat sources or your own
12574 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12575 much faster, and their output much smaller. Read-only here refers to access
12576 or permissions status in the file system for the current user.
12578 @item -aIDIR
12579 @cindex @option{-aIDIR} (@command{gnatxref})
12580 When looking for source files also look in directory DIR. The order in which
12581 source file search is undertaken is the same as for @command{gnatmake}.
12583 @item -aODIR
12584 @cindex @option{-aODIR} (@command{gnatxref})
12585 When searching for library and object files, look in directory
12586 DIR. The order in which library files are searched is the same as for
12587 @command{gnatmake}.
12589 @item -nostdinc
12590 @cindex @option{-nostdinc} (@command{gnatxref})
12591 Do not look for sources in the system default directory.
12593 @item -nostdlib
12594 @cindex @option{-nostdlib} (@command{gnatxref})
12595 Do not look for library files in the system default directory.
12597 @item --ext=@var{extension}
12598 @cindex @option{--ext} (@command{gnatxref})
12599 Specify an alternate ali file extension. The default is @code{ali} and other
12600 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12601 switch. Note that if this switch overrides the default, which means that only
12602 the new extension will be considered.
12604 @item --RTS=@var{rts-path}
12605 @cindex @option{--RTS} (@command{gnatxref})
12606 Specifies the default location of the runtime library. Same meaning as the
12607 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12609 @item ^-d^/DERIVED_TYPES^
12610 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12611 If this switch is set @code{gnatxref} will output the parent type
12612 reference for each matching derived types.
12614 @item ^-f^/FULL_PATHNAME^
12615 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12616 If this switch is set, the output file names will be preceded by their
12617 directory (if the file was found in the search path). If this switch is
12618 not set, the directory will not be printed.
12620 @item ^-g^/IGNORE_LOCALS^
12621 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12622 If this switch is set, information is output only for library-level
12623 entities, ignoring local entities. The use of this switch may accelerate
12624 @code{gnatfind} and @code{gnatxref}.
12626 @item -IDIR
12627 @cindex @option{-IDIR} (@command{gnatxref})
12628 Equivalent to @samp{-aODIR -aIDIR}.
12630 @item -pFILE
12631 @cindex @option{-pFILE} (@command{gnatxref})
12632 Specify a project file to use @xref{GNAT Project Manager}.
12633 If you need to use the @file{.gpr}
12634 project files, you should use gnatxref through the GNAT driver
12635 (@command{gnat xref -Pproject}).
12637 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12638 project file in the current directory.
12640 If a project file is either specified or found by the tools, then the content
12641 of the source directory and object directory lines are added as if they
12642 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12643 and @samp{^-aO^OBJECT_SEARCH^}.
12644 @item ^-u^/UNUSED^
12645 Output only unused symbols. This may be really useful if you give your
12646 main compilation unit on the command line, as @code{gnatxref} will then
12647 display every unused entity and 'with'ed package.
12649 @ifclear vms
12650 @item -v
12651 Instead of producing the default output, @code{gnatxref} will generate a
12652 @file{tags} file that can be used by vi. For examples how to use this
12653 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12654 to the standard output, thus you will have to redirect it to a file.
12655 @end ifclear
12657 @end table
12659 @noindent
12660 All these switches may be in any order on the command line, and may even
12661 appear after the file names. They need not be separated by spaces, thus
12662 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12663 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12665 @node Switches for gnatfind
12666 @section @code{gnatfind} Switches
12668 @noindent
12669 The command line for @code{gnatfind} is:
12671 @smallexample
12672 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12673 @c       @r{[}@var{file1} @var{file2} @dots{}]
12674 @c Expanding @ovar macro inline (explanation in macro def comments)
12675 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12676       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12677 @end smallexample
12679 @noindent
12680 where
12682 @table @var
12683 @item pattern
12684 An entity will be output only if it matches the regular expression found
12685 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12687 Omitting the pattern is equivalent to specifying @samp{*}, which
12688 will match any entity. Note that if you do not provide a pattern, you
12689 have to provide both a sourcefile and a line.
12691 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12692 for matching purposes. At the current time there is no support for
12693 8-bit codes other than Latin-1, or for wide characters in identifiers.
12695 @item sourcefile
12696 @code{gnatfind} will look for references, bodies or declarations
12697 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12698 and column @var{column}. See @ref{Examples of gnatfind Usage}
12699 for syntax examples.
12701 @item line
12702 is a decimal integer identifying the line number containing
12703 the reference to the entity (or entities) to be located.
12705 @item column
12706 is a decimal integer identifying the exact location on the
12707 line of the first character of the identifier for the
12708 entity reference. Columns are numbered from 1.
12710 @item file1 file2 @dots{}
12711 The search will be restricted to these source files. If none are given, then
12712 the search will be done for every library file in the search path.
12713 These file must appear only after the pattern or sourcefile.
12715 These file names are considered to be regular expressions, so for instance
12716 specifying @file{source*.adb} is the same as giving every file in the current
12717 directory whose name starts with @file{source} and whose extension is
12718 @file{adb}.
12720 The location of the spec of the entity will always be displayed, even if it
12721 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12722 occurrences of the entity in the separate units of the ones given on the
12723 command line will also be displayed.
12725 Note that if you specify at least one file in this part, @code{gnatfind} may
12726 sometimes not be able to find the body of the subprograms.
12728 @end table
12730 @noindent
12731 At least one of 'sourcefile' or 'pattern' has to be present on
12732 the command line.
12734 The following switches are available:
12735 @table @option
12736 @c !sort!
12738 @cindex @option{--version} @command{gnatfind}
12739 Display Copyright and version, then exit disregarding all other options.
12741 @item --help
12742 @cindex @option{--help} @command{gnatfind}
12743 If @option{--version} was not used, display usage, then exit disregarding
12744 all other options.
12746 @item ^-a^/ALL_FILES^
12747 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12748 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12749 the read-only files found in the library search path. Otherwise, these files
12750 will be ignored. This option can be used to protect Gnat sources or your own
12751 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12752 much faster, and their output much smaller. Read-only here refers to access
12753 or permission status in the file system for the current user.
12755 @item -aIDIR
12756 @cindex @option{-aIDIR} (@command{gnatfind})
12757 When looking for source files also look in directory DIR. The order in which
12758 source file search is undertaken is the same as for @command{gnatmake}.
12760 @item -aODIR
12761 @cindex @option{-aODIR} (@command{gnatfind})
12762 When searching for library and object files, look in directory
12763 DIR. The order in which library files are searched is the same as for
12764 @command{gnatmake}.
12766 @item -nostdinc
12767 @cindex @option{-nostdinc} (@command{gnatfind})
12768 Do not look for sources in the system default directory.
12770 @item -nostdlib
12771 @cindex @option{-nostdlib} (@command{gnatfind})
12772 Do not look for library files in the system default directory.
12774 @item --ext=@var{extension}
12775 @cindex @option{--ext} (@command{gnatfind})
12776 Specify an alternate ali file extension. The default is @code{ali} and other
12777 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12778 switch. Note that if this switch overrides the default, which means that only
12779 the new extension will be considered.
12781 @item --RTS=@var{rts-path}
12782 @cindex @option{--RTS} (@command{gnatfind})
12783 Specifies the default location of the runtime library. Same meaning as the
12784 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12786 @item ^-d^/DERIVED_TYPE_INFORMATION^
12787 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12788 If this switch is set, then @code{gnatfind} will output the parent type
12789 reference for each matching derived types.
12791 @item ^-e^/EXPRESSIONS^
12792 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12793 By default, @code{gnatfind} accept the simple regular expression set for
12794 @samp{pattern}. If this switch is set, then the pattern will be
12795 considered as full Unix-style regular expression.
12797 @item ^-f^/FULL_PATHNAME^
12798 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12799 If this switch is set, the output file names will be preceded by their
12800 directory (if the file was found in the search path). If this switch is
12801 not set, the directory will not be printed.
12803 @item ^-g^/IGNORE_LOCALS^
12804 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12805 If this switch is set, information is output only for library-level
12806 entities, ignoring local entities. The use of this switch may accelerate
12807 @code{gnatfind} and @code{gnatxref}.
12809 @item -IDIR
12810 @cindex @option{-IDIR} (@command{gnatfind})
12811 Equivalent to @samp{-aODIR -aIDIR}.
12813 @item -pFILE
12814 @cindex @option{-pFILE} (@command{gnatfind})
12815 Specify a project file (@pxref{GNAT Project Manager}) to use.
12816 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12817 project file in the current directory.
12819 If a project file is either specified or found by the tools, then the content
12820 of the source directory and object directory lines are added as if they
12821 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12822 @samp{^-aO^/OBJECT_SEARCH^}.
12824 @item ^-r^/REFERENCES^
12825 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12826 By default, @code{gnatfind} will output only the information about the
12827 declaration, body or type completion of the entities. If this switch is
12828 set, the @code{gnatfind} will locate every reference to the entities in
12829 the files specified on the command line (or in every file in the search
12830 path if no file is given on the command line).
12832 @item ^-s^/PRINT_LINES^
12833 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12834 If this switch is set, then @code{gnatfind} will output the content
12835 of the Ada source file lines were the entity was found.
12837 @item ^-t^/TYPE_HIERARCHY^
12838 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12839 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12840 the specified type. It act like -d option but recursively from parent
12841 type to parent type. When this switch is set it is not possible to
12842 specify more than one file.
12844 @end table
12846 @noindent
12847 All these switches may be in any order on the command line, and may even
12848 appear after the file names. They need not be separated by spaces, thus
12849 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12850 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12852 As stated previously, gnatfind will search in every directory in the
12853 search path. You can force it to look only in the current directory if
12854 you specify @code{*} at the end of the command line.
12856 @node Project Files for gnatxref and gnatfind
12857 @section Project Files for @command{gnatxref} and @command{gnatfind}
12859 @noindent
12860 Project files allow a programmer to specify how to compile its
12861 application, where to find sources, etc.  These files are used
12862 @ifclear vms
12863 primarily by GPS, but they can also be used
12864 @end ifclear
12865 by the two tools
12866 @code{gnatxref} and @code{gnatfind}.
12868 A project file name must end with @file{.gpr}. If a single one is
12869 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12870 extract the information from it. If multiple project files are found, none of
12871 them is read, and you have to use the @samp{-p} switch to specify the one
12872 you want to use.
12874 The following lines can be included, even though most of them have default
12875 values which can be used in most cases.
12876 The lines can be entered in any order in the file.
12877 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12878 each line. If you have multiple instances, only the last one is taken into
12879 account.
12881 @table @code
12882 @item src_dir=DIR
12883 [default: @code{"^./^[]^"}]
12884 specifies a directory where to look for source files. Multiple @code{src_dir}
12885 lines can be specified and they will be searched in the order they
12886 are specified.
12888 @item obj_dir=DIR
12889 [default: @code{"^./^[]^"}]
12890 specifies a directory where to look for object and library files. Multiple
12891 @code{obj_dir} lines can be specified, and they will be searched in the order
12892 they are specified
12894 @item comp_opt=SWITCHES
12895 [default: @code{""}]
12896 creates a variable which can be referred to subsequently by using
12897 the @code{$@{comp_opt@}} notation. This is intended to store the default
12898 switches given to @command{gnatmake} and @command{gcc}.
12900 @item bind_opt=SWITCHES
12901 [default: @code{""}]
12902 creates a variable which can be referred to subsequently by using
12903 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12904 switches given to @command{gnatbind}.
12906 @item link_opt=SWITCHES
12907 [default: @code{""}]
12908 creates a variable which can be referred to subsequently by using
12909 the @samp{$@{link_opt@}} notation. This is intended to store the default
12910 switches given to @command{gnatlink}.
12912 @item main=EXECUTABLE
12913 [default: @code{""}]
12914 specifies the name of the executable for the application. This variable can
12915 be referred to in the following lines by using the @samp{$@{main@}} notation.
12917 @ifset vms
12918 @item comp_cmd=COMMAND
12919 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12920 @end ifset
12921 @ifclear vms
12922 @item comp_cmd=COMMAND
12923 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12924 @end ifclear
12925 specifies the command used to compile a single file in the application.
12927 @ifset vms
12928 @item make_cmd=COMMAND
12929 [default: @code{"GNAT MAKE $@{main@}
12930 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12931 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12932 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12933 @end ifset
12934 @ifclear vms
12935 @item make_cmd=COMMAND
12936 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12937 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12938 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12939 @end ifclear
12940 specifies the command used to recompile the whole application.
12942 @item run_cmd=COMMAND
12943 [default: @code{"$@{main@}"}]
12944 specifies the command used to run the application.
12946 @item debug_cmd=COMMAND
12947 [default: @code{"gdb $@{main@}"}]
12948 specifies the command used to debug the application
12950 @end table
12952 @noindent
12953 @command{gnatxref} and @command{gnatfind} only take into account the
12954 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12956 @node Regular Expressions in gnatfind and gnatxref
12957 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12959 @noindent
12960 As specified in the section about @command{gnatfind}, the pattern can be a
12961 regular expression. Actually, there are to set of regular expressions
12962 which are recognized by the program:
12964 @table @code
12965 @item globbing patterns
12966 These are the most usual regular expression. They are the same that you
12967 generally used in a Unix shell command line, or in a DOS session.
12969 Here is a more formal grammar:
12970 @smallexample
12971 @group
12972 @iftex
12973 @leftskip=.5cm
12974 @end iftex
12975 regexp ::= term
12976 term   ::= elmt            -- matches elmt
12977 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12978 term   ::= *               -- any string of 0 or more characters
12979 term   ::= ?               -- matches any character
12980 term   ::= [char @{char@}]   -- matches any character listed
12981 term   ::= [char - char]   -- matches any character in range
12982 @end group
12983 @end smallexample
12985 @item full regular expression
12986 The second set of regular expressions is much more powerful. This is the
12987 type of regular expressions recognized by utilities such a @file{grep}.
12989 The following is the form of a regular expression, expressed in Ada
12990 reference manual style BNF is as follows
12992 @smallexample
12993 @iftex
12994 @leftskip=.5cm
12995 @end iftex
12996 @group
12997 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12999 term ::= item @{item@}       -- concatenation (item then item)
13001 item ::= elmt              -- match elmt
13002 item ::= elmt *            -- zero or more elmt's
13003 item ::= elmt +            -- one or more elmt's
13004 item ::= elmt ?            -- matches elmt or nothing
13005 @end group
13006 @group
13007 elmt ::= nschar            -- matches given character
13008 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13009 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13010 elmt ::= [char - char]     -- matches chars in given range
13011 elmt ::= \ char            -- matches given character
13012 elmt ::= .                 -- matches any single character
13013 elmt ::= ( regexp )        -- parens used for grouping
13015 char ::= any character, including special characters
13016 nschar ::= any character except ()[].*+?^^^
13017 @end group
13018 @end smallexample
13020 Following are a few examples:
13022 @table @samp
13023 @item abcde|fghi
13024 will match any of the two strings @samp{abcde} and @samp{fghi},
13026 @item abc*d
13027 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13028 @samp{abcccd}, and so on,
13030 @item [a-z]+
13031 will match any string which has only lowercase characters in it (and at
13032 least one character.
13034 @end table
13035 @end table
13037 @node Examples of gnatxref Usage
13038 @section Examples of @code{gnatxref} Usage
13040 @subsection General Usage
13042 @noindent
13043 For the following examples, we will consider the following units:
13045 @smallexample @c ada
13046 @group
13047 @cartouche
13048 main.ads:
13049 1: with Bar;
13050 2: package Main is
13051 3:     procedure Foo (B : in Integer);
13052 4:     C : Integer;
13053 5: private
13054 6:     D : Integer;
13055 7: end Main;
13057 main.adb:
13058 1: package body Main is
13059 2:     procedure Foo (B : in Integer) is
13060 3:     begin
13061 4:        C := B;
13062 5:        D := B;
13063 6:        Bar.Print (B);
13064 7:        Bar.Print (C);
13065 8:     end Foo;
13066 9: end Main;
13068 bar.ads:
13069 1: package Bar is
13070 2:     procedure Print (B : Integer);
13071 3: end bar;
13072 @end cartouche
13073 @end group
13074 @end smallexample
13076 @table @code
13078 @noindent
13079 The first thing to do is to recompile your application (for instance, in
13080 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13081 the cross-referencing information.
13082 You can then issue any of the following commands:
13084 @item gnatxref main.adb
13085 @code{gnatxref} generates cross-reference information for main.adb
13086 and every unit 'with'ed by main.adb.
13088 The output would be:
13089 @smallexample
13090 @iftex
13091 @leftskip=0cm
13092 @end iftex
13093 B                                                      Type: Integer
13094   Decl: bar.ads           2:22
13095 B                                                      Type: Integer
13096   Decl: main.ads          3:20
13097   Body: main.adb          2:20
13098   Ref:  main.adb          4:13     5:13     6:19
13099 Bar                                                    Type: Unit
13100   Decl: bar.ads           1:9
13101   Ref:  main.adb          6:8      7:8
13102        main.ads           1:6
13103 C                                                      Type: Integer
13104   Decl: main.ads          4:5
13105   Modi: main.adb          4:8
13106   Ref:  main.adb          7:19
13107 D                                                      Type: Integer
13108   Decl: main.ads          6:5
13109   Modi: main.adb          5:8
13110 Foo                                                    Type: Unit
13111   Decl: main.ads          3:15
13112   Body: main.adb          2:15
13113 Main                                                    Type: Unit
13114   Decl: main.ads          2:9
13115   Body: main.adb          1:14
13116 Print                                                   Type: Unit
13117   Decl: bar.ads           2:15
13118   Ref:  main.adb          6:12     7:12
13119 @end smallexample
13121 @noindent
13122 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13123 its body is in main.adb, line 1, column 14 and is not referenced any where.
13125 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13126 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13128 @item gnatxref package1.adb package2.ads
13129 @code{gnatxref} will generates cross-reference information for
13130 package1.adb, package2.ads and any other package 'with'ed by any
13131 of these.
13133 @end table
13135 @ifclear vms
13136 @subsection Using gnatxref with vi
13138 @code{gnatxref} can generate a tags file output, which can be used
13139 directly from @command{vi}. Note that the standard version of @command{vi}
13140 will not work properly with overloaded symbols. Consider using another
13141 free implementation of @command{vi}, such as @command{vim}.
13143 @smallexample
13144 $ gnatxref -v gnatfind.adb > tags
13145 @end smallexample
13147 @noindent
13148 will generate the tags file for @code{gnatfind} itself (if the sources
13149 are in the search path!).
13151 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13152 (replacing @var{entity} by whatever you are looking for), and vi will
13153 display a new file with the corresponding declaration of entity.
13154 @end ifclear
13156 @node Examples of gnatfind Usage
13157 @section Examples of @code{gnatfind} Usage
13159 @table @code
13161 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13162 Find declarations for all entities xyz referenced at least once in
13163 main.adb. The references are search in every library file in the search
13164 path.
13166 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13167 switch is set)
13169 The output will look like:
13170 @smallexample
13171 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13172 ^directory/^[directory]^main.adb:24:10: xyz <= body
13173 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13174 @end smallexample
13176 @noindent
13177 that is to say, one of the entities xyz found in main.adb is declared at
13178 line 12 of main.ads (and its body is in main.adb), and another one is
13179 declared at line 45 of foo.ads
13181 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13182 This is the same command as the previous one, instead @code{gnatfind} will
13183 display the content of the Ada source file lines.
13185 The output will look like:
13187 @smallexample
13188 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13189    procedure xyz;
13190 ^directory/^[directory]^main.adb:24:10: xyz <= body
13191    procedure xyz is
13192 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13193    xyz : Integer;
13194 @end smallexample
13196 @noindent
13197 This can make it easier to find exactly the location your are looking
13198 for.
13200 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13201 Find references to all entities containing an x that are
13202 referenced on line 123 of main.ads.
13203 The references will be searched only in main.ads and foo.adb.
13205 @item gnatfind main.ads:123
13206 Find declarations and bodies for all entities that are referenced on
13207 line 123 of main.ads.
13209 This is the same as @code{gnatfind "*":main.adb:123}.
13211 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13212 Find the declaration for the entity referenced at column 45 in
13213 line 123 of file main.adb in directory mydir. Note that it
13214 is usual to omit the identifier name when the column is given,
13215 since the column position identifies a unique reference.
13217 The column has to be the beginning of the identifier, and should not
13218 point to any character in the middle of the identifier.
13220 @end table
13222 @c *********************************
13223 @node The GNAT Pretty-Printer gnatpp
13224 @chapter The GNAT Pretty-Printer @command{gnatpp}
13225 @findex gnatpp
13226 @cindex Pretty-Printer
13228 @noindent
13229 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13230 for source reformatting / pretty-printing.
13231 It takes an Ada source file as input and generates a reformatted
13232 version as output.
13233 You can specify various style directives via switches; e.g.,
13234 identifier case conventions, rules of indentation, and comment layout.
13236 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13237 tree for the input source and thus requires the input to be syntactically and
13238 semantically legal.
13239 If this condition is not met, @command{gnatpp} will terminate with an
13240 error message; no output file will be generated.
13242 @command{gnatpp} cannot process sources that contain
13243 preprocessing directives.
13245 If the compilation unit
13246 contained in the input source depends semantically upon units located
13247 outside the current directory, you have to provide the source search path
13248 when invoking @command{gnatpp}, if these units are contained in files with
13249 names that do not follow the GNAT file naming rules, you have to provide
13250 the configuration file describing the corresponding naming scheme;
13251 see the description of the @command{gnatpp}
13252 switches below. Another possibility is to use a project file and to
13253 call @command{gnatpp} through the @command{gnat} driver
13254 (see @ref{The GNAT Driver and Project Files}).
13256 The @command{gnatpp} command has the form
13258 @smallexample
13259 @c $ gnatpp @ovar{switches} @var{filename}
13260 @c Expanding @ovar macro inline (explanation in macro def comments)
13261 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13262 @end smallexample
13264 @noindent
13265 where
13266 @itemize @bullet
13267 @item
13268 @var{switches} is an optional sequence of switches defining such properties as
13269 the formatting rules, the source search path, and the destination for the
13270 output source file
13272 @item
13273 @var{filename} is the name (including the extension) of the source file to
13274 reformat; ``wildcards'' or several file names on the same gnatpp command are
13275 allowed.  The file name may contain path information; it does not have to
13276 follow the GNAT file naming rules
13278 @item
13279 @samp{@var{gcc_switches}} is a list of switches for
13280 @command{gcc}. They will be passed on to all compiler invocations made by
13281 @command{gnatelim} to generate the ASIS trees. Here you can provide
13282 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13283 use the @option{-gnatec} switch to set the configuration file,
13284 use the @option{-gnat05} switch if sources should be compiled in
13285 Ada 2005 mode  etc.
13286 @end itemize
13288 @menu
13289 * Switches for gnatpp::
13290 * Formatting Rules::
13291 @end menu
13293 @node Switches for gnatpp
13294 @section Switches for @command{gnatpp}
13296 @noindent
13297 The following subsections describe the various switches accepted by
13298 @command{gnatpp}, organized by category.
13300 @ifclear vms
13301 You specify a switch by supplying a name and generally also a value.
13302 In many cases the values for a switch with a given name are incompatible with
13303 each other
13304 (for example the switch that controls the casing of a reserved word may have
13305 exactly one value: upper case, lower case, or
13306 mixed case) and thus exactly one such switch can be in effect for an
13307 invocation of @command{gnatpp}.
13308 If more than one is supplied, the last one is used.
13309 However, some values for the same switch are mutually compatible.
13310 You may supply several such switches to @command{gnatpp}, but then
13311 each must be specified in full, with both the name and the value.
13312 Abbreviated forms (the name appearing once, followed by each value) are
13313 not permitted.
13314 For example, to set
13315 the alignment of the assignment delimiter both in declarations and in
13316 assignment statements, you must write @option{-A2A3}
13317 (or @option{-A2 -A3}), but not @option{-A23}.
13318 @end ifclear
13320 @ifset vms
13321 In many cases the set of options for a given qualifier are incompatible with
13322 each other (for example the qualifier that controls the casing of a reserved
13323 word may have exactly one option, which specifies either upper case, lower
13324 case, or mixed case), and thus exactly one such option can be in effect for
13325 an invocation of @command{gnatpp}.
13326 If more than one is supplied, the last one is used.
13327 However, some qualifiers have options that are mutually compatible,
13328 and then you may then supply several such options when invoking
13329 @command{gnatpp}.
13330 @end ifset
13332 In most cases, it is obvious whether or not the
13333 ^values for a switch with a given name^options for a given qualifier^
13334 are compatible with each other.
13335 When the semantics might not be evident, the summaries below explicitly
13336 indicate the effect.
13338 @menu
13339 * Alignment Control::
13340 * Casing Control::
13341 * Construct Layout Control::
13342 * General Text Layout Control::
13343 * Other Formatting Options::
13344 * Setting the Source Search Path::
13345 * Output File Control::
13346 * Other gnatpp Switches::
13347 @end menu
13349 @node Alignment Control
13350 @subsection Alignment Control
13351 @cindex Alignment control in @command{gnatpp}
13353 @noindent
13354 Programs can be easier to read if certain constructs are vertically aligned.
13355 By default all alignments are set ON.
13356 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13357 OFF, and then use one or more of the other
13358 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13359 to activate alignment for specific constructs.
13361 @table @option
13362 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13364 @ifset vms
13365 @item /ALIGN=ON
13366 Set all alignments to ON
13367 @end ifset
13369 @item ^-A0^/ALIGN=OFF^
13370 Set all alignments to OFF
13372 @item ^-A1^/ALIGN=COLONS^
13373 Align @code{:} in declarations
13375 @item ^-A2^/ALIGN=DECLARATIONS^
13376 Align @code{:=} in initializations in declarations
13378 @item ^-A3^/ALIGN=STATEMENTS^
13379 Align @code{:=} in assignment statements
13381 @item ^-A4^/ALIGN=ARROWS^
13382 Align @code{=>} in associations
13384 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13385 Align @code{at} keywords in the component clauses in record
13386 representation clauses
13387 @end table
13389 @noindent
13390 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13391 is allowed.
13393 @node Casing Control
13394 @subsection Casing Control
13395 @cindex Casing control in @command{gnatpp}
13397 @noindent
13398 @command{gnatpp} allows you to specify the casing for reserved words,
13399 pragma names, attribute designators and identifiers.
13400 For identifiers you may define a
13401 general rule for name casing but also override this rule
13402 via a set of dictionary files.
13404 Three types of casing are supported: lower case, upper case, and mixed case.
13405 Lower and upper case are self-explanatory (but since some letters in
13406 Latin1 and other GNAT-supported character sets
13407 exist only in lower-case form, an upper case conversion will have no
13408 effect on them.)
13409 ``Mixed case'' means that the first letter, and also each letter immediately
13410 following an underscore, are converted to their uppercase forms;
13411 all the other letters are converted to their lowercase forms.
13413 @table @option
13414 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13415 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13416 Attribute designators are lower case
13418 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13419 Attribute designators are upper case
13421 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13422 Attribute designators are mixed case (this is the default)
13424 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13425 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13426 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13427 lower case (this is the default)
13429 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13430 Keywords are upper case
13432 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13433 @item ^-nD^/NAME_CASING=AS_DECLARED^
13434 Name casing for defining occurrences are as they appear in the source file
13435 (this is the default)
13437 @item ^-nU^/NAME_CASING=UPPER_CASE^
13438 Names are in upper case
13440 @item ^-nL^/NAME_CASING=LOWER_CASE^
13441 Names are in lower case
13443 @item ^-nM^/NAME_CASING=MIXED_CASE^
13444 Names are in mixed case
13446 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13447 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13448 Enumeration literal casing for defining occurrences are as they appear in the
13449 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13451 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13452 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13453 setting.
13455 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13456 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13457 setting.
13459 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13460 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13461 setting.
13463 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13464 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13465 Names introduced by type and subtype declarations are always
13466 cased as they appear in the declaration in the source file.
13467 Overrides ^-n^/NAME_CASING^ casing setting.
13469 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13470 Names introduced by type and subtype declarations are always in
13471 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13473 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13474 Names introduced by type and subtype declarations are always in
13475 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13477 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13478 Names introduced by type and subtype declarations are always in
13479 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13481 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
13482 Names introduced by number declarations are always in
13483 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13485 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
13486 Names introduced by number declarations are always in
13487 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13489 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
13490 Names introduced by number declarations are always in
13491 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13493 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13494 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13495 Pragma names are lower case
13497 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13498 Pragma names are upper case
13500 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13501 Pragma names are mixed case (this is the default)
13503 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13504 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13505 Use @var{file} as a @emph{dictionary file} that defines
13506 the casing for a set of specified names,
13507 thereby overriding the effect on these names by
13508 any explicit or implicit
13509 ^-n^/NAME_CASING^ switch.
13510 To supply more than one dictionary file,
13511 use ^several @option{-D} switches^a list of files as options^.
13513 @noindent
13514 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13515 to define the casing for the Ada predefined names and
13516 the names declared in the GNAT libraries.
13518 @item ^-D-^/SPECIFIC_CASING^
13519 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13520 Do not use the default dictionary file;
13521 instead, use the casing
13522 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13523 dictionary file(s)
13524 @end table
13526 @noindent
13527 The structure of a dictionary file, and details on the conventions
13528 used in the default dictionary file, are defined in @ref{Name Casing}.
13530 The @option{^-D-^/SPECIFIC_CASING^} and
13531 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13532 compatible.
13534 @node Construct Layout Control
13535 @subsection Construct Layout Control
13536 @cindex Layout control in @command{gnatpp}
13538 @noindent
13539 This group of @command{gnatpp} switches controls the layout of comments and
13540 complex syntactic constructs.  See @ref{Formatting Comments} for details
13541 on their effect.
13543 @table @option
13544 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13545 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13546 All the comments remain unchanged
13548 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13549 GNAT-style comment line indentation (this is the default).
13551 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13552 Reference-manual comment line indentation.
13554 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13555 GNAT-style comment beginning
13557 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13558 Reformat comment blocks
13560 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13561 Keep unchanged special form comments
13563 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13564 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13565 GNAT-style layout (this is the default)
13567 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13568 Compact layout
13570 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13571 Uncompact layout
13573 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13574 @item ^-N^/NOTABS^
13575 All the VT characters are removed from the comment text. All the HT characters
13576 are expanded with the sequences of space characters to get to the next tab
13577 stops.
13579 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13580 @item ^--no-separate-is^/NO_SEPARATE_IS^
13581 Do not place the keyword @code{is} on a separate line in a subprogram body in
13582 case if the spec occupies more than one line.
13584 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13585 @item ^--separate-label^/SEPARATE_LABEL^
13586 Place statement label(s) on a separate line, with the following statement
13587 on the next line.
13589 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13590 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13591 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13592 keyword @code{then} in IF statements on a separate line.
13594 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13595 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13596 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13597 keyword @code{then} in IF statements on a separate line. This option is
13598 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13600 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13601 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13602 Start each USE clause in a context clause from a separate line.
13604 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13605 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13606 Use a separate line for a loop or block statement name, but do not use an extra
13607 indentation level for the statement itself.
13609 @end table
13611 @ifclear vms
13612 @noindent
13613 The @option{-c1} and @option{-c2} switches are incompatible.
13614 The @option{-c3} and @option{-c4} switches are compatible with each other and
13615 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13616 the other comment formatting switches.
13618 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13619 @end ifclear
13621 @ifset vms
13622 @noindent
13623 For the @option{/COMMENTS_LAYOUT} qualifier:
13624 @itemize @bullet
13625 @item
13626 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13627 @item
13628 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13629 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13630 @end itemize
13632 @noindent
13633 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13634 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13635 @end ifset
13637 @node General Text Layout Control
13638 @subsection General Text Layout Control
13640 @noindent
13641 These switches allow control over line length and indentation.
13643 @table @option
13644 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13645 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13646 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13648 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13649 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13650 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13652 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13653 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13654 Indentation level for continuation lines (relative to the line being
13655 continued), @var{nnn} from 1@dots{}9.
13656 The default
13657 value is one less than the (normal) indentation level, unless the
13658 indentation is set to 1 (in which case the default value for continuation
13659 line indentation is also 1)
13660 @end table
13662 @node Other Formatting Options
13663 @subsection Other Formatting Options
13665 @noindent
13666 These switches control the inclusion of missing end/exit labels, and
13667 the indentation level in @b{case} statements.
13669 @table @option
13670 @item ^-e^/NO_MISSED_LABELS^
13671 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13672 Do not insert missing end/exit labels. An end label is the name of
13673 a construct that may optionally be repeated at the end of the
13674 construct's declaration;
13675 e.g., the names of packages, subprograms, and tasks.
13676 An exit label is the name of a loop that may appear as target
13677 of an exit statement within the loop.
13678 By default, @command{gnatpp} inserts these end/exit labels when
13679 they are absent from the original source. This option suppresses such
13680 insertion, so that the formatted source reflects the original.
13682 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13683 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13684 Insert a Form Feed character after a pragma Page.
13686 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13687 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13688 Do not use an additional indentation level for @b{case} alternatives
13689 and variants if there are @var{nnn} or more (the default
13690 value is 10).
13691 If @var{nnn} is 0, an additional indentation level is
13692 used for @b{case} alternatives and variants regardless of their number.
13694 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
13695 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
13696 If the number of parameter associations is greater than @var{nnn} and if at
13697 least one association uses named notation, start each association from
13698 a new line. If @var{nnn} is 0, no check for the number of associations
13699 is made, this is the default.
13701 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
13702 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
13703 If the number of parameter specifications is greater than @var{nnn}
13704 (or equal to @var{nnn} in case of a function), start each specification from
13705 a new line. The default for @var{nnn} is 3.
13706 @end table
13708 @node Setting the Source Search Path
13709 @subsection Setting the Source Search Path
13711 @noindent
13712 To define the search path for the input source file, @command{gnatpp}
13713 uses the same switches as the GNAT compiler, with the same effects.
13715 @table @option
13716 @item ^-I^/SEARCH=^@var{dir}
13717 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13718 The same as the corresponding gcc switch
13720 @item ^-I-^/NOCURRENT_DIRECTORY^
13721 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13722 The same as the corresponding gcc switch
13724 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13725 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13726 The same as the corresponding gcc switch
13728 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13729 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13730 The same as the corresponding gcc switch
13732 @end table
13734 @node Output File Control
13735 @subsection Output File Control
13737 @noindent
13738 By default the output is sent to the file whose name is obtained by appending
13739 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13740 (if the file with this name already exists, it is unconditionally overwritten).
13741 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13742 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13743 as output file.
13744 The output may be redirected by the following switches:
13746 @table @option
13747 @item ^-pipe^/STANDARD_OUTPUT^
13748 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13749 Send the output to @code{Standard_Output}
13751 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13752 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13753 Write the output into @var{output_file}.
13754 If @var{output_file} already exists, @command{gnatpp} terminates without
13755 reading or processing the input file.
13757 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13758 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13759 Write the output into @var{output_file}, overwriting the existing file
13760 (if one is present).
13762 @item ^-r^/REPLACE^
13763 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13764 Replace the input source file with the reformatted output, and copy the
13765 original input source into the file whose name is obtained by appending the
13766 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13767 If a file with this name already exists, @command{gnatpp} terminates without
13768 reading or processing the input file.
13770 @item ^-rf^/OVERRIDING_REPLACE^
13771 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13772 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13773 already exists, it is overwritten.
13775 @item ^-rnb^/REPLACE_NO_BACKUP^
13776 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13777 Replace the input source file with the reformatted output without
13778 creating any backup copy of the input source.
13780 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13781 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13782 Specifies the format of the reformatted output file. The @var{xxx}
13783 ^string specified with the switch^option^ may be either
13784 @itemize @bullet
13785 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13786 @item ``@option{^crlf^CRLF^}''
13787 the same as @option{^crlf^CRLF^}
13788 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13789 @item ``@option{^lf^LF^}''
13790 the same as @option{^unix^UNIX^}
13791 @end itemize
13793 @item ^-W^/RESULT_ENCODING=^@var{e}
13794 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13795 Specify the wide character encoding method used to write the code in the
13796 result file
13797 @var{e} is one of the following:
13799 @itemize @bullet
13801 @item ^h^HEX^
13802 Hex encoding
13804 @item ^u^UPPER^
13805 Upper half encoding
13807 @item ^s^SHIFT_JIS^
13808 Shift/JIS encoding
13810 @item ^e^EUC^
13811 EUC encoding
13813 @item ^8^UTF8^
13814 UTF-8 encoding
13816 @item ^b^BRACKETS^
13817 Brackets encoding (default value)
13818 @end itemize
13820 @end table
13822 @noindent
13823 Options @option{^-pipe^/STANDARD_OUTPUT^},
13824 @option{^-o^/OUTPUT^} and
13825 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13826 contains only one file to reformat.
13827 Option
13828 @option{^--eol^/END_OF_LINE^}
13830 @option{^-W^/RESULT_ENCODING^}
13831 cannot be used together
13832 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13834 @node Other gnatpp Switches
13835 @subsection Other @code{gnatpp} Switches
13837 @noindent
13838 The additional @command{gnatpp} switches are defined in this subsection.
13840 @table @option
13841 @item ^-files @var{filename}^/FILES=@var{filename}^
13842 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13843 Take the argument source files from the specified file. This file should be an
13844 ordinary text file containing file names separated by spaces or
13845 line breaks. You can use this switch more than once in the same call to
13846 @command{gnatpp}. You also can combine this switch with an explicit list of
13847 files.
13849 @item ^-v^/VERBOSE^
13850 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13851 Verbose mode;
13852 @command{gnatpp} generates version information and then
13853 a trace of the actions it takes to produce or obtain the ASIS tree.
13855 @item ^-w^/WARNINGS^
13856 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13857 Warning mode;
13858 @command{gnatpp} generates a warning whenever it cannot provide
13859 a required layout in the result source.
13860 @end table
13862 @node Formatting Rules
13863 @section Formatting Rules
13865 @noindent
13866 The following subsections show how @command{gnatpp} treats ``white space'',
13867 comments, program layout, and name casing.
13868 They provide the detailed descriptions of the switches shown above.
13870 @menu
13871 * White Space and Empty Lines::
13872 * Formatting Comments::
13873 * Construct Layout::
13874 * Name Casing::
13875 @end menu
13877 @node White Space and Empty Lines
13878 @subsection White Space and Empty Lines
13880 @noindent
13881 @command{gnatpp} does not have an option to control space characters.
13882 It will add or remove spaces according to the style illustrated by the
13883 examples in the @cite{Ada Reference Manual}.
13885 The only format effectors
13886 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13887 that will appear in the output file are platform-specific line breaks,
13888 and also format effectors within (but not at the end of) comments.
13889 In particular, each horizontal tab character that is not inside
13890 a comment will be treated as a space and thus will appear in the
13891 output file as zero or more spaces depending on
13892 the reformatting of the line in which it appears.
13893 The only exception is a Form Feed character, which is inserted after a
13894 pragma @code{Page} when @option{-ff} is set.
13896 The output file will contain no lines with trailing ``white space'' (spaces,
13897 format effectors).
13899 Empty lines in the original source are preserved
13900 only if they separate declarations or statements.
13901 In such contexts, a
13902 sequence of two or more empty lines is replaced by exactly one empty line.
13903 Note that a blank line will be removed if it separates two ``comment blocks''
13904 (a comment block is a sequence of whole-line comments).
13905 In order to preserve a visual separation between comment blocks, use an
13906 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13907 Likewise, if for some reason you wish to have a sequence of empty lines,
13908 use a sequence of empty comments instead.
13910 @node Formatting Comments
13911 @subsection Formatting Comments
13913 @noindent
13914 Comments in Ada code are of two kinds:
13915 @itemize @bullet
13916 @item
13917 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13918 ``white space'') on a line
13920 @item
13921 an @emph{end-of-line comment}, which follows some other Ada lexical element
13922 on the same line.
13923 @end itemize
13925 @noindent
13926 The indentation of a whole-line comment is that of either
13927 the preceding or following line in
13928 the formatted source, depending on switch settings as will be described below.
13930 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13931 between the end of the preceding Ada lexical element and the beginning
13932 of the comment as appear in the original source,
13933 unless either the comment has to be split to
13934 satisfy the line length limitation, or else the next line contains a
13935 whole line comment that is considered a continuation of this end-of-line
13936 comment (because it starts at the same position).
13937 In the latter two
13938 cases, the start of the end-of-line comment is moved right to the nearest
13939 multiple of the indentation level.
13940 This may result in a ``line overflow'' (the right-shifted comment extending
13941 beyond the maximum line length), in which case the comment is split as
13942 described below.
13944 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13945 (GNAT-style comment line indentation)
13946 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13947 (reference-manual comment line indentation).
13948 With reference-manual style, a whole-line comment is indented as if it
13949 were a declaration or statement at the same place
13950 (i.e., according to the indentation of the preceding line(s)).
13951 With GNAT style, a whole-line comment that is immediately followed by an
13952 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13953 word @b{begin}, is indented based on the construct that follows it.
13955 For example:
13956 @smallexample @c ada
13957 @cartouche
13958 if A then
13959     null;
13960        -- some comment
13961 else
13962    null;
13963 end if;
13964 @end cartouche
13965 @end smallexample
13967 @noindent
13968 Reference-manual indentation produces:
13970 @smallexample @c ada
13971 @cartouche
13972 if A then
13973    null;
13974    --  some comment
13975 else
13976    null;
13977 end if;
13978 @end cartouche
13979 @end smallexample
13981 @noindent
13982 while GNAT-style indentation produces:
13984 @smallexample @c ada
13985 @cartouche
13986 if A then
13987    null;
13988 --  some comment
13989 else
13990    null;
13991 end if;
13992 @end cartouche
13993 @end smallexample
13995 @noindent
13996 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13997 (GNAT style comment beginning) has the following
13998 effect:
14000 @itemize @bullet
14001 @item
14002 For each whole-line comment that does not end with two hyphens,
14003 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14004 to ensure that there are at least two spaces between these hyphens and the
14005 first non-blank character of the comment.
14006 @end itemize
14008 @noindent
14009 For an end-of-line comment, if in the original source the next line is a
14010 whole-line comment that starts at the same position
14011 as the end-of-line comment,
14012 then the whole-line comment (and all whole-line comments
14013 that follow it and that start at the same position)
14014 will start at this position in the output file.
14016 @noindent
14017 That is, if in the original source we have:
14019 @smallexample @c ada
14020 @cartouche
14021 begin
14022 A := B + C;            --  B must be in the range Low1..High1
14023                        --  C must be in the range Low2..High2
14024              --B+C will be in the range Low1+Low2..High1+High2
14025 X := X + 1;
14026 @end cartouche
14027 @end smallexample
14029 @noindent
14030 Then in the formatted source we get
14032 @smallexample @c ada
14033 @cartouche
14034 begin
14035    A := B + C;            --  B must be in the range Low1..High1
14036                           --  C must be in the range Low2..High2
14037    --  B+C will be in the range Low1+Low2..High1+High2
14038    X := X + 1;
14039 @end cartouche
14040 @end smallexample
14042 @noindent
14043 A comment that exceeds the line length limit will be split.
14044 Unless switch
14045 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14046 the line belongs to a reformattable block, splitting the line generates a
14047 @command{gnatpp} warning.
14048 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14049 comments may be reformatted in typical
14050 word processor style (that is, moving words between lines and putting as
14051 many words in a line as possible).
14053 @noindent
14054 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14055 that has a special format (that is, a character that is neither a letter nor digit
14056 not white space nor line break immediately following the leading @code{--} of
14057 the comment) should be without any change moved from the argument source
14058 into reformatted source. This switch allows to preserve comments that are used
14059 as a special marks in the code (e.g.@: SPARK annotation).
14061 @node Construct Layout
14062 @subsection Construct Layout
14064 @noindent
14065 In several cases the suggested layout in the Ada Reference Manual includes
14066 an extra level of indentation that many programmers prefer to avoid. The
14067 affected cases include:
14069 @itemize @bullet
14071 @item Record type declaration (RM 3.8)
14073 @item Record representation clause (RM 13.5.1)
14075 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14077 @item Block statement in case if a block has a statement identifier (RM 5.6)
14078 @end itemize
14080 @noindent
14081 In compact mode (when GNAT style layout or compact layout is set),
14082 the pretty printer uses one level of indentation instead
14083 of two. This is achieved in the record definition and record representation
14084 clause cases by putting the @code{record} keyword on the same line as the
14085 start of the declaration or representation clause, and in the block and loop
14086 case by putting the block or loop header on the same line as the statement
14087 identifier.
14089 @noindent
14090 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14091 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14092 layout on the one hand, and uncompact layout
14093 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14094 can be illustrated by the following examples:
14096 @iftex
14097 @cartouche
14098 @multitable @columnfractions .5 .5
14099 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14101 @item
14102 @smallexample @c ada
14103 type q is record
14104    a : integer;
14105    b : integer;
14106 end record;
14107 @end smallexample
14108 @tab
14109 @smallexample @c ada
14110 type q is
14111    record
14112       a : integer;
14113       b : integer;
14114    end record;
14115 @end smallexample
14117 @item
14118 @smallexample @c ada
14119 for q use record
14120    a at 0 range  0 .. 31;
14121    b at 4 range  0 .. 31;
14122 end record;
14123 @end smallexample
14124 @tab
14125 @smallexample @c ada
14126 for q use
14127    record
14128       a at 0 range  0 .. 31;
14129       b at 4 range  0 .. 31;
14130    end record;
14131 @end smallexample
14133 @item
14134 @smallexample @c ada
14135 Block : declare
14136    A : Integer := 3;
14137 begin
14138    Proc (A, A);
14139 end Block;
14140 @end smallexample
14141 @tab
14142 @smallexample @c ada
14143 Block :
14144    declare
14145       A : Integer := 3;
14146    begin
14147       Proc (A, A);
14148    end Block;
14149 @end smallexample
14151 @item
14152 @smallexample @c ada
14153 Clear : for J in 1 .. 10 loop
14154    A (J) := 0;
14155 end loop Clear;
14156 @end smallexample
14157 @tab
14158 @smallexample @c ada
14159 Clear :
14160    for J in 1 .. 10 loop
14161       A (J) := 0;
14162    end loop Clear;
14163 @end smallexample
14164 @end multitable
14165 @end cartouche
14166 @end iftex
14168 @ifnottex
14169 @smallexample
14170 @cartouche
14171 GNAT style, compact layout              Uncompact layout
14173 type q is record                        type q is
14174    a : integer;                            record
14175    b : integer;                               a : integer;
14176 end record;                                   b : integer;
14177                                            end record;
14179 for q use record                        for q use
14180    a at 0 range  0 .. 31;                  record
14181    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
14182 end record;                                   b at 4 range  0 .. 31;
14183                                            end record;
14185 Block : declare                         Block :
14186    A : Integer := 3;                       declare
14187 begin                                         A : Integer := 3;
14188    Proc (A, A);                            begin
14189 end Block;                                    Proc (A, A);
14190                                            end Block;
14192 Clear : for J in 1 .. 10 loop           Clear :
14193    A (J) := 0;                             for J in 1 .. 10 loop
14194 end loop Clear;                               A (J) := 0;
14195                                            end loop Clear;
14196 @end cartouche
14197 @end smallexample
14198 @end ifnottex
14200 @noindent
14201 A further difference between GNAT style layout and compact layout is that
14202 GNAT style layout inserts empty lines as separation for
14203 compound statements, return statements and bodies.
14205 Note that the layout specified by
14206 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14207 for named block and loop statements overrides the layout defined by these
14208 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14209 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14210 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14212 @node Name Casing
14213 @subsection Name Casing
14215 @noindent
14216 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14217 the same casing as the corresponding defining identifier.
14219 You control the casing for defining occurrences via the
14220 @option{^-n^/NAME_CASING^} switch.
14221 @ifclear vms
14222 With @option{-nD} (``as declared'', which is the default),
14223 @end ifclear
14224 @ifset vms
14225 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14226 @end ifset
14227 defining occurrences appear exactly as in the source file
14228 where they are declared.
14229 The other ^values for this switch^options for this qualifier^ ---
14230 @option{^-nU^UPPER_CASE^},
14231 @option{^-nL^LOWER_CASE^},
14232 @option{^-nM^MIXED_CASE^} ---
14233 result in
14234 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14235 If @command{gnatpp} changes the casing of a defining
14236 occurrence, it analogously changes the casing of all the
14237 usage occurrences of this name.
14239 If the defining occurrence of a name is not in the source compilation unit
14240 currently being processed by @command{gnatpp}, the casing of each reference to
14241 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14242 switch (subject to the dictionary file mechanism described below).
14243 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14244 had affected the
14245 casing for the defining occurrence of the name.
14247 Some names may need to be spelled with casing conventions that are not
14248 covered by the upper-, lower-, and mixed-case transformations.
14249 You can arrange correct casing by placing such names in a
14250 @emph{dictionary file},
14251 and then supplying a @option{^-D^/DICTIONARY^} switch.
14252 The casing of names from dictionary files overrides
14253 any @option{^-n^/NAME_CASING^} switch.
14255 To handle the casing of Ada predefined names and the names from GNAT libraries,
14256 @command{gnatpp} assumes a default dictionary file.
14257 The name of each predefined entity is spelled with the same casing as is used
14258 for the entity in the @cite{Ada Reference Manual}.
14259 The name of each entity in the GNAT libraries is spelled with the same casing
14260 as is used in the declaration of that entity.
14262 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14263 default dictionary file.
14264 Instead, the casing for predefined and GNAT-defined names will be established
14265 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14266 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14267 will appear as just shown,
14268 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14269 To ensure that even such names are rendered in uppercase,
14270 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14271 (or else, less conveniently, place these names in upper case in a dictionary
14272 file).
14274 A dictionary file is
14275 a plain text file; each line in this file can be either a blank line
14276 (containing only space characters and ASCII.HT characters), an Ada comment
14277 line, or the specification of exactly one @emph{casing schema}.
14279 A casing schema is a string that has the following syntax:
14281 @smallexample
14282 @cartouche
14283   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14285   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14286 @end cartouche
14287 @end smallexample
14289 @noindent
14290 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14291 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14293 The casing schema string can be followed by white space and/or an Ada-style
14294 comment; any amount of white space is allowed before the string.
14296 If a dictionary file is passed as
14297 @ifclear vms
14298 the value of a @option{-D@var{file}} switch
14299 @end ifclear
14300 @ifset vms
14301 an option to the @option{/DICTIONARY} qualifier
14302 @end ifset
14303 then for every
14304 simple name and every identifier, @command{gnatpp} checks if the dictionary
14305 defines the casing for the name or for some of its parts (the term ``subword''
14306 is used below to denote the part of a name which is delimited by ``_'' or by
14307 the beginning or end of the word and which does not contain any ``_'' inside):
14309 @itemize @bullet
14310 @item
14311 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14312 the casing defined by the dictionary; no subwords are checked for this word
14314 @item
14315 for every subword @command{gnatpp} checks if the dictionary contains the
14316 corresponding string of the form @code{*@var{simple_identifier}*},
14317 and if it does, the casing of this @var{simple_identifier} is used
14318 for this subword
14320 @item
14321 if the whole name does not contain any ``_'' inside, and if for this name
14322 the dictionary contains two entries - one of the form @var{identifier},
14323 and another - of the form *@var{simple_identifier}*, then the first one
14324 is applied to define the casing of this name
14326 @item
14327 if more than one dictionary file is passed as @command{gnatpp} switches, each
14328 dictionary adds new casing exceptions and overrides all the existing casing
14329 exceptions set by the previous dictionaries
14331 @item
14332 when @command{gnatpp} checks if the word or subword is in the dictionary,
14333 this check is not case sensitive
14334 @end itemize
14336 @noindent
14337 For example, suppose we have the following source to reformat:
14339 @smallexample @c ada
14340 @cartouche
14341 procedure test is
14342    name1 : integer := 1;
14343    name4_name3_name2 : integer := 2;
14344    name2_name3_name4 : Boolean;
14345    name1_var : Float;
14346 begin
14347    name2_name3_name4 := name4_name3_name2 > name1;
14348 end;
14349 @end cartouche
14350 @end smallexample
14352 @noindent
14353 And suppose we have two dictionaries:
14355 @smallexample
14356 @cartouche
14357 @i{dict1:}
14358    NAME1
14359    *NaMe3*
14360    *Name1*
14361 @end cartouche
14363 @cartouche
14364 @i{dict2:}
14365   *NAME3*
14366 @end cartouche
14367 @end smallexample
14369 @noindent
14370 If @command{gnatpp} is called with the following switches:
14372 @smallexample
14373 @ifclear vms
14374 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14375 @end ifclear
14376 @ifset vms
14377 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14378 @end ifset
14379 @end smallexample
14381 @noindent
14382 then we will get the following name casing in the @command{gnatpp} output:
14384 @smallexample @c ada
14385 @cartouche
14386 procedure Test is
14387    NAME1             : Integer := 1;
14388    Name4_NAME3_Name2 : Integer := 2;
14389    Name2_NAME3_Name4 : Boolean;
14390    Name1_Var         : Float;
14391 begin
14392    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14393 end Test;
14394 @end cartouche
14395 @end smallexample
14397 @c *********************************
14398 @node The GNAT Metric Tool gnatmetric
14399 @chapter The GNAT Metric Tool @command{gnatmetric}
14400 @findex gnatmetric
14401 @cindex Metric tool
14403 @noindent
14404 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14405 for computing various program metrics.
14406 It takes an Ada source file as input and generates a file containing the
14407 metrics data as output. Various switches control which
14408 metrics are computed and output.
14410 @command{gnatmetric} generates and uses the ASIS
14411 tree for the input source and thus requires the input to be syntactically and
14412 semantically legal.
14413 If this condition is not met, @command{gnatmetric} will generate
14414 an error message; no metric information for this file will be
14415 computed and reported.
14417 If the compilation unit contained in the input source depends semantically
14418 upon units in files located outside the current directory, you have to provide
14419 the source search path when invoking @command{gnatmetric}.
14420 If it depends semantically upon units that are contained
14421 in files with names that do not follow the GNAT file naming rules, you have to
14422 provide the configuration file describing the corresponding naming scheme (see
14423 the description of the @command{gnatmetric} switches below.)
14424 Alternatively, you may use a project file and invoke @command{gnatmetric}
14425 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14427 The @command{gnatmetric} command has the form
14429 @smallexample
14430 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14431 @c Expanding @ovar macro inline (explanation in macro def comments)
14432 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14433 @end smallexample
14435 @noindent
14436 where
14437 @itemize @bullet
14438 @item
14439 @var{switches} specify the metrics to compute and define the destination for
14440 the output
14442 @item
14443 Each @var{filename} is the name (including the extension) of a source
14444 file to process. ``Wildcards'' are allowed, and
14445 the file name may contain path information.
14446 If no @var{filename} is supplied, then the @var{switches} list must contain
14447 at least one
14448 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14449 Including both a @option{-files} switch and one or more
14450 @var{filename} arguments is permitted.
14452 @item
14453 @samp{@var{gcc_switches}} is a list of switches for
14454 @command{gcc}. They will be passed on to all compiler invocations made by
14455 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14456 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14457 and use the @option{-gnatec} switch to set the configuration file,
14458 use the @option{-gnat05} switch if sources should be compiled in
14459 Ada 2005 mode etc.
14460 @end itemize
14462 @menu
14463 * Switches for gnatmetric::
14464 @end menu
14466 @node Switches for gnatmetric
14467 @section Switches for @command{gnatmetric}
14469 @noindent
14470 The following subsections describe the various switches accepted by
14471 @command{gnatmetric}, organized by category.
14473 @menu
14474 * Output Files Control::
14475 * Disable Metrics For Local Units::
14476 * Specifying a set of metrics to compute::
14477 * Other gnatmetric Switches::
14478 * Generate project-wide metrics::
14479 @end menu
14481 @node Output Files Control
14482 @subsection Output File Control
14483 @cindex Output file control in @command{gnatmetric}
14485 @noindent
14486 @command{gnatmetric} has two output formats. It can generate a
14487 textual (human-readable) form, and also XML. By default only textual
14488 output is generated.
14490 When generating the output in textual form, @command{gnatmetric} creates
14491 for each Ada source file a corresponding text file
14492 containing the computed metrics, except for the case when the set of metrics
14493 specified by gnatmetric parameters consists only of metrics that are computed
14494 for the whole set of analyzed sources, but not for each Ada source.
14495 By default, this file is placed in the same directory as where the source
14496 file is located, and its name is obtained
14497 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14498 input file.
14500 All the output information generated in XML format is placed in a single
14501 file. By default this file is placed in the current directory and has the
14502 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14504 Some of the computed metrics are summed over the units passed to
14505 @command{gnatmetric}; for example, the total number of lines of code.
14506 By default this information is sent to @file{stdout}, but a file
14507 can be specified with the @option{-og} switch.
14509 The following switches control the @command{gnatmetric} output:
14511 @table @option
14512 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14513 @item ^-x^/XML^
14514 Generate the XML output
14516 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14517 @item ^-xs^/XSD^
14518 Generate the XML output and the XML schema file that describes the structure
14519 of the XML metric report, this schema is assigned to the XML file. The schema
14520 file has the same name as the XML output file with @file{.xml} suffix replaced
14521 with @file{.xsd}
14523 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14524 @item ^-nt^/NO_TEXT^
14525 Do not generate the output in text form (implies @option{^-x^/XML^})
14527 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14528 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14529 Put text files with detailed metrics into @var{output_dir}
14531 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14532 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14533 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14534 in the name of the output file.
14536 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14537 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14538 Put global metrics into @var{file_name}
14540 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14541 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14542 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14544 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14545 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14546 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14547 output includes the name(s) of the Ada source file(s) from which the metrics
14548 are computed.  By default each name includes the absolute path. The
14549 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14550 to exclude all directory information from the file names that are output.)
14552 @end table
14554 @node Disable Metrics For Local Units
14555 @subsection Disable Metrics For Local Units
14556 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14558 @noindent
14559 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14560 one compilation
14561 unit per one source file. It computes line metrics for the whole source
14562 file, and it also computes syntax
14563 and complexity metrics for the file's outermost unit.
14565 By default, @command{gnatmetric} will also compute all metrics for certain
14566 kinds of locally declared program units:
14568 @itemize @bullet
14569 @item
14570 subprogram (and generic subprogram) bodies;
14572 @item
14573 package (and generic package) specs and bodies;
14575 @item
14576 task object and type specifications and bodies;
14578 @item
14579 protected object and type specifications and bodies.
14580 @end itemize
14582 @noindent
14583 These kinds of entities will be referred to as
14584 @emph{eligible local program units}, or simply @emph{eligible local units},
14585 @cindex Eligible local unit (for @command{gnatmetric})
14586 in the discussion below.
14588 Note that a subprogram declaration, generic instantiation,
14589 or renaming declaration only receives metrics
14590 computation when it appear as the outermost entity
14591 in a source file.
14593 Suppression of metrics computation for eligible local units can be
14594 obtained via the following switch:
14596 @table @option
14597 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14598 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14599 Do not compute detailed metrics for eligible local program units
14601 @end table
14603 @node Specifying a set of metrics to compute
14604 @subsection Specifying a set of metrics to compute
14606 @noindent
14607 By default all the metrics are computed and reported. The switches
14608 described in this subsection allow you to control, on an individual
14609 basis, whether metrics are computed and
14610 reported. If at least one positive metric
14611 switch is specified (that is, a switch that defines that a given
14612 metric or set of metrics is to be computed), then only
14613 explicitly specified metrics are reported.
14615 @menu
14616 * Line Metrics Control::
14617 * Syntax Metrics Control::
14618 * Complexity Metrics Control::
14619 * Coupling Metrics Control::
14620 @end menu
14622 @node Line Metrics Control
14623 @subsubsection Line Metrics Control
14624 @cindex Line metrics control in @command{gnatmetric}
14626 @noindent
14627 For any (legal) source file, and for each of its
14628 eligible local program units, @command{gnatmetric} computes the following
14629 metrics:
14631 @itemize @bullet
14632 @item
14633 the total number of lines;
14635 @item
14636 the total number of code lines (i.e., non-blank lines that are not comments)
14638 @item
14639 the number of comment lines
14641 @item
14642 the number of code lines containing end-of-line comments;
14644 @item
14645 the comment percentage: the ratio between the number of lines that contain
14646 comments and the number of all non-blank lines, expressed as a percentage;
14648 @item
14649 the number of empty lines and lines containing only space characters and/or
14650 format effectors (blank lines)
14652 @item
14653 the average number of code lines in subprogram bodies, task bodies, entry
14654 bodies and statement sequences in package bodies (this metric is only computed
14655 across the whole set of the analyzed units)
14657 @end itemize
14659 @noindent
14660 @command{gnatmetric} sums the values of the line metrics for all the
14661 files being processed and then generates the cumulative results. The tool
14662 also computes for all the files being processed the average number of code
14663 lines in bodies.
14665 You can use the following switches to select the specific line metrics
14666 to be computed and reported.
14668 @table @option
14669 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14671 @ifclear vms
14672 @cindex @option{--no-lines@var{x}}
14673 @end ifclear
14675 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14676 Report all the line metrics
14678 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14679 Do not report any of line metrics
14681 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14682 Report the number of all lines
14684 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14685 Do not report the number of all lines
14687 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14688 Report the number of code lines
14690 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14691 Do not report the number of code lines
14693 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14694 Report the number of comment lines
14696 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14697 Do not report the number of comment lines
14699 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14700 Report the number of code lines containing
14701 end-of-line comments
14703 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14704 Do not report the number of code lines containing
14705 end-of-line comments
14707 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14708 Report the comment percentage in the program text
14710 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14711 Do not report the comment percentage in the program text
14713 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14714 Report the number of blank lines
14716 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14717 Do not report the number of blank lines
14719 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14720 Report the average number of code lines in subprogram bodies, task bodies,
14721 entry bodies and statement sequences in package bodies. The metric is computed
14722 and reported for the whole set of processed Ada sources only.
14724 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14725 Do not report the average number of code lines in subprogram bodies,
14726 task bodies, entry bodies and statement sequences in package bodies.
14728 @end table
14730 @node Syntax Metrics Control
14731 @subsubsection Syntax Metrics Control
14732 @cindex Syntax metrics control in @command{gnatmetric}
14734 @noindent
14735 @command{gnatmetric} computes various syntactic metrics for the
14736 outermost unit and for each eligible local unit:
14738 @table @emph
14739 @item LSLOC (``Logical Source Lines Of Code'')
14740 The total number of declarations and the total number of statements. Note
14741 that the definition of declarations is the one given in the reference
14742 manual:
14744 @noindent
14745 ``Each of the following is defined to be a declaration: any basic_declaration;
14746 an enumeration_literal_specification; a discriminant_specification;
14747 a component_declaration; a loop_parameter_specification; a
14748 parameter_specification; a subprogram_body; an entry_declaration;
14749 an entry_index_specification; a choice_parameter_specification;
14750 a generic_formal_parameter_declaration.''
14752 This means for example that each enumeration literal adds one to the count,
14753 as well as each subprogram parameter.
14755 Thus the results from this metric will be significantly greater than might
14756 be expected from a naive view of counting semicolons.
14758 @item Maximal static nesting level of inner program units
14759 According to
14760 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14761 package, a task unit, a protected unit, a
14762 protected entry, a generic unit, or an explicitly declared subprogram other
14763 than an enumeration literal.''
14765 @item Maximal nesting level of composite syntactic constructs
14766 This corresponds to the notion of the
14767 maximum nesting level in the GNAT built-in style checks
14768 (@pxref{Style Checking})
14769 @end table
14771 @noindent
14772 For the outermost unit in the file, @command{gnatmetric} additionally computes
14773 the following metrics:
14775 @table @emph
14776 @item Public subprograms
14777 This metric is computed for package specs. It is the
14778 number of subprograms and generic subprograms declared in the visible
14779 part (including the visible part of nested packages, protected objects, and
14780 protected types).
14782 @item All subprograms
14783 This metric is computed for bodies and subunits. The
14784 metric is equal to a total number of subprogram bodies in the compilation
14785 unit.
14786 Neither generic instantiations nor renamings-as-a-body nor body stubs
14787 are counted. Any subprogram body is counted, independently of its nesting
14788 level and enclosing constructs. Generic bodies and bodies of protected
14789 subprograms are counted in the same way as ``usual'' subprogram bodies.
14791 @item Public types
14792 This metric is computed for package specs and
14793 generic package declarations. It is the total number of types
14794 that can be referenced from outside this compilation unit, plus the
14795 number of types from all the visible parts of all the visible generic
14796 packages. Generic formal types are not counted.  Only types, not subtypes,
14797 are included.
14799 @noindent
14800 Along with the total number of public types, the following
14801 types are counted and reported separately:
14803 @itemize @bullet
14804 @item
14805 Abstract types
14807 @item
14808 Root tagged types (abstract, non-abstract, private, non-private). Type
14809 extensions are @emph{not} counted
14811 @item
14812 Private types (including private extensions)
14814 @item
14815 Task types
14817 @item
14818 Protected types
14820 @end itemize
14822 @item All types
14823 This metric is computed for any compilation unit. It is equal to the total
14824 number of the declarations of different types given in the compilation unit.
14825 The private and the corresponding full type declaration are counted as one
14826 type declaration. Incomplete type declarations and generic formal types
14827 are not counted.
14828 No distinction is made among different kinds of types (abstract,
14829 private etc.); the total number of types is computed and reported.
14831 @end table
14833 @noindent
14834 By default, all the syntax metrics are computed and reported. You can use the
14835 following switches to select specific syntax metrics.
14837 @table @option
14839 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14841 @ifclear vms
14842 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14843 @end ifclear
14845 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14846 Report all the syntax metrics
14848 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14849 Do not report any of syntax metrics
14851 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14852 Report the total number of declarations
14854 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14855 Do not report the total number of declarations
14857 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14858 Report the total number of statements
14860 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14861 Do not report the total number of statements
14863 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14864 Report the number of public subprograms in a compilation unit
14866 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14867 Do not report the number of public subprograms in a compilation unit
14869 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14870 Report the number of all the subprograms in a compilation unit
14872 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14873 Do not report the number of all the subprograms in a compilation unit
14875 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14876 Report the number of public types in a compilation unit
14878 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14879 Do not report the number of public types in a compilation unit
14881 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14882 Report the number of all the types in a compilation unit
14884 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14885 Do not report the number of all the types in a compilation unit
14887 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14888 Report the maximal program unit nesting level
14890 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14891 Do not report the maximal program unit nesting level
14893 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14894 Report the maximal construct nesting level
14896 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14897 Do not report the maximal construct nesting level
14899 @end table
14901 @node Complexity Metrics Control
14902 @subsubsection Complexity Metrics Control
14903 @cindex Complexity metrics control in @command{gnatmetric}
14905 @noindent
14906 For a program unit that is an executable body (a subprogram body (including
14907 generic bodies), task body, entry body or a package body containing
14908 its own statement sequence) @command{gnatmetric} computes the following
14909 complexity metrics:
14911 @itemize @bullet
14912 @item
14913 McCabe cyclomatic complexity;
14915 @item
14916 McCabe essential complexity;
14918 @item
14919 maximal loop nesting level;
14921 @item
14922 extra exit points (for subprograms);
14923 @end itemize
14925 @noindent
14926 The McCabe cyclomatic complexity metric is defined
14927 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14929 According to McCabe, both control statements and short-circuit control forms
14930 should be taken into account when computing cyclomatic complexity.
14931 For Ada 2012 we have also take into account conditional expressions
14932 and quantified expressions. For each body, we compute three metric values:
14934 @itemize @bullet
14935 @item
14936 the complexity introduced by control
14937 statements only, without taking into account short-circuit forms,
14939 @item
14940 the complexity introduced by short-circuit control forms only, and
14942 @item
14943 the total
14944 cyclomatic complexity, which is the sum of these two values.
14945 @end itemize
14947 @noindent
14949 The cyclomatic complexity is also computed for Ada 2012 expression functions.
14950 An expression function cannot have statements as its components, so only one
14951 metric value is computed as a cyclomatic complexity of an expression function.
14953 The origin of cyclomatic complexity metric is the need to estimate the number
14954 of independent paths in the control flow graph that in turn gives the number
14955 of tests needed to satisfy paths coverage testing completeness criterion.
14956 Considered from the testing point of view, a static Ada @code{loop} (that is,
14957 the @code{loop} statement having static subtype in loop parameter
14958 specification) does not add to cyclomatic complexity. By providing
14959 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14960 may specify that such loops should not be counted when computing the
14961 cyclomatic complexity metric
14963 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14964 counted for the code that is reduced by excluding all the pure structural Ada
14965 control statements. An compound statement is considered as a non-structural
14966 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14967 or if it contains a @code{goto} statement that transfers the control outside
14968 the operator. A selective accept statement with @code{terminate} alternative
14969 is considered as non-structural statement. When computing this metric,
14970 @code{exit} statements are treated in the same way as @code{goto}
14971 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14973 The Ada essential complexity metric defined here is intended to quantify
14974 the extent to which the software is unstructured. It is adapted from
14975 the McCabe essential complexity metric defined in
14976 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
14977 suitable for typical Ada usage. For example, short circuit forms
14978 are not penalized as unstructured in the Ada essential complexity metric.
14980 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14981 the code in the exception handlers and in all the nested program units. The
14982 code of assertions and predicates (that is, subprogram preconditions and
14983 postconditions, subtype predicates and type invariants) is also skipped.
14985 By default, all the complexity metrics are computed and reported.
14986 For more fine-grained control you can use
14987 the following switches:
14989 @table @option
14990 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14992 @ifclear vms
14993 @cindex @option{--no-complexity@var{x}}
14994 @end ifclear
14996 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14997 Report all the complexity metrics
14999 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
15000 Do not report any of complexity metrics
15002 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
15003 Report the McCabe Cyclomatic Complexity
15005 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
15006 Do not report the McCabe Cyclomatic Complexity
15008 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
15009 Report the Essential Complexity
15011 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
15012 Do not report the Essential Complexity
15014 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
15015 Report maximal loop nesting level
15017 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
15018 Do not report maximal loop nesting level
15020 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
15021 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15022 task bodies, entry bodies and statement sequences in package bodies.
15023 The metric is computed and reported for whole set of processed Ada sources
15024 only.
15026 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
15027 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15028 bodies, task bodies, entry bodies and statement sequences in package bodies
15030 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
15031 @item ^-ne^/NO_EXITS_AS_GOTOS^
15032 Do not consider @code{exit} statements as @code{goto}s when
15033 computing Essential Complexity
15035 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
15036 @item ^--no-static-loop^/NO_STATIC_LOOP^
15037 Do not consider static loops when computing cyclomatic complexity
15039 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
15040 Report the extra exit points for subprogram bodies. As an exit point, this
15041 metric counts @code{return} statements and raise statements in case when the
15042 raised exception is not handled in the same body. In case of a function this
15043 metric subtracts 1 from the number of exit points, because a function body
15044 must contain at least one @code{return} statement.
15046 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
15047 Do not report the extra exit points for subprogram bodies
15048 @end table
15051 @node Coupling Metrics Control
15052 @subsubsection Coupling Metrics Control
15053 @cindex Coupling metrics control in @command{gnatmetric}
15055 @noindent
15056 @cindex Coupling metrics (in in @command{gnatmetric})
15057 Coupling metrics measure the dependencies between a given entity and other
15058 entities the program consists of. The goal of these metrics is to estimate the
15059 stability of the whole program considered as the collection of entities
15060 (modules, classes etc.).
15062 Gnatmetric computes the following coupling metrics:
15064 @itemize @bullet
15066 @item
15067 @emph{object-oriented coupling} - for classes in traditional object-oriented
15068 sense;
15070 @item
15071 @emph{unit coupling} - for all the program units making up a program;
15073 @item
15074 @emph{control coupling} - this metric counts dependencies between a unit and
15075 only those units that define subprograms;
15076 @end itemize
15078 @noindent
15079 Two kinds of coupling metrics are computed:
15081 @table @asis
15082 @item fan-out coupling (efferent coupling)
15083 @cindex fan-out coupling
15084 @cindex efferent coupling
15085 the number of entities the given entity depends upon. It
15086 estimates in what extent the given entity depends on the changes in
15087 ``external world''
15089 @item fan-in coupling (afferent coupling)
15090 @cindex fan-in coupling
15091 @cindex afferent coupling
15092 the number of entities that depend on a given entity.
15093 It estimates in what extent the ``external world'' depends on the changes in a
15094 given entity
15095 @end table
15097 @noindent
15099 Object-oriented coupling metrics are metrics that measure the dependencies
15100 between a given class (or a group of classes) and the other classes in the
15101 program. In this subsection the term ``class'' is used in its traditional
15102 object-oriented programming sense (an instantiable module that contains data
15103 and/or method members). A @emph{category} (of classes) is a group of closely
15104 related classes that are reused and/or modified together.
15106 A class @code{K}'s fan-out coupling is the number of classes
15107 that @code{K} depends upon.
15108 A category's fan-out coupling is the number of classes outside the
15109 category that the classes inside the category depend upon.
15111 A class @code{K}'s fan-in coupling is the number of classes
15112 that depend upon @code{K}.
15113 A category's fan-in coupling is the number of classes outside the
15114 category that depend on classes belonging to the category.
15116 Ada's implementation of the object-oriented paradigm does not use the
15117 traditional class notion, so the definition of the coupling
15118 metrics for Ada maps the class and class category notions
15119 onto Ada constructs.
15121 For the coupling metrics, several kinds of modules -- a library package,
15122 a library generic package, and a library generic package instantiation --
15123 that define a tagged type or an interface type are
15124 considered to be a class. A category consists of a library package (or
15125 a library generic package) that defines a tagged or an interface type,
15126 together with all its descendant (generic) packages that define tagged
15127 or interface types. That is a
15128 category is an Ada hierarchy of library-level program units. So class coupling
15129 in case of Ada is called as tagged coupling, and category coupling - as
15130 hierarchy coupling.
15132 For any package counted as a class, its body and subunits (if any) are
15133 considered together with its spec when counting the dependencies, and coupling
15134 metrics are reported for spec units only. For dependencies between classes,
15135 the Ada semantic dependencies are considered. For object-oriented coupling
15136 metrics, only dependencies on units that are considered as classes, are
15137 considered.
15139 For unit and control coupling also not compilation units but program units are
15140 counted. That is, for a package, its spec, its body and its subunits (if any)
15141 are considered as making up one unit, and the dependencies that are counted
15142 are the dependencies of all these compilation units collected together as
15143 the dependencies as a (whole) unit. And metrics are reported for spec
15144 compilation units only (or for a subprogram body unit in case if there is no
15145 separate spec for the given subprogram).
15147 For unit coupling, dependencies between all kinds of program units are
15148 considered. For control coupling, for each unit the dependencies of this unit
15149 upon units that define subprograms are counted, so control fan-out coupling
15150 is reported for all units, but control fan-in coupling - only for the units
15151 that define subprograms.
15153 The following simple example illustrates the difference between unit coupling
15154 and control coupling metrics:
15156 @smallexample @c ada
15157 package Lib_1 is
15158     function F_1 (I : Integer) return Integer;
15159 end Lib_1;
15161 package Lib_2 is
15162     type T_2 is new Integer;
15163 end Lib_2;
15165 package body Lib_1 is
15166     function F_1 (I : Integer) return Integer is
15167     begin
15168        return I + 1;
15169     end F_1;
15170 end Lib_1;
15172 with Lib_2; use Lib_2;
15173 package Pack is
15174     Var : T_2;
15175     function Fun (I : Integer) return Integer;
15176 end Pack;
15178 with Lib_1; use Lib_1;
15179 package body Pack is
15180     function Fun (I : Integer) return Integer is
15181     begin
15182        return F_1 (I);
15183     end Fun;
15184 end Pack;
15185 @end smallexample
15187 @noindent
15188 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
15189 units, the result will be:
15191 @smallexample
15192 Coupling metrics:
15193 =================
15194     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15195        control fan-out coupling  : 0
15196        control fan-in coupling   : 1
15197        unit fan-out coupling     : 0
15198        unit fan-in coupling      : 1
15200     Unit Pack (C:\customers\662\L406-007\pack.ads)
15201        control fan-out coupling  : 1
15202        control fan-in coupling   : 0
15203        unit fan-out coupling     : 2
15204        unit fan-in coupling      : 0
15206     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15207        control fan-out coupling  : 0
15208        unit fan-out coupling     : 0
15209        unit fan-in coupling      : 1
15210 @end smallexample
15212 @noindent
15213 The result does not contain values for object-oriented
15214 coupling because none of the argument unit contains a tagged type and
15215 therefore none of these units can be treated as a class.
15217 @code{Pack} (considered as a program unit, that is spec+body) depends on two
15218 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
15219 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
15220 well as control fan-in coupling. Only one of the units @code{Pack} depends
15221 upon defines a subprogram, so its control fan-out coupling is 1.
15223 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
15224 not define a subprogram, so control fan-in metric cannot be applied to it,
15225 and there is one unit that depends on it (@code{Pack}), so it has
15226 unit fan-in coupling equals to 1.
15228 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15229 So it has control fan-in coupling equals to 1 (because there is a unit
15230 depending on it).
15232 When computing coupling metrics, @command{gnatmetric} counts only
15233 dependencies between units that are arguments of the @command{gnatmetric}
15234 call. Coupling metrics are program-wide (or project-wide) metrics, so to
15235 get a valid result, you should call @command{gnatmetric} for
15236 the whole set of sources that make up your program. It can be done
15237 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
15238 option (see @ref{The GNAT Driver and Project Files} for details).
15240 By default, all the coupling metrics are disabled. You can use the following
15241 switches to specify the coupling metrics to be computed and reported:
15243 @table @option
15245 @ifclear vms
15246 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15247 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15248 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15249 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15250 @end ifclear
15252 @ifset vms
15253 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
15254 @end ifset
15256 @item ^--coupling-all^/COUPLING_METRICS=ALL^
15257 Report all the coupling metrics
15259 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
15260 Report tagged (class) fan-out coupling
15262 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
15263 Report tagged (class) fan-in coupling
15265 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
15266 Report hierarchy (category) fan-out coupling
15268 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
15269 Report hierarchy (category) fan-in coupling
15271 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
15272 Report unit fan-out coupling
15274 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
15275 Report unit fan-in coupling
15277 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
15278 Report control fan-out coupling
15280 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
15281 Report control fan-in coupling
15282 @end table
15284 @node Other gnatmetric Switches
15285 @subsection Other @code{gnatmetric} Switches
15287 @noindent
15288 Additional @command{gnatmetric} switches are as follows:
15290 @table @option
15291 @item ^-files @var{filename}^/FILES=@var{filename}^
15292 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15293 Take the argument source files from the specified file. This file should be an
15294 ordinary text file containing file names separated by spaces or
15295 line breaks. You can use this switch more than once in the same call to
15296 @command{gnatmetric}. You also can combine this switch with
15297 an explicit list of files.
15299 @item ^-v^/VERBOSE^
15300 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15301 Verbose mode;
15302 @command{gnatmetric} generates version information and then
15303 a trace of sources being processed.
15305 @item ^-q^/QUIET^
15306 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15307 Quiet mode.
15308 @end table
15310 @node Generate project-wide metrics
15311 @subsection Generate project-wide metrics
15313 In order to compute metrics on all units of a given project, you can use
15314 the @command{gnat} driver along with the @option{-P} option:
15315 @smallexample
15316    gnat metric -Pproj
15317 @end smallexample
15319 @noindent
15320 If the project @code{proj} depends upon other projects, you can compute
15321 the metrics on the project closure using the @option{-U} option:
15322 @smallexample
15323    gnat metric -Pproj -U
15324 @end smallexample
15326 @noindent
15327 Finally, if not all the units are relevant to a particular main
15328 program in the project closure, you can generate metrics for the set
15329 of units needed to create a given main program (unit closure) using
15330 the @option{-U} option followed by the name of the main unit:
15331 @smallexample
15332    gnat metric -Pproj -U main
15333 @end smallexample
15336 @c ***********************************
15337 @node File Name Krunching Using gnatkr
15338 @chapter File Name Krunching Using @code{gnatkr}
15339 @findex gnatkr
15341 @noindent
15342 This chapter discusses the method used by the compiler to shorten
15343 the default file names chosen for Ada units so that they do not
15344 exceed the maximum length permitted. It also describes the
15345 @code{gnatkr} utility that can be used to determine the result of
15346 applying this shortening.
15347 @menu
15348 * About gnatkr::
15349 * Using gnatkr::
15350 * Krunching Method::
15351 * Examples of gnatkr Usage::
15352 @end menu
15354 @node About gnatkr
15355 @section About @code{gnatkr}
15357 @noindent
15358 The default file naming rule in GNAT
15359 is that the file name must be derived from
15360 the unit name. The exact default rule is as follows:
15361 @itemize @bullet
15362 @item
15363 Take the unit name and replace all dots by hyphens.
15364 @item
15365 If such a replacement occurs in the
15366 second character position of a name, and the first character is
15367 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15368 then replace the dot by the character
15369 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15370 instead of a minus.
15371 @end itemize
15372 The reason for this exception is to avoid clashes
15373 with the standard names for children of System, Ada, Interfaces,
15374 and GNAT, which use the prefixes
15375 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15376 respectively.
15378 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15379 switch of the compiler activates a ``krunching''
15380 circuit that limits file names to nn characters (where nn is a decimal
15381 integer). For example, using OpenVMS,
15382 where the maximum file name length is
15383 39, the value of nn is usually set to 39, but if you want to generate
15384 a set of files that would be usable if ported to a system with some
15385 different maximum file length, then a different value can be specified.
15386 The default value of 39 for OpenVMS need not be specified.
15388 The @code{gnatkr} utility can be used to determine the krunched name for
15389 a given file, when krunched to a specified maximum length.
15391 @node Using gnatkr
15392 @section Using @code{gnatkr}
15394 @noindent
15395 The @code{gnatkr} command has the form
15397 @ifclear vms
15398 @smallexample
15399 @c $ gnatkr @var{name} @ovar{length}
15400 @c Expanding @ovar macro inline (explanation in macro def comments)
15401 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15402 @end smallexample
15403 @end ifclear
15405 @ifset vms
15406 @smallexample
15407 $ gnatkr @var{name} /COUNT=nn
15408 @end smallexample
15409 @end ifset
15411 @noindent
15412 @var{name} is the uncrunched file name, derived from the name of the unit
15413 in the standard manner described in the previous section (i.e., in particular
15414 all dots are replaced by hyphens). The file name may or may not have an
15415 extension (defined as a suffix of the form period followed by arbitrary
15416 characters other than period). If an extension is present then it will
15417 be preserved in the output. For example, when krunching @file{hellofile.ads}
15418 to eight characters, the result will be hellofil.ads.
15420 Note: for compatibility with previous versions of @code{gnatkr} dots may
15421 appear in the name instead of hyphens, but the last dot will always be
15422 taken as the start of an extension. So if @code{gnatkr} is given an argument
15423 such as @file{Hello.World.adb} it will be treated exactly as if the first
15424 period had been a hyphen, and for example krunching to eight characters
15425 gives the result @file{hellworl.adb}.
15427 Note that the result is always all lower case (except on OpenVMS where it is
15428 all upper case). Characters of the other case are folded as required.
15430 @var{length} represents the length of the krunched name. The default
15431 when no argument is given is ^8^39^ characters. A length of zero stands for
15432 unlimited, in other words do not chop except for system files where the
15433 implied crunching length is always eight characters.
15435 @noindent
15436 The output is the krunched name. The output has an extension only if the
15437 original argument was a file name with an extension.
15439 @node Krunching Method
15440 @section Krunching Method
15442 @noindent
15443 The initial file name is determined by the name of the unit that the file
15444 contains. The name is formed by taking the full expanded name of the
15445 unit and replacing the separating dots with hyphens and
15446 using ^lowercase^uppercase^
15447 for all letters, except that a hyphen in the second character position is
15448 replaced by a ^tilde^dollar sign^ if the first character is
15449 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15450 The extension is @code{.ads} for a
15451 spec and @code{.adb} for a body.
15452 Krunching does not affect the extension, but the file name is shortened to
15453 the specified length by following these rules:
15455 @itemize @bullet
15456 @item
15457 The name is divided into segments separated by hyphens, tildes or
15458 underscores and all hyphens, tildes, and underscores are
15459 eliminated. If this leaves the name short enough, we are done.
15461 @item
15462 If the name is too long, the longest segment is located (left-most
15463 if there are two of equal length), and shortened by dropping
15464 its last character. This is repeated until the name is short enough.
15466 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15467 to fit the name into 8 characters as required by some operating systems.
15469 @smallexample
15470 our-strings-wide_fixed 22
15471 our strings wide fixed 19
15472 our string  wide fixed 18
15473 our strin   wide fixed 17
15474 our stri    wide fixed 16
15475 our stri    wide fixe  15
15476 our str     wide fixe  14
15477 our str     wid  fixe  13
15478 our str     wid  fix   12
15479 ou  str     wid  fix   11
15480 ou  st      wid  fix   10
15481 ou  st      wi   fix   9
15482 ou  st      wi   fi    8
15483 Final file name: oustwifi.adb
15484 @end smallexample
15486 @item
15487 The file names for all predefined units are always krunched to eight
15488 characters. The krunching of these predefined units uses the following
15489 special prefix replacements:
15491 @table @file
15492 @item ada-
15493 replaced by @file{^a^A^-}
15495 @item gnat-
15496 replaced by @file{^g^G^-}
15498 @item interfaces-
15499 replaced by @file{^i^I^-}
15501 @item system-
15502 replaced by @file{^s^S^-}
15503 @end table
15505 These system files have a hyphen in the second character position. That
15506 is why normal user files replace such a character with a
15507 ^tilde^dollar sign^, to
15508 avoid confusion with system file names.
15510 As an example of this special rule, consider
15511 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15513 @smallexample
15514 ada-strings-wide_fixed 22
15515 a-  strings wide fixed 18
15516 a-  string  wide fixed 17
15517 a-  strin   wide fixed 16
15518 a-  stri    wide fixed 15
15519 a-  stri    wide fixe  14
15520 a-  str     wide fixe  13
15521 a-  str     wid  fixe  12
15522 a-  str     wid  fix   11
15523 a-  st      wid  fix   10
15524 a-  st      wi   fix   9
15525 a-  st      wi   fi    8
15526 Final file name: a-stwifi.adb
15527 @end smallexample
15528 @end itemize
15530 Of course no file shortening algorithm can guarantee uniqueness over all
15531 possible unit names, and if file name krunching is used then it is your
15532 responsibility to ensure that no name clashes occur. The utility
15533 program @code{gnatkr} is supplied for conveniently determining the
15534 krunched name of a file.
15536 @node Examples of gnatkr Usage
15537 @section Examples of @code{gnatkr} Usage
15539 @smallexample
15540 @iftex
15541 @leftskip=0cm
15542 @end iftex
15543 @ifclear vms
15544 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15545 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15546 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15547 $ gnatkr grandparent-parent-child     --> grparchi
15548 @end ifclear
15549 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15550 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15551 @end smallexample
15553 @node Preprocessing Using gnatprep
15554 @chapter Preprocessing Using @code{gnatprep}
15555 @findex gnatprep
15557 @noindent
15558 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15559 preprocessing.
15560 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15561 special GNAT features.
15562 For further discussion of conditional compilation in general, see
15563 @ref{Conditional Compilation}.
15565 @menu
15566 * Preprocessing Symbols::
15567 * Using gnatprep::
15568 * Switches for gnatprep::
15569 * Form of Definitions File::
15570 * Form of Input Text for gnatprep::
15571 @end menu
15573 @node Preprocessing Symbols
15574 @section Preprocessing Symbols
15576 @noindent
15577 Preprocessing symbols are defined in definition files and referred to in
15578 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15579 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15580 all characters need to be in the ASCII set (no accented letters).
15582 @node Using gnatprep
15583 @section Using @code{gnatprep}
15585 @noindent
15586 To call @code{gnatprep} use
15588 @smallexample
15589 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15590 @c Expanding @ovar macro inline (explanation in macro def comments)
15591 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15592 @end smallexample
15594 @noindent
15595 where
15596 @table @var
15597 @item switches
15598 is an optional sequence of switches as described in the next section.
15600 @item infile
15601 is the full name of the input file, which is an Ada source
15602 file containing preprocessor directives.
15604 @item outfile
15605 is the full name of the output file, which is an Ada source
15606 in standard Ada form. When used with GNAT, this file name will
15607 normally have an ads or adb suffix.
15609 @item deffile
15610 is the full name of a text file containing definitions of
15611 preprocessing symbols to be referenced by the preprocessor. This argument is
15612 optional, and can be replaced by the use of the @option{-D} switch.
15614 @end table
15616 @node Switches for gnatprep
15617 @section Switches for @code{gnatprep}
15619 @table @option
15620 @c !sort!
15622 @item ^-b^/BLANK_LINES^
15623 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15624 Causes both preprocessor lines and the lines deleted by
15625 preprocessing to be replaced by blank lines in the output source file,
15626 preserving line numbers in the output file.
15628 @item ^-c^/COMMENTS^
15629 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15630 Causes both preprocessor lines and the lines deleted
15631 by preprocessing to be retained in the output source as comments marked
15632 with the special string @code{"--! "}. This option will result in line numbers
15633 being preserved in the output file.
15635 @item ^-C^/REPLACE_IN_COMMENTS^
15636 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15637 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15638 If this option is specified, then comments are scanned and any $symbol
15639 substitutions performed as in program text. This is particularly useful
15640 when structured comments are used (e.g., when writing programs in the
15641 SPARK dialect of Ada). Note that this switch is not available when
15642 doing integrated preprocessing (it would be useless in this context
15643 since comments are ignored by the compiler in any case).
15645 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15646 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15647 Defines a new preprocessing symbol, associated with value. If no value is given
15648 on the command line, then symbol is considered to be @code{True}. This switch
15649 can be used in place of a definition file.
15651 @ifset vms
15652 @item /REMOVE
15653 @cindex @option{/REMOVE} (@command{gnatprep})
15654 This is the default setting which causes lines deleted by preprocessing
15655 to be entirely removed from the output file.
15656 @end ifset
15658 @item ^-r^/REFERENCE^
15659 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15660 Causes a @code{Source_Reference} pragma to be generated that
15661 references the original input file, so that error messages will use
15662 the file name of this original file. The use of this switch implies
15663 that preprocessor lines are not to be removed from the file, so its
15664 use will force @option{^-b^/BLANK_LINES^} mode if
15665 @option{^-c^/COMMENTS^}
15666 has not been specified explicitly.
15668 Note that if the file to be preprocessed contains multiple units, then
15669 it will be necessary to @code{gnatchop} the output file from
15670 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15671 in the preprocessed file, it will be respected by
15672 @code{gnatchop ^-r^/REFERENCE^}
15673 so that the final chopped files will correctly refer to the original
15674 input source file for @code{gnatprep}.
15676 @item ^-s^/SYMBOLS^
15677 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15678 Causes a sorted list of symbol names and values to be
15679 listed on the standard output file.
15681 @item ^-u^/UNDEFINED^
15682 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15683 Causes undefined symbols to be treated as having the value FALSE in the context
15684 of a preprocessor test. In the absence of this option, an undefined symbol in
15685 a @code{#if} or @code{#elsif} test will be treated as an error.
15687 @end table
15689 @ifclear vms
15690 @noindent
15691 Note: if neither @option{-b} nor @option{-c} is present,
15692 then preprocessor lines and
15693 deleted lines are completely removed from the output, unless -r is
15694 specified, in which case -b is assumed.
15695 @end ifclear
15697 @node Form of Definitions File
15698 @section Form of Definitions File
15700 @noindent
15701 The definitions file contains lines of the form
15703 @smallexample
15704 symbol := value
15705 @end smallexample
15707 @noindent
15708 where symbol is a preprocessing symbol, and value is one of the following:
15710 @itemize @bullet
15711 @item
15712 Empty, corresponding to a null substitution
15713 @item
15714 A string literal using normal Ada syntax
15715 @item
15716 Any sequence of characters from the set
15717 (letters, digits, period, underline).
15718 @end itemize
15720 @noindent
15721 Comment lines may also appear in the definitions file, starting with
15722 the usual @code{--},
15723 and comments may be added to the definitions lines.
15725 @node Form of Input Text for gnatprep
15726 @section Form of Input Text for @code{gnatprep}
15728 @noindent
15729 The input text may contain preprocessor conditional inclusion lines,
15730 as well as general symbol substitution sequences.
15732 The preprocessor conditional inclusion commands have the form
15734 @smallexample
15735 @group
15736 @cartouche
15737 #if @i{expression} @r{[}then@r{]}
15738    lines
15739 #elsif @i{expression} @r{[}then@r{]}
15740    lines
15741 #elsif @i{expression} @r{[}then@r{]}
15742    lines
15743 @dots{}
15744 #else
15745    lines
15746 #end if;
15747 @end cartouche
15748 @end group
15749 @end smallexample
15751 @noindent
15752 In this example, @i{expression} is defined by the following grammar:
15753 @smallexample
15754 @i{expression} ::=  <symbol>
15755 @i{expression} ::=  <symbol> = "<value>"
15756 @i{expression} ::=  <symbol> = <symbol>
15757 @i{expression} ::=  <symbol> 'Defined
15758 @i{expression} ::=  not @i{expression}
15759 @i{expression} ::=  @i{expression} and @i{expression}
15760 @i{expression} ::=  @i{expression} or @i{expression}
15761 @i{expression} ::=  @i{expression} and then @i{expression}
15762 @i{expression} ::=  @i{expression} or else @i{expression}
15763 @i{expression} ::=  ( @i{expression} )
15764 @end smallexample
15766 The following restriction exists: it is not allowed to have "and" or "or"
15767 following "not" in the same expression without parentheses. For example, this
15768 is not allowed:
15770 @smallexample
15771    not X or Y
15772 @end smallexample
15774 This should be one of the following:
15776 @smallexample
15777    (not X) or Y
15778    not (X or Y)
15779 @end smallexample
15781 @noindent
15782 For the first test (@i{expression} ::= <symbol>) the symbol must have
15783 either the value true or false, that is to say the right-hand of the
15784 symbol definition must be one of the (case-insensitive) literals
15785 @code{True} or @code{False}. If the value is true, then the
15786 corresponding lines are included, and if the value is false, they are
15787 excluded.
15789 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15790 the symbol has been defined in the definition file or by a @option{-D}
15791 switch on the command line. Otherwise, the test is false.
15793 The equality tests are case insensitive, as are all the preprocessor lines.
15795 If the symbol referenced is not defined in the symbol definitions file,
15796 then the effect depends on whether or not switch @option{-u}
15797 is specified. If so, then the symbol is treated as if it had the value
15798 false and the test fails. If this switch is not specified, then
15799 it is an error to reference an undefined symbol. It is also an error to
15800 reference a symbol that is defined with a value other than @code{True}
15801 or @code{False}.
15803 The use of the @code{not} operator inverts the sense of this logical test.
15804 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15805 operators, without parentheses. For example, "if not X or Y then" is not
15806 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15808 The @code{then} keyword is optional as shown
15810 The @code{#} must be the first non-blank character on a line, but
15811 otherwise the format is free form. Spaces or tabs may appear between
15812 the @code{#} and the keyword. The keywords and the symbols are case
15813 insensitive as in normal Ada code. Comments may be used on a
15814 preprocessor line, but other than that, no other tokens may appear on a
15815 preprocessor line. Any number of @code{elsif} clauses can be present,
15816 including none at all. The @code{else} is optional, as in Ada.
15818 The @code{#} marking the start of a preprocessor line must be the first
15819 non-blank character on the line, i.e., it must be preceded only by
15820 spaces or horizontal tabs.
15822 Symbol substitution outside of preprocessor lines is obtained by using
15823 the sequence
15825 @smallexample
15826 $symbol
15827 @end smallexample
15829 @noindent
15830 anywhere within a source line, except in a comment or within a
15831 string literal. The identifier
15832 following the @code{$} must match one of the symbols defined in the symbol
15833 definition file, and the result is to substitute the value of the
15834 symbol in place of @code{$symbol} in the output file.
15836 Note that although the substitution of strings within a string literal
15837 is not possible, it is possible to have a symbol whose defined value is
15838 a string literal. So instead of setting XYZ to @code{hello} and writing:
15840 @smallexample
15841 Header : String := "$XYZ";
15842 @end smallexample
15844 @noindent
15845 you should set XYZ to @code{"hello"} and write:
15847 @smallexample
15848 Header : String := $XYZ;
15849 @end smallexample
15851 @noindent
15852 and then the substitution will occur as desired.
15854 @node The GNAT Library Browser gnatls
15855 @chapter The GNAT Library Browser @code{gnatls}
15856 @findex gnatls
15857 @cindex Library browser
15859 @noindent
15860 @code{gnatls} is a tool that outputs information about compiled
15861 units. It gives the relationship between objects, unit names and source
15862 files. It can also be used to check the source dependencies of a unit
15863 as well as various characteristics.
15865 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15866 driver (see @ref{The GNAT Driver and Project Files}).
15868 @menu
15869 * Running gnatls::
15870 * Switches for gnatls::
15871 * Examples of gnatls Usage::
15872 @end menu
15874 @node Running gnatls
15875 @section Running @code{gnatls}
15877 @noindent
15878 The @code{gnatls} command has the form
15880 @smallexample
15881 $ gnatls switches @var{object_or_ali_file}
15882 @end smallexample
15884 @noindent
15885 The main argument is the list of object or @file{ali} files
15886 (@pxref{The Ada Library Information Files})
15887 for which information is requested.
15889 In normal mode, without additional option, @code{gnatls} produces a
15890 four-column listing. Each line represents information for a specific
15891 object. The first column gives the full path of the object, the second
15892 column gives the name of the principal unit in this object, the third
15893 column gives the status of the source and the fourth column gives the
15894 full path of the source representing this unit.
15895 Here is a simple example of use:
15897 @smallexample
15898 $ gnatls *.o
15899 ^./^[]^demo1.o            demo1            DIF demo1.adb
15900 ^./^[]^demo2.o            demo2             OK demo2.adb
15901 ^./^[]^hello.o            h1                OK hello.adb
15902 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15903 ^./^[]^instr.o            instr             OK instr.adb
15904 ^./^[]^tef.o              tef              DIF tef.adb
15905 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15906 ^./^[]^tgef.o             tgef             DIF tgef.adb
15907 @end smallexample
15909 @noindent
15910 The first line can be interpreted as follows: the main unit which is
15911 contained in
15912 object file @file{demo1.o} is demo1, whose main source is in
15913 @file{demo1.adb}. Furthermore, the version of the source used for the
15914 compilation of demo1 has been modified (DIF). Each source file has a status
15915 qualifier which can be:
15917 @table @code
15918 @item OK (unchanged)
15919 The version of the source file used for the compilation of the
15920 specified unit corresponds exactly to the actual source file.
15922 @item MOK (slightly modified)
15923 The version of the source file used for the compilation of the
15924 specified unit differs from the actual source file but not enough to
15925 require recompilation. If you use gnatmake with the qualifier
15926 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15927 MOK will not be recompiled.
15929 @item DIF (modified)
15930 No version of the source found on the path corresponds to the source
15931 used to build this object.
15933 @item ??? (file not found)
15934 No source file was found for this unit.
15936 @item HID (hidden,  unchanged version not first on PATH)
15937 The version of the source that corresponds exactly to the source used
15938 for compilation has been found on the path but it is hidden by another
15939 version of the same source that has been modified.
15941 @end table
15943 @node Switches for gnatls
15944 @section Switches for @code{gnatls}
15946 @noindent
15947 @code{gnatls} recognizes the following switches:
15949 @table @option
15950 @c !sort!
15951 @cindex @option{--version} @command{gnatls}
15952 Display Copyright and version, then exit disregarding all other options.
15954 @item --help
15955 @cindex @option{--help} @command{gnatls}
15956 If @option{--version} was not used, display usage, then exit disregarding
15957 all other options.
15959 @item ^-a^/ALL_UNITS^
15960 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15961 Consider all units, including those of the predefined Ada library.
15962 Especially useful with @option{^-d^/DEPENDENCIES^}.
15964 @item ^-d^/DEPENDENCIES^
15965 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15966 List sources from which specified units depend on.
15968 @item ^-h^/OUTPUT=OPTIONS^
15969 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15970 Output the list of options.
15972 @item ^-o^/OUTPUT=OBJECTS^
15973 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15974 Only output information about object files.
15976 @item ^-s^/OUTPUT=SOURCES^
15977 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15978 Only output information about source files.
15980 @item ^-u^/OUTPUT=UNITS^
15981 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15982 Only output information about compilation units.
15984 @item ^-files^/FILES^=@var{file}
15985 @cindex @option{^-files^/FILES^} (@code{gnatls})
15986 Take as arguments the files listed in text file @var{file}.
15987 Text file @var{file} may contain empty lines that are ignored.
15988 Each nonempty line should contain the name of an existing file.
15989 Several such switches may be specified simultaneously.
15991 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15992 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15993 @itemx ^-I^/SEARCH=^@var{dir}
15994 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15995 @itemx -nostdinc
15996 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15997 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15998 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15999 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16000 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16001 flags (@pxref{Switches for gnatmake}).
16003 @item --RTS=@var{rts-path}
16004 @cindex @option{--RTS} (@code{gnatls})
16005 Specifies the default location of the runtime library. Same meaning as the
16006 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16008 @item ^-v^/OUTPUT=VERBOSE^
16009 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16010 Verbose mode. Output the complete source, object and project paths. Do not use
16011 the default column layout but instead use long format giving as much as
16012 information possible on each requested units, including special
16013 characteristics such as:
16015 @table @code
16016 @item  Preelaborable
16017 The unit is preelaborable in the Ada sense.
16019 @item No_Elab_Code
16020 No elaboration code has been produced by the compiler for this unit.
16022 @item Pure
16023 The unit is pure in the Ada sense.
16025 @item Elaborate_Body
16026 The unit contains a pragma Elaborate_Body.
16028 @item Remote_Types
16029 The unit contains a pragma Remote_Types.
16031 @item Shared_Passive
16032 The unit contains a pragma Shared_Passive.
16034 @item Predefined
16035 This unit is part of the predefined environment and cannot be modified
16036 by the user.
16038 @item Remote_Call_Interface
16039 The unit contains a pragma Remote_Call_Interface.
16041 @end table
16043 @end table
16045 @node Examples of gnatls Usage
16046 @section Example of @code{gnatls} Usage
16047 @ifclear vms
16049 @noindent
16050 Example of using the verbose switch. Note how the source and
16051 object paths are affected by the -I switch.
16053 @smallexample
16054 $ gnatls -v -I.. demo1.o
16056 GNATLS 5.03w (20041123-34)
16057 Copyright 1997-2004 Free Software Foundation, Inc.
16059 Source Search Path:
16060    <Current_Directory>
16061    ../
16062    /home/comar/local/adainclude/
16064 Object Search Path:
16065    <Current_Directory>
16066    ../
16067    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16069 Project Search Path:
16070    <Current_Directory>
16071    /home/comar/local/lib/gnat/
16073 ./demo1.o
16074    Unit =>
16075      Name   => demo1
16076      Kind   => subprogram body
16077      Flags  => No_Elab_Code
16078      Source => demo1.adb    modified
16079 @end smallexample
16081 @noindent
16082 The following is an example of use of the dependency list.
16083 Note the use of the -s switch
16084 which gives a straight list of source files. This can be useful for
16085 building specialized scripts.
16087 @smallexample
16088 $ gnatls -d demo2.o
16089 ./demo2.o   demo2        OK demo2.adb
16090                          OK gen_list.ads
16091                          OK gen_list.adb
16092                          OK instr.ads
16093                          OK instr-child.ads
16095 $ gnatls -d -s -a demo1.o
16096 demo1.adb
16097 /home/comar/local/adainclude/ada.ads
16098 /home/comar/local/adainclude/a-finali.ads
16099 /home/comar/local/adainclude/a-filico.ads
16100 /home/comar/local/adainclude/a-stream.ads
16101 /home/comar/local/adainclude/a-tags.ads
16102 gen_list.ads
16103 gen_list.adb
16104 /home/comar/local/adainclude/gnat.ads
16105 /home/comar/local/adainclude/g-io.ads
16106 instr.ads
16107 /home/comar/local/adainclude/system.ads
16108 /home/comar/local/adainclude/s-exctab.ads
16109 /home/comar/local/adainclude/s-finimp.ads
16110 /home/comar/local/adainclude/s-finroo.ads
16111 /home/comar/local/adainclude/s-secsta.ads
16112 /home/comar/local/adainclude/s-stalib.ads
16113 /home/comar/local/adainclude/s-stoele.ads
16114 /home/comar/local/adainclude/s-stratt.ads
16115 /home/comar/local/adainclude/s-tasoli.ads
16116 /home/comar/local/adainclude/s-unstyp.ads
16117 /home/comar/local/adainclude/unchconv.ads
16118 @end smallexample
16119 @end ifclear
16121 @ifset vms
16122 @smallexample
16123 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16125 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16126 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16127 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16128 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16129 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16130 demo1.adb
16131 gen_list.ads
16132 gen_list.adb
16133 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16134 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16135 instr.ads
16136 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16137 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16138 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16139 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16140 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16141 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16142 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16143 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16144 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16145 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16146 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16147 @end smallexample
16148 @end ifset
16150 @node Cleaning Up Using gnatclean
16151 @chapter Cleaning Up Using @code{gnatclean}
16152 @findex gnatclean
16153 @cindex Cleaning tool
16155 @noindent
16156 @code{gnatclean} is a tool that allows the deletion of files produced by the
16157 compiler, binder and linker, including ALI files, object files, tree files,
16158 expanded source files, library files, interface copy source files, binder
16159 generated files and executable files.
16161 @menu
16162 * Running gnatclean::
16163 * Switches for gnatclean::
16164 @c * Examples of gnatclean Usage::
16165 @end menu
16167 @node Running gnatclean
16168 @section Running @code{gnatclean}
16170 @noindent
16171 The @code{gnatclean} command has the form:
16173 @smallexample
16174 $ gnatclean switches @var{names}
16175 @end smallexample
16177 @noindent
16178 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16179 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16180 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16182 @noindent
16183 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16184 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16185 the linker. In informative-only mode, specified by switch
16186 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16187 normal mode is listed, but no file is actually deleted.
16189 @node Switches for gnatclean
16190 @section Switches for @code{gnatclean}
16192 @noindent
16193 @code{gnatclean} recognizes the following switches:
16195 @table @option
16196 @c !sort!
16197 @cindex @option{--version} @command{gnatclean}
16198 Display Copyright and version, then exit disregarding all other options.
16200 @item --help
16201 @cindex @option{--help} @command{gnatclean}
16202 If @option{--version} was not used, display usage, then exit disregarding
16203 all other options.
16205 @item ^--subdirs^/SUBDIRS^=subdir
16206 Actual object directory of each project file is the subdirectory subdir of the
16207 object directory specified or defaulted in the project file.
16209 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
16210 By default, shared library projects are not allowed to import static library
16211 projects. When this switch is used on the command line, this restriction is
16212 relaxed.
16214 @item ^-c^/COMPILER_FILES_ONLY^
16215 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16216 Only attempt to delete the files produced by the compiler, not those produced
16217 by the binder or the linker. The files that are not to be deleted are library
16218 files, interface copy files, binder generated files and executable files.
16220 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16221 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16222 Indicate that ALI and object files should normally be found in directory
16223 @var{dir}.
16225 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16226 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16227 When using project files, if some errors or warnings are detected during
16228 parsing and verbose mode is not in effect (no use of switch
16229 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16230 file, rather than its simple file name.
16232 @item ^-h^/HELP^
16233 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16234 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16236 @item ^-n^/NODELETE^
16237 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16238 Informative-only mode. Do not delete any files. Output the list of the files
16239 that would have been deleted if this switch was not specified.
16241 @item ^-P^/PROJECT_FILE=^@var{project}
16242 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16243 Use project file @var{project}. Only one such switch can be used.
16244 When cleaning a project file, the files produced by the compilation of the
16245 immediate sources or inherited sources of the project files are to be
16246 deleted. This is not depending on the presence or not of executable names
16247 on the command line.
16249 @item ^-q^/QUIET^
16250 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16251 Quiet output. If there are no errors, do not output anything, except in
16252 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16253 (switch ^-n^/NODELETE^).
16255 @item ^-r^/RECURSIVE^
16256 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16257 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16258 clean all imported and extended project files, recursively. If this switch
16259 is not specified, only the files related to the main project file are to be
16260 deleted. This switch has no effect if no project file is specified.
16262 @item ^-v^/VERBOSE^
16263 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16264 Verbose mode.
16266 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16267 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16268 Indicates the verbosity of the parsing of GNAT project files.
16269 @xref{Switches Related to Project Files}.
16271 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16272 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16273 Indicates that external variable @var{name} has the value @var{value}.
16274 The Project Manager will use this value for occurrences of
16275 @code{external(name)} when parsing the project file.
16276 @xref{Switches Related to Project Files}.
16278 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16279 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16280 When searching for ALI and object files, look in directory
16281 @var{dir}.
16283 @item ^-I^/SEARCH=^@var{dir}
16284 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16285 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16287 @item ^-I-^/NOCURRENT_DIRECTORY^
16288 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16289 @cindex Source files, suppressing search
16290 Do not look for ALI or object files in the directory
16291 where @code{gnatclean} was invoked.
16293 @end table
16295 @c @node Examples of gnatclean Usage
16296 @c @section Examples of @code{gnatclean} Usage
16298 @ifclear vms
16299 @node GNAT and Libraries
16300 @chapter GNAT and Libraries
16301 @cindex Library, building, installing, using
16303 @noindent
16304 This chapter describes how to build and use libraries with GNAT, and also shows
16305 how to recompile the GNAT run-time library. You should be familiar with the
16306 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16307 chapter.
16309 @menu
16310 * Introduction to Libraries in GNAT::
16311 * General Ada Libraries::
16312 * Stand-alone Ada Libraries::
16313 * Rebuilding the GNAT Run-Time Library::
16314 @end menu
16316 @node Introduction to Libraries in GNAT
16317 @section Introduction to Libraries in GNAT
16319 @noindent
16320 A library is, conceptually, a collection of objects which does not have its
16321 own main thread of execution, but rather provides certain services to the
16322 applications that use it. A library can be either statically linked with the
16323 application, in which case its code is directly included in the application,
16324 or, on platforms that support it, be dynamically linked, in which case
16325 its code is shared by all applications making use of this library.
16327 GNAT supports both types of libraries.
16328 In the static case, the compiled code can be provided in different ways. The
16329 simplest approach is to provide directly the set of objects resulting from
16330 compilation of the library source files. Alternatively, you can group the
16331 objects into an archive using whatever commands are provided by the operating
16332 system. For the latter case, the objects are grouped into a shared library.
16334 In the GNAT environment, a library has three types of components:
16335 @itemize @bullet
16336 @item
16337 Source files.
16338 @item
16339 @file{ALI} files.
16340 @xref{The Ada Library Information Files}.
16341 @item
16342 Object files, an archive or a shared library.
16343 @end itemize
16345 @noindent
16346 A GNAT library may expose all its source files, which is useful for
16347 documentation purposes. Alternatively, it may expose only the units needed by
16348 an external user to make use of the library. That is to say, the specs
16349 reflecting the library services along with all the units needed to compile
16350 those specs, which can include generic bodies or any body implementing an
16351 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16352 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16354 All compilation units comprising an application, including those in a library,
16355 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16356 computes the elaboration order from the @file{ALI} files and this is why they
16357 constitute a mandatory part of GNAT libraries.
16358 @emph{Stand-alone libraries} are the exception to this rule because a specific
16359 library elaboration routine is produced independently of the application(s)
16360 using the library.
16362 @node General Ada Libraries
16363 @section General Ada Libraries
16365 @menu
16366 * Building a library::
16367 * Installing a library::
16368 * Using a library::
16369 @end menu
16371 @node Building a library
16372 @subsection Building a library
16374 @noindent
16375 The easiest way to build a library is to use the Project Manager,
16376 which supports a special type of project called a @emph{Library Project}
16377 (@pxref{Library Projects}).
16379 A project is considered a library project, when two project-level attributes
16380 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16381 control different aspects of library configuration, additional optional
16382 project-level attributes can be specified:
16383 @table @code
16384 @item Library_Kind
16385 This attribute controls whether the library is to be static or dynamic
16387 @item Library_Version
16388 This attribute specifies the library version; this value is used
16389 during dynamic linking of shared libraries to determine if the currently
16390 installed versions of the binaries are compatible.
16392 @item Library_Options
16393 @item Library_GCC
16394 These attributes specify additional low-level options to be used during
16395 library generation, and redefine the actual application used to generate
16396 library.
16397 @end table
16399 @noindent
16400 The GNAT Project Manager takes full care of the library maintenance task,
16401 including recompilation of the source files for which objects do not exist
16402 or are not up to date, assembly of the library archive, and installation of
16403 the library (i.e., copying associated source, object and @file{ALI} files
16404 to the specified location).
16406 Here is a simple library project file:
16407 @smallexample @c ada
16408 project My_Lib is
16409    for Source_Dirs use ("src1", "src2");
16410    for Object_Dir use "obj";
16411    for Library_Name use "mylib";
16412    for Library_Dir use "lib";
16413    for Library_Kind use "dynamic";
16414 end My_lib;
16415 @end smallexample
16417 @noindent
16418 and the compilation command to build and install the library:
16420 @smallexample @c ada
16421   $ gnatmake -Pmy_lib
16422 @end smallexample
16424 @noindent
16425 It is not entirely trivial to perform manually all the steps required to
16426 produce a library. We recommend that you use the GNAT Project Manager
16427 for this task. In special cases where this is not desired, the necessary
16428 steps are discussed below.
16430 There are various possibilities for compiling the units that make up the
16431 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16432 with a conventional script. For simple libraries, it is also possible to create
16433 a dummy main program which depends upon all the packages that comprise the
16434 interface of the library. This dummy main program can then be given to
16435 @command{gnatmake}, which will ensure that all necessary objects are built.
16437 After this task is accomplished, you should follow the standard procedure
16438 of the underlying operating system to produce the static or shared library.
16440 Here is an example of such a dummy program:
16441 @smallexample @c ada
16442 @group
16443 with My_Lib.Service1;
16444 with My_Lib.Service2;
16445 with My_Lib.Service3;
16446 procedure My_Lib_Dummy is
16447 begin
16448    null;
16449 end;
16450 @end group
16451 @end smallexample
16453 @noindent
16454 Here are the generic commands that will build an archive or a shared library.
16456 @smallexample
16457 # compiling the library
16458 $ gnatmake -c my_lib_dummy.adb
16460 # we don't need the dummy object itself
16461 $ rm my_lib_dummy.o my_lib_dummy.ali
16463 # create an archive with the remaining objects
16464 $ ar rc libmy_lib.a *.o
16465 # some systems may require "ranlib" to be run as well
16467 # or create a shared library
16468 $ gcc -shared -o libmy_lib.so *.o
16469 # some systems may require the code to have been compiled with -fPIC
16471 # remove the object files that are now in the library
16472 $ rm *.o
16474 # Make the ALI files read-only so that gnatmake will not try to
16475 # regenerate the objects that are in the library
16476 $ chmod -w *.ali
16477 @end smallexample
16479 @noindent
16480 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16481 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16482 be accessed by the directive @option{-l@var{xxx}} at link time.
16484 @node Installing a library
16485 @subsection Installing a library
16486 @cindex @code{ADA_PROJECT_PATH}
16487 @cindex @code{GPR_PROJECT_PATH}
16489 @noindent
16490 If you use project files, library installation is part of the library build
16491 process (@pxref{Installing a library with project files}).
16493 When project files are not an option, it is also possible, but not recommended,
16494 to install the library so that the sources needed to use the library are on the
16495 Ada source path and the ALI files & libraries be on the Ada Object path (see
16496 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16497 administrator can place general-purpose libraries in the default compiler
16498 paths, by specifying the libraries' location in the configuration files
16499 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16500 must be located in the GNAT installation tree at the same place as the gcc spec
16501 file. The location of the gcc spec file can be determined as follows:
16502 @smallexample
16503 $ gcc -v
16504 @end smallexample
16506 @noindent
16507 The configuration files mentioned above have a simple format: each line
16508 must contain one unique directory name.
16509 Those names are added to the corresponding path
16510 in their order of appearance in the file. The names can be either absolute
16511 or relative; in the latter case, they are relative to where theses files
16512 are located.
16514 The files @file{ada_source_path} and @file{ada_object_path} might not be
16515 present in a
16516 GNAT installation, in which case, GNAT will look for its run-time library in
16517 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16518 objects and @file{ALI} files). When the files exist, the compiler does not
16519 look in @file{adainclude} and @file{adalib}, and thus the
16520 @file{ada_source_path} file
16521 must contain the location for the GNAT run-time sources (which can simply
16522 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16523 contain the location for the GNAT run-time objects (which can simply
16524 be @file{adalib}).
16526 You can also specify a new default path to the run-time library at compilation
16527 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16528 the run-time library you want your program to be compiled with. This switch is
16529 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16530 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16532 It is possible to install a library before or after the standard GNAT
16533 library, by reordering the lines in the configuration files. In general, a
16534 library must be installed before the GNAT library if it redefines
16535 any part of it.
16537 @node Using a library
16538 @subsection Using a library
16540 @noindent Once again, the project facility greatly simplifies the use of
16541 libraries. In this context, using a library is just a matter of adding a
16542 @code{with} clause in the user project. For instance, to make use of the
16543 library @code{My_Lib} shown in examples in earlier sections, you can
16544 write:
16546 @smallexample @c projectfile
16547 with "my_lib";
16548 project My_Proj is
16549   @dots{}
16550 end My_Proj;
16551 @end smallexample
16553 Even if you have a third-party, non-Ada library, you can still use GNAT's
16554 Project Manager facility to provide a wrapper for it. For example, the
16555 following project, when @code{with}ed by your main project, will link with the
16556 third-party library @file{liba.a}:
16558 @smallexample @c projectfile
16559 @group
16560 project Liba is
16561    for Externally_Built use "true";
16562    for Source_Files use ();
16563    for Library_Dir use "lib";
16564    for Library_Name use "a";
16565    for Library_Kind use "static";
16566 end Liba;
16567 @end group
16568 @end smallexample
16569 This is an alternative to the use of @code{pragma Linker_Options}. It is
16570 especially interesting in the context of systems with several interdependent
16571 static libraries where finding a proper linker order is not easy and best be
16572 left to the tools having visibility over project dependence information.
16574 @noindent
16575 In order to use an Ada library manually, you need to make sure that this
16576 library is on both your source and object path
16577 (see @ref{Search Paths and the Run-Time Library (RTL)}
16578 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16579 in an archive or a shared library, you need to specify the desired
16580 library at link time.
16582 For example, you can use the library @file{mylib} installed in
16583 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16585 @smallexample
16586 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16587   -largs -lmy_lib
16588 @end smallexample
16590 @noindent
16591 This can be expressed more simply:
16592 @smallexample
16593 $ gnatmake my_appl
16594 @end smallexample
16595 @noindent
16596 when the following conditions are met:
16597 @itemize @bullet
16598 @item
16599 @file{/dir/my_lib_src} has been added by the user to the environment
16600 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16601 @file{ada_source_path}
16602 @item
16603 @file{/dir/my_lib_obj} has been added by the user to the environment
16604 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16605 @file{ada_object_path}
16606 @item
16607 a pragma @code{Linker_Options} has been added to one of the sources.
16608 For example:
16610 @smallexample @c ada
16611 pragma Linker_Options ("-lmy_lib");
16612 @end smallexample
16613 @end itemize
16615 @node Stand-alone Ada Libraries
16616 @section Stand-alone Ada Libraries
16617 @cindex Stand-alone library, building, using
16619 @menu
16620 * Introduction to Stand-alone Libraries::
16621 * Building a Stand-alone Library::
16622 * Creating a Stand-alone Library to be used in a non-Ada context::
16623 * Restrictions in Stand-alone Libraries::
16624 @end menu
16626 @node Introduction to Stand-alone Libraries
16627 @subsection Introduction to Stand-alone Libraries
16629 @noindent
16630 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16631 necessary code to
16632 elaborate the Ada units that are included in the library. In contrast with
16633 an ordinary library, which consists of all sources, objects and @file{ALI}
16634 files of the
16635 library, a SAL may specify a restricted subset of compilation units
16636 to serve as a library interface. In this case, the fully
16637 self-sufficient set of files will normally consist of an objects
16638 archive, the sources of interface units' specs, and the @file{ALI}
16639 files of interface units.
16640 If an interface spec contains a generic unit or an inlined subprogram,
16641 the body's
16642 source must also be provided; if the units that must be provided in the source
16643 form depend on other units, the source and @file{ALI} files of those must
16644 also be provided.
16646 The main purpose of a SAL is to minimize the recompilation overhead of client
16647 applications when a new version of the library is installed. Specifically,
16648 if the interface sources have not changed, client applications do not need to
16649 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16650 version, controlled by @code{Library_Version} attribute, is not changed,
16651 then the clients do not need to be relinked.
16653 SALs also allow the library providers to minimize the amount of library source
16654 text exposed to the clients.  Such ``information hiding'' might be useful or
16655 necessary for various reasons.
16657 Stand-alone libraries are also well suited to be used in an executable whose
16658 main routine is not written in Ada.
16660 @node Building a Stand-alone Library
16661 @subsection Building a Stand-alone Library
16663 @noindent
16664 GNAT's Project facility provides a simple way of building and installing
16665 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16666 To be a Stand-alone Library Project, in addition to the two attributes
16667 that make a project a Library Project (@code{Library_Name} and
16668 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16669 @code{Library_Interface} must be defined.  For example:
16671 @smallexample @c projectfile
16672 @group
16673    for Library_Dir use "lib_dir";
16674    for Library_Name use "dummy";
16675    for Library_Interface use ("int1", "int1.child");
16676 @end group
16677 @end smallexample
16679 @noindent
16680 Attribute @code{Library_Interface} has a non-empty string list value,
16681 each string in the list designating a unit contained in an immediate source
16682 of the project file.
16684 When a Stand-alone Library is built, first the binder is invoked to build
16685 a package whose name depends on the library name
16686 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16687 This binder-generated package includes initialization and
16688 finalization procedures whose
16689 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16690 in the example
16691 above). The object corresponding to this package is included in the library.
16693 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16694 calling of these procedures if a static SAL is built, or if a shared SAL
16695 is built
16696 with the project-level attribute @code{Library_Auto_Init} set to
16697 @code{"false"}.
16699 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16700 (those that are listed in attribute @code{Library_Interface}) are copied to
16701 the Library Directory. As a consequence, only the Interface Units may be
16702 imported from Ada units outside of the library. If other units are imported,
16703 the binding phase will fail.
16705 @noindent
16706 It is also possible to build an encapsulated library where not only
16707 the code to elaborate and finalize the library is embedded but also
16708 ensuring that the library is linked only against static
16709 libraries. So an encapsulated library only depends on system
16710 libraries, all other code, including the GNAT runtime, is embedded. To
16711 build an encapsulated library the attribute
16712 @code{Library_Standalone} must be set to @code{encapsulated}:
16714 @smallexample @c projectfile
16715 @group
16716    for Library_Dir use "lib_dir";
16717    for Library_Name use "dummy";
16718    for Library_Interface use ("int1", "int1.child");
16719    for Library_Standalone use "encapsulated";
16720 @end group
16721 @end smallexample
16723 @noindent
16724 The default value for this attribute is @code{standard} in which case
16725 a stand-alone library is built.
16727 The attribute @code{Library_Src_Dir} may be specified for a
16728 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16729 single string value. Its value must be the path (absolute or relative to the
16730 project directory) of an existing directory. This directory cannot be the
16731 object directory or one of the source directories, but it can be the same as
16732 the library directory. The sources of the Interface
16733 Units of the library that are needed by an Ada client of the library will be
16734 copied to the designated directory, called the Interface Copy directory.
16735 These sources include the specs of the Interface Units, but they may also
16736 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16737 are used, or when there is a generic unit in the spec. Before the sources
16738 are copied to the Interface Copy directory, an attempt is made to delete all
16739 files in the Interface Copy directory.
16741 Building stand-alone libraries by hand is somewhat tedious, but for those
16742 occasions when it is necessary here are the steps that you need to perform:
16743 @itemize @bullet
16744 @item
16745 Compile all library sources.
16747 @item
16748 Invoke the binder with the switch @option{-n} (No Ada main program),
16749 with all the @file{ALI} files of the interfaces, and
16750 with the switch @option{-L} to give specific names to the @code{init}
16751 and @code{final} procedures.  For example:
16752 @smallexample
16753   gnatbind -n int1.ali int2.ali -Lsal1
16754 @end smallexample
16756 @item
16757 Compile the binder generated file:
16758 @smallexample
16759   gcc -c b~int2.adb
16760 @end smallexample
16762 @item
16763 Link the dynamic library with all the necessary object files,
16764 indicating to the linker the names of the @code{init} (and possibly
16765 @code{final}) procedures for automatic initialization (and finalization).
16766 The built library should be placed in a directory different from
16767 the object directory.
16769 @item
16770 Copy the @code{ALI} files of the interface to the library directory,
16771 add in this copy an indication that it is an interface to a SAL
16772 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16773 with letter ``P'') and make the modified copy of the @file{ALI} file
16774 read-only.
16775 @end itemize
16777 @noindent
16778 Using SALs is not different from using other libraries
16779 (see @ref{Using a library}).
16781 @node Creating a Stand-alone Library to be used in a non-Ada context
16782 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16784 @noindent
16785 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16786 a non-Ada context.
16788 The only extra step required is to ensure that library interface subprograms
16789 are compatible with the main program, by means of @code{pragma Export}
16790 or @code{pragma Convention}.
16792 Here is an example of simple library interface for use with C main program:
16794 @smallexample @c ada
16795 package My_Package is
16797    procedure Do_Something;
16798    pragma Export (C, Do_Something, "do_something");
16800    procedure Do_Something_Else;
16801    pragma Export (C, Do_Something_Else, "do_something_else");
16803 end My_Package;
16804 @end smallexample
16806 @noindent
16807 On the foreign language side, you must provide a ``foreign'' view of the
16808 library interface; remember that it should contain elaboration routines in
16809 addition to interface subprograms.
16811 The example below shows the content of @code{mylib_interface.h} (note
16812 that there is no rule for the naming of this file, any name can be used)
16813 @smallexample
16814 /* the library elaboration procedure */
16815 extern void mylibinit (void);
16817 /* the library finalization procedure */
16818 extern void mylibfinal (void);
16820 /* the interface exported by the library */
16821 extern void do_something (void);
16822 extern void do_something_else (void);
16823 @end smallexample
16825 @noindent
16826 Libraries built as explained above can be used from any program, provided
16827 that the elaboration procedures (named @code{mylibinit} in the previous
16828 example) are called before the library services are used. Any number of
16829 libraries can be used simultaneously, as long as the elaboration
16830 procedure of each library is called.
16832 Below is an example of a C program that uses the @code{mylib} library.
16834 @smallexample
16835 #include "mylib_interface.h"
16838 main (void)
16840    /* First, elaborate the library before using it */
16841    mylibinit ();
16843    /* Main program, using the library exported entities */
16844    do_something ();
16845    do_something_else ();
16847    /* Library finalization at the end of the program */
16848    mylibfinal ();
16849    return 0;
16851 @end smallexample
16853 @noindent
16854 Note that invoking any library finalization procedure generated by
16855 @code{gnatbind} shuts down the Ada run-time environment.
16856 Consequently, the
16857 finalization of all Ada libraries must be performed at the end of the program.
16858 No call to these libraries or to the Ada run-time library should be made
16859 after the finalization phase.
16861 @node Restrictions in Stand-alone Libraries
16862 @subsection Restrictions in Stand-alone Libraries
16864 @noindent
16865 The pragmas listed below should be used with caution inside libraries,
16866 as they can create incompatibilities with other Ada libraries:
16867 @itemize @bullet
16868 @item pragma @code{Locking_Policy}
16869 @item pragma @code{Queuing_Policy}
16870 @item pragma @code{Task_Dispatching_Policy}
16871 @item pragma @code{Unreserve_All_Interrupts}
16872 @end itemize
16874 @noindent
16875 When using a library that contains such pragmas, the user must make sure
16876 that all libraries use the same pragmas with the same values. Otherwise,
16877 @code{Program_Error} will
16878 be raised during the elaboration of the conflicting
16879 libraries. The usage of these pragmas and its consequences for the user
16880 should therefore be well documented.
16882 Similarly, the traceback in the exception occurrence mechanism should be
16883 enabled or disabled in a consistent manner across all libraries.
16884 Otherwise, Program_Error will be raised during the elaboration of the
16885 conflicting libraries.
16887 If the @code{Version} or @code{Body_Version}
16888 attributes are used inside a library, then you need to
16889 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16890 libraries, so that version identifiers can be properly computed.
16891 In practice these attributes are rarely used, so this is unlikely
16892 to be a consideration.
16894 @node  Rebuilding the GNAT Run-Time Library
16895 @section Rebuilding the GNAT Run-Time Library
16896 @cindex GNAT Run-Time Library, rebuilding
16897 @cindex Building the GNAT Run-Time Library
16898 @cindex Rebuilding the GNAT Run-Time Library
16899 @cindex Run-Time Library, rebuilding
16901 @noindent
16902 It may be useful to recompile the GNAT library in various contexts, the
16903 most important one being the use of partition-wide configuration pragmas
16904 such as @code{Normalize_Scalars}. A special Makefile called
16905 @code{Makefile.adalib} is provided to that effect and can be found in
16906 the directory containing the GNAT library. The location of this
16907 directory depends on the way the GNAT environment has been installed and can
16908 be determined by means of the command:
16910 @smallexample
16911 $ gnatls -v
16912 @end smallexample
16914 @noindent
16915 The last entry in the object search path usually contains the
16916 gnat library. This Makefile contains its own documentation and in
16917 particular the set of instructions needed to rebuild a new library and
16918 to use it.
16920 @node Using the GNU make Utility
16921 @chapter Using the GNU @code{make} Utility
16922 @findex make
16924 @noindent
16925 This chapter offers some examples of makefiles that solve specific
16926 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16927 make, make, GNU @code{make}}), nor does it try to replace the
16928 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16930 All the examples in this section are specific to the GNU version of
16931 make. Although @command{make} is a standard utility, and the basic language
16932 is the same, these examples use some advanced features found only in
16933 @code{GNU make}.
16935 @menu
16936 * Using gnatmake in a Makefile::
16937 * Automatically Creating a List of Directories::
16938 * Generating the Command Line Switches::
16939 * Overcoming Command Line Length Limits::
16940 @end menu
16942 @node Using gnatmake in a Makefile
16943 @section Using gnatmake in a Makefile
16944 @findex makefile
16945 @cindex GNU make
16947 @noindent
16948 Complex project organizations can be handled in a very powerful way by
16949 using GNU make combined with gnatmake. For instance, here is a Makefile
16950 which allows you to build each subsystem of a big project into a separate
16951 shared library. Such a makefile allows you to significantly reduce the link
16952 time of very big applications while maintaining full coherence at
16953 each step of the build process.
16955 The list of dependencies are handled automatically by
16956 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16957 the appropriate directories.
16959 Note that you should also read the example on how to automatically
16960 create the list of directories
16961 (@pxref{Automatically Creating a List of Directories})
16962 which might help you in case your project has a lot of subdirectories.
16964 @smallexample
16965 @iftex
16966 @leftskip=0cm
16967 @font@heightrm=cmr8
16968 @heightrm
16969 @end iftex
16970 ## This Makefile is intended to be used with the following directory
16971 ## configuration:
16972 ##  - The sources are split into a series of csc (computer software components)
16973 ##    Each of these csc is put in its own directory.
16974 ##    Their name are referenced by the directory names.
16975 ##    They will be compiled into shared library (although this would also work
16976 ##    with static libraries
16977 ##  - The main program (and possibly other packages that do not belong to any
16978 ##    csc is put in the top level directory (where the Makefile is).
16979 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16980 ##                    \_ second_csc (sources) __ lib (will contain the library)
16981 ##                    \_ @dots{}
16982 ## Although this Makefile is build for shared library, it is easy to modify
16983 ## to build partial link objects instead (modify the lines with -shared and
16984 ## gnatlink below)
16986 ## With this makefile, you can change any file in the system or add any new
16987 ## file, and everything will be recompiled correctly (only the relevant shared
16988 ## objects will be recompiled, and the main program will be re-linked).
16990 # The list of computer software component for your project. This might be
16991 # generated automatically.
16992 CSC_LIST=aa bb cc
16994 # Name of the main program (no extension)
16995 MAIN=main
16997 # If we need to build objects with -fPIC, uncomment the following line
16998 #NEED_FPIC=-fPIC
17000 # The following variable should give the directory containing libgnat.so
17001 # You can get this directory through 'gnatls -v'. This is usually the last
17002 # directory in the Object_Path.
17003 GLIB=@dots{}
17005 # The directories for the libraries
17006 # (This macro expands the list of CSC to the list of shared libraries, you
17007 # could simply use the expanded form:
17008 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17009 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17011 $@{MAIN@}: objects $@{LIB_DIR@}
17012     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17013     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17015 objects::
17016     # recompile the sources
17017     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17019 # Note: In a future version of GNAT, the following commands will be simplified
17020 # by a new tool, gnatmlib
17021 $@{LIB_DIR@}:
17022     mkdir -p $@{dir $@@ @}
17023     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17024     cd $@{dir $@@ @} && cp -f ../*.ali .
17026 # The dependencies for the modules
17027 # Note that we have to force the expansion of *.o, since in some cases
17028 # make won't be able to do it itself.
17029 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17030 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17031 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17033 # Make sure all of the shared libraries are in the path before starting the
17034 # program
17035 run::
17036     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17038 clean::
17039     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17040     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17041     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17042     $@{RM@} *.o *.ali $@{MAIN@}
17043 @end smallexample
17045 @node Automatically Creating a List of Directories
17046 @section Automatically Creating a List of Directories
17048 @noindent
17049 In most makefiles, you will have to specify a list of directories, and
17050 store it in a variable. For small projects, it is often easier to
17051 specify each of them by hand, since you then have full control over what
17052 is the proper order for these directories, which ones should be
17053 included.
17055 However, in larger projects, which might involve hundreds of
17056 subdirectories, it might be more convenient to generate this list
17057 automatically.
17059 The example below presents two methods. The first one, although less
17060 general, gives you more control over the list. It involves wildcard
17061 characters, that are automatically expanded by @command{make}. Its
17062 shortcoming is that you need to explicitly specify some of the
17063 organization of your project, such as for instance the directory tree
17064 depth, whether some directories are found in a separate tree, @enddots{}
17066 The second method is the most general one. It requires an external
17067 program, called @command{find}, which is standard on all Unix systems. All
17068 the directories found under a given root directory will be added to the
17069 list.
17071 @smallexample
17072 @iftex
17073 @leftskip=0cm
17074 @font@heightrm=cmr8
17075 @heightrm
17076 @end iftex
17077 # The examples below are based on the following directory hierarchy:
17078 # All the directories can contain any number of files
17079 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17080 #                       ->  ab
17081 #                       ->  ac
17082 #                ->  b  ->  ba  ->  baa
17083 #                       ->  bb
17084 #                       ->  bc
17085 # This Makefile creates a variable called DIRS, that can be reused any time
17086 # you need this list (see the other examples in this section)
17088 # The root of your project's directory hierarchy
17089 ROOT_DIRECTORY=.
17091 ####
17092 # First method: specify explicitly the list of directories
17093 # This allows you to specify any subset of all the directories you need.
17094 ####
17096 DIRS := a/aa/ a/ab/ b/ba/
17098 ####
17099 # Second method: use wildcards
17100 # Note that the argument(s) to wildcard below should end with a '/'.
17101 # Since wildcards also return file names, we have to filter them out
17102 # to avoid duplicate directory names.
17103 # We thus use make's @code{dir} and @code{sort} functions.
17104 # It sets DIRs to the following value (note that the directories aaa and baa
17105 # are not given, unless you change the arguments to wildcard).
17106 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17107 ####
17109 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17110                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17112 ####
17113 # Third method: use an external program
17114 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17115 # This is the most complete command: it sets DIRs to the following value:
17116 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17117 ####
17119 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17121 @end smallexample
17123 @node Generating the Command Line Switches
17124 @section Generating the Command Line Switches
17126 @noindent
17127 Once you have created the list of directories as explained in the
17128 previous section (@pxref{Automatically Creating a List of Directories}),
17129 you can easily generate the command line arguments to pass to gnatmake.
17131 For the sake of completeness, this example assumes that the source path
17132 is not the same as the object path, and that you have two separate lists
17133 of directories.
17135 @smallexample
17136 # see "Automatically creating a list of directories" to create
17137 # these variables
17138 SOURCE_DIRS=
17139 OBJECT_DIRS=
17141 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17142 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17144 all:
17145         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17146 @end smallexample
17148 @node Overcoming Command Line Length Limits
17149 @section Overcoming Command Line Length Limits
17151 @noindent
17152 One problem that might be encountered on big projects is that many
17153 operating systems limit the length of the command line. It is thus hard to give
17154 gnatmake the list of source and object directories.
17156 This example shows how you can set up environment variables, which will
17157 make @command{gnatmake} behave exactly as if the directories had been
17158 specified on the command line, but have a much higher length limit (or
17159 even none on most systems).
17161 It assumes that you have created a list of directories in your Makefile,
17162 using one of the methods presented in
17163 @ref{Automatically Creating a List of Directories}.
17164 For the sake of completeness, we assume that the object
17165 path (where the ALI files are found) is different from the sources patch.
17167 Note a small trick in the Makefile below: for efficiency reasons, we
17168 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17169 expanded immediately by @code{make}. This way we overcome the standard
17170 make behavior which is to expand the variables only when they are
17171 actually used.
17173 On Windows, if you are using the standard Windows command shell, you must
17174 replace colons with semicolons in the assignments to these variables.
17176 @smallexample
17177 @iftex
17178 @leftskip=0cm
17179 @font@heightrm=cmr8
17180 @heightrm
17181 @end iftex
17182 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17183 # This is the same thing as putting the -I arguments on the command line.
17184 # (the equivalent of using -aI on the command line would be to define
17185 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17186 # You can of course have different values for these variables.
17188 # Note also that we need to keep the previous values of these variables, since
17189 # they might have been set before running 'make' to specify where the GNAT
17190 # library is installed.
17192 # see "Automatically creating a list of directories" to create these
17193 # variables
17194 SOURCE_DIRS=
17195 OBJECT_DIRS=
17197 empty:=
17198 space:=$@{empty@} $@{empty@}
17199 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17200 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17201 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17202 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17203 export ADA_INCLUDE_PATH
17204 export ADA_OBJECTS_PATH
17206 all:
17207         gnatmake main_unit
17208 @end smallexample
17209 @end ifclear
17211 @node Memory Management Issues
17212 @chapter Memory Management Issues
17214 @noindent
17215 This chapter describes some useful memory pools provided in the GNAT library
17216 and in particular the GNAT Debug Pool facility, which can be used to detect
17217 incorrect uses of access values (including ``dangling references'').
17218 @ifclear vms
17219 It also describes the @command{gnatmem} tool, which can be used to track down
17220 ``memory leaks''.
17221 @end ifclear
17223 @menu
17224 * Some Useful Memory Pools::
17225 * The GNAT Debug Pool Facility::
17226 @ifclear vms
17227 * The gnatmem Tool::
17228 @end ifclear
17229 @end menu
17231 @node Some Useful Memory Pools
17232 @section Some Useful Memory Pools
17233 @findex Memory Pool
17234 @cindex storage, pool
17236 @noindent
17237 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17238 storage pool. Allocations use the standard system call @code{malloc} while
17239 deallocations use the standard system call @code{free}. No reclamation is
17240 performed when the pool goes out of scope. For performance reasons, the
17241 standard default Ada allocators/deallocators do not use any explicit storage
17242 pools but if they did, they could use this storage pool without any change in
17243 behavior. That is why this storage pool is used  when the user
17244 manages to make the default implicit allocator explicit as in this example:
17245 @smallexample @c ada
17246    type T1 is access Something;
17247     -- no Storage pool is defined for T2
17248    type T2 is access Something_Else;
17249    for T2'Storage_Pool use T1'Storage_Pool;
17250    -- the above is equivalent to
17251    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17252 @end smallexample
17254 @noindent
17255 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17256 pool. The allocation strategy is similar to @code{Pool_Local}'s
17257 except that the all
17258 storage allocated with this pool is reclaimed when the pool object goes out of
17259 scope. This pool provides a explicit mechanism similar to the implicit one
17260 provided by several Ada 83 compilers for allocations performed through a local
17261 access type and whose purpose was to reclaim memory when exiting the
17262 scope of a given local access. As an example, the following program does not
17263 leak memory even though it does not perform explicit deallocation:
17265 @smallexample @c ada
17266 with System.Pool_Local;
17267 procedure Pooloc1 is
17268    procedure Internal is
17269       type A is access Integer;
17270       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17271       for A'Storage_Pool use X;
17272       v : A;
17273    begin
17274       for I in  1 .. 50 loop
17275          v := new Integer;
17276       end loop;
17277    end Internal;
17278 begin
17279    for I in  1 .. 100 loop
17280       Internal;
17281    end loop;
17282 end Pooloc1;
17283 @end smallexample
17285 @noindent
17286 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17287 @code{Storage_Size} is specified for an access type.
17288 The whole storage for the pool is
17289 allocated at once, usually on the stack at the point where the access type is
17290 elaborated. It is automatically reclaimed when exiting the scope where the
17291 access type is defined. This package is not intended to be used directly by the
17292 user and it is implicitly used for each such declaration:
17294 @smallexample @c ada
17295    type T1 is access Something;
17296    for T1'Storage_Size use 10_000;
17297 @end smallexample
17299 @node The GNAT Debug Pool Facility
17300 @section The GNAT Debug Pool Facility
17301 @findex Debug Pool
17302 @cindex storage, pool, memory corruption
17304 @noindent
17305 The use of unchecked deallocation and unchecked conversion can easily
17306 lead to incorrect memory references. The problems generated by such
17307 references are usually difficult to tackle because the symptoms can be
17308 very remote from the origin of the problem. In such cases, it is
17309 very helpful to detect the problem as early as possible. This is the
17310 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17312 In order to use the GNAT specific debugging pool, the user must
17313 associate a debug pool object with each of the access types that may be
17314 related to suspected memory problems. See Ada Reference Manual 13.11.
17315 @smallexample @c ada
17316 type Ptr is access Some_Type;
17317 Pool : GNAT.Debug_Pools.Debug_Pool;
17318 for Ptr'Storage_Pool use Pool;
17319 @end smallexample
17321 @noindent
17322 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17323 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17324 allow the user to redefine allocation and deallocation strategies. They
17325 also provide a checkpoint for each dereference, through the use of
17326 the primitive operation @code{Dereference} which is implicitly called at
17327 each dereference of an access value.
17329 Once an access type has been associated with a debug pool, operations on
17330 values of the type may raise four distinct exceptions,
17331 which correspond to four potential kinds of memory corruption:
17332 @itemize @bullet
17333 @item
17334 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17335 @item
17336 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17337 @item
17338 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17339 @item
17340 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17341 @end itemize
17343 @noindent
17344 For types associated with a Debug_Pool, dynamic allocation is performed using
17345 the standard GNAT allocation routine. References to all allocated chunks of
17346 memory are kept in an internal dictionary. Several deallocation strategies are
17347 provided, whereupon the user can choose to release the memory to the system,
17348 keep it allocated for further invalid access checks, or fill it with an easily
17349 recognizable pattern for debug sessions. The memory pattern is the old IBM
17350 hexadecimal convention: @code{16#DEADBEEF#}.
17352 See the documentation in the file g-debpoo.ads for more information on the
17353 various strategies.
17355 Upon each dereference, a check is made that the access value denotes a
17356 properly allocated memory location. Here is a complete example of use of
17357 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17358 @smallexample @c ada
17359 @iftex
17360 @leftskip=0cm
17361 @end iftex
17362 with Gnat.Io; use Gnat.Io;
17363 with Unchecked_Deallocation;
17364 with Unchecked_Conversion;
17365 with GNAT.Debug_Pools;
17366 with System.Storage_Elements;
17367 with Ada.Exceptions; use Ada.Exceptions;
17368 procedure Debug_Pool_Test is
17370    type T is access Integer;
17371    type U is access all T;
17373    P : GNAT.Debug_Pools.Debug_Pool;
17374    for T'Storage_Pool use P;
17376    procedure Free is new Unchecked_Deallocation (Integer, T);
17377    function UC is new Unchecked_Conversion (U, T);
17378    A, B : aliased T;
17380    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17382 begin
17383    Info (P);
17384    A := new Integer;
17385    B := new Integer;
17386    B := A;
17387    Info (P);
17388    Free (A);
17389    begin
17390       Put_Line (Integer'Image(B.all));
17391    exception
17392       when E : others => Put_Line ("raised: " & Exception_Name (E));
17393    end;
17394    begin
17395       Free (B);
17396    exception
17397       when E : others => Put_Line ("raised: " & Exception_Name (E));
17398    end;
17399    B := UC(A'Access);
17400    begin
17401       Put_Line (Integer'Image(B.all));
17402    exception
17403       when E : others => Put_Line ("raised: " & Exception_Name (E));
17404    end;
17405    begin
17406       Free (B);
17407    exception
17408       when E : others => Put_Line ("raised: " & Exception_Name (E));
17409    end;
17410    Info (P);
17411 end Debug_Pool_Test;
17412 @end smallexample
17414 @noindent
17415 The debug pool mechanism provides the following precise diagnostics on the
17416 execution of this erroneous program:
17417 @smallexample
17418 Debug Pool info:
17419   Total allocated bytes :  0
17420   Total deallocated bytes :  0
17421   Current Water Mark:  0
17422   High Water Mark:  0
17424 Debug Pool info:
17425   Total allocated bytes :  8
17426   Total deallocated bytes :  0
17427   Current Water Mark:  8
17428   High Water Mark:  8
17430 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17431 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17432 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17433 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17434 Debug Pool info:
17435   Total allocated bytes :  8
17436   Total deallocated bytes :  4
17437   Current Water Mark:  4
17438   High Water Mark:  8
17439 @end smallexample
17441 @ifclear vms
17442 @node The gnatmem Tool
17443 @section The @command{gnatmem} Tool
17444 @findex gnatmem
17446 @noindent
17447 The @code{gnatmem} utility monitors dynamic allocation and
17448 deallocation activity in a program, and displays information about
17449 incorrect deallocations and possible sources of memory leaks.
17450 It is designed to work in association with a static runtime library
17451 only and in this context provides three types of information:
17452 @itemize @bullet
17453 @item
17454 General information concerning memory management, such as the total
17455 number of allocations and deallocations, the amount of allocated
17456 memory and the high water mark, i.e.@: the largest amount of allocated
17457 memory in the course of program execution.
17459 @item
17460 Backtraces for all incorrect deallocations, that is to say deallocations
17461 which do not correspond to a valid allocation.
17463 @item
17464 Information on each allocation that is potentially the origin of a memory
17465 leak.
17466 @end itemize
17468 @menu
17469 * Running gnatmem::
17470 * Switches for gnatmem::
17471 * Example of gnatmem Usage::
17472 @end menu
17474 @node Running gnatmem
17475 @subsection Running @code{gnatmem}
17477 @noindent
17478 @code{gnatmem} makes use of the output created by the special version of
17479 allocation and deallocation routines that record call information. This
17480 allows to obtain accurate dynamic memory usage history at a minimal cost to
17481 the execution speed. Note however, that @code{gnatmem} is not supported on
17482 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17483 Solaris and Windows NT/2000/XP (x86).
17485 @noindent
17486 The @code{gnatmem} command has the form
17488 @smallexample
17489 @c    $ gnatmem @ovar{switches} user_program
17490 @c Expanding @ovar macro inline (explanation in macro def comments)
17491       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17492 @end smallexample
17494 @noindent
17495 The program must have been linked with the instrumented version of the
17496 allocation and deallocation routines. This is done by linking with the
17497 @file{libgmem.a} library. For correct symbolic backtrace information,
17498 the user program should be compiled with debugging options
17499 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17501 @smallexample
17502 $ gnatmake -g my_program -largs -lgmem
17503 @end smallexample
17505 @noindent
17506 As library @file{libgmem.a} contains an alternate body for package
17507 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17508 when an executable is linked with library @file{libgmem.a}. It is then not
17509 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17511 @noindent
17512 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17513 This file contains information about all allocations and deallocations
17514 performed by the program. It is produced by the instrumented allocations and
17515 deallocations routines and will be used by @code{gnatmem}.
17517 In order to produce symbolic backtrace information for allocations and
17518 deallocations performed by the GNAT run-time library, you need to use a
17519 version of that library that has been compiled with the @option{-g} switch
17520 (see @ref{Rebuilding the GNAT Run-Time Library}).
17522 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17523 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17524 @option{-i} switch, gnatmem will assume that this file can be found in the
17525 current directory. For example, after you have executed @file{my_program},
17526 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17528 @smallexample
17529 $ gnatmem my_program
17530 @end smallexample
17532 @noindent
17533 This will produce the output with the following format:
17535 *************** debut cc
17536 @smallexample
17537 $ gnatmem my_program
17539 Global information
17540 ------------------
17541    Total number of allocations        :  45
17542    Total number of deallocations      :   6
17543    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17544    High Water Mark                    :  11.40 Kilobytes
17549 Allocation Root # 2
17550 -------------------
17551  Number of non freed allocations    :  11
17552  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17553  High Water Mark                    :   1.27 Kilobytes
17554  Backtrace                          :
17555    my_program.adb:23 my_program.alloc
17559 @end smallexample
17561 The first block of output gives general information. In this case, the
17562 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17563 Unchecked_Deallocation routine occurred.
17565 @noindent
17566 Subsequent paragraphs display  information on all allocation roots.
17567 An allocation root is a specific point in the execution of the program
17568 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17569 construct. This root is represented by an execution backtrace (or subprogram
17570 call stack). By default the backtrace depth for allocations roots is 1, so
17571 that a root corresponds exactly to a source location. The backtrace can
17572 be made deeper, to make the root more specific.
17574 @node Switches for gnatmem
17575 @subsection Switches for @code{gnatmem}
17577 @noindent
17578 @code{gnatmem} recognizes the following switches:
17580 @table @option
17582 @item -q
17583 @cindex @option{-q} (@code{gnatmem})
17584 Quiet. Gives the minimum output needed to identify the origin of the
17585 memory leaks. Omits statistical information.
17587 @item @var{N}
17588 @cindex @var{N} (@code{gnatmem})
17589 N is an integer literal (usually between 1 and 10) which controls the
17590 depth of the backtraces defining allocation root. The default value for
17591 N is 1. The deeper the backtrace, the more precise the localization of
17592 the root. Note that the total number of roots can depend on this
17593 parameter. This parameter must be specified @emph{before} the name of the
17594 executable to be analyzed, to avoid ambiguity.
17596 @item -b n
17597 @cindex @option{-b} (@code{gnatmem})
17598 This switch has the same effect as just depth parameter.
17600 @item -i @var{file}
17601 @cindex @option{-i} (@code{gnatmem})
17602 Do the @code{gnatmem} processing starting from @file{file}, rather than
17603 @file{gmem.out} in the current directory.
17605 @item -m n
17606 @cindex @option{-m} (@code{gnatmem})
17607 This switch causes @code{gnatmem} to mask the allocation roots that have less
17608 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17609 examine even the roots that didn't result in leaks.
17611 @item -s order
17612 @cindex @option{-s} (@code{gnatmem})
17613 This switch causes @code{gnatmem} to sort the allocation roots according to the
17614 specified order of sort criteria, each identified by a single letter. The
17615 currently supported criteria are @code{n, h, w} standing respectively for
17616 number of unfreed allocations, high watermark, and final watermark
17617 corresponding to a specific root. The default order is @code{nwh}.
17619 @end table
17621 @node Example of gnatmem Usage
17622 @subsection Example of @code{gnatmem} Usage
17624 @noindent
17625 The following example shows the use of @code{gnatmem}
17626 on a simple memory-leaking program.
17627 Suppose that we have the following Ada program:
17629 @smallexample @c ada
17630 @group
17631 @cartouche
17632 with Unchecked_Deallocation;
17633 procedure Test_Gm is
17635    type T is array (1..1000) of Integer;
17636    type Ptr is access T;
17637    procedure Free is new Unchecked_Deallocation (T, Ptr);
17638    A : Ptr;
17640    procedure My_Alloc is
17641    begin
17642       A := new T;
17643    end My_Alloc;
17645    procedure My_DeAlloc is
17646       B : Ptr := A;
17647    begin
17648       Free (B);
17649    end My_DeAlloc;
17651 begin
17652    My_Alloc;
17653    for I in 1 .. 5 loop
17654       for J in I .. 5 loop
17655          My_Alloc;
17656       end loop;
17657       My_Dealloc;
17658    end loop;
17659 end;
17660 @end cartouche
17661 @end group
17662 @end smallexample
17664 @noindent
17665 The program needs to be compiled with debugging option and linked with
17666 @code{gmem} library:
17668 @smallexample
17669 $ gnatmake -g test_gm -largs -lgmem
17670 @end smallexample
17672 @noindent
17673 Then we execute the program as usual:
17675 @smallexample
17676 $ test_gm
17677 @end smallexample
17679 @noindent
17680 Then @code{gnatmem} is invoked simply with
17681 @smallexample
17682 $ gnatmem test_gm
17683 @end smallexample
17685 @noindent
17686 which produces the following output (result may vary on different platforms):
17688 @smallexample
17689 Global information
17690 ------------------
17691    Total number of allocations        :  18
17692    Total number of deallocations      :   5
17693    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17694    High Water Mark                    :  56.90 Kilobytes
17696 Allocation Root # 1
17697 -------------------
17698  Number of non freed allocations    :  11
17699  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17700  High Water Mark                    :  46.88 Kilobytes
17701  Backtrace                          :
17702    test_gm.adb:11 test_gm.my_alloc
17704 Allocation Root # 2
17705 -------------------
17706  Number of non freed allocations    :   1
17707  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17708  High Water Mark                    :  10.02 Kilobytes
17709  Backtrace                          :
17710    s-secsta.adb:81 system.secondary_stack.ss_init
17712 Allocation Root # 3
17713 -------------------
17714  Number of non freed allocations    :   1
17715  Final Water Mark (non freed mem)   :  12 Bytes
17716  High Water Mark                    :  12 Bytes
17717  Backtrace                          :
17718    s-secsta.adb:181 system.secondary_stack.ss_init
17719 @end smallexample
17721 @noindent
17722 Note that the GNAT run time contains itself a certain number of
17723 allocations that have no  corresponding deallocation,
17724 as shown here for root #2 and root
17725 #3. This is a normal behavior when the number of non-freed allocations
17726 is one, it allocates dynamic data structures that the run time needs for
17727 the complete lifetime of the program. Note also that there is only one
17728 allocation root in the user program with a single line back trace:
17729 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17730 program shows that 'My_Alloc' is called at 2 different points in the
17731 source (line 21 and line 24). If those two allocation roots need to be
17732 distinguished, the backtrace depth parameter can be used:
17734 @smallexample
17735 $ gnatmem 3 test_gm
17736 @end smallexample
17738 @noindent
17739 which will give the following output:
17741 @smallexample
17742 Global information
17743 ------------------
17744    Total number of allocations        :  18
17745    Total number of deallocations      :   5
17746    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17747    High Water Mark                    :  56.90 Kilobytes
17749 Allocation Root # 1
17750 -------------------
17751  Number of non freed allocations    :  10
17752  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17753  High Water Mark                    :  42.97 Kilobytes
17754  Backtrace                          :
17755    test_gm.adb:11 test_gm.my_alloc
17756    test_gm.adb:24 test_gm
17757    b_test_gm.c:52 main
17759 Allocation Root # 2
17760 -------------------
17761  Number of non freed allocations    :   1
17762  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17763  High Water Mark                    :  10.02 Kilobytes
17764  Backtrace                          :
17765    s-secsta.adb:81  system.secondary_stack.ss_init
17766    s-secsta.adb:283 <system__secondary_stack___elabb>
17767    b_test_gm.c:33   adainit
17769 Allocation Root # 3
17770 -------------------
17771  Number of non freed allocations    :   1
17772  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17773  High Water Mark                    :   3.91 Kilobytes
17774  Backtrace                          :
17775    test_gm.adb:11 test_gm.my_alloc
17776    test_gm.adb:21 test_gm
17777    b_test_gm.c:52 main
17779 Allocation Root # 4
17780 -------------------
17781  Number of non freed allocations    :   1
17782  Final Water Mark (non freed mem)   :  12 Bytes
17783  High Water Mark                    :  12 Bytes
17784  Backtrace                          :
17785    s-secsta.adb:181 system.secondary_stack.ss_init
17786    s-secsta.adb:283 <system__secondary_stack___elabb>
17787    b_test_gm.c:33   adainit
17788 @end smallexample
17790 @noindent
17791 The allocation root #1 of the first example has been split in 2 roots #1
17792 and #3 thanks to the more precise associated backtrace.
17794 @end ifclear
17796 @node Stack Related Facilities
17797 @chapter Stack Related Facilities
17799 @noindent
17800 This chapter describes some useful tools associated with stack
17801 checking and analysis. In
17802 particular, it deals with dynamic and static stack usage measurements.
17804 @menu
17805 * Stack Overflow Checking::
17806 * Static Stack Usage Analysis::
17807 * Dynamic Stack Usage Analysis::
17808 @end menu
17810 @node Stack Overflow Checking
17811 @section Stack Overflow Checking
17812 @cindex Stack Overflow Checking
17813 @cindex -fstack-check
17815 @noindent
17816 For most operating systems, @command{gcc} does not perform stack overflow
17817 checking by default. This means that if the main environment task or
17818 some other task exceeds the available stack space, then unpredictable
17819 behavior will occur. Most native systems offer some level of protection by
17820 adding a guard page at the end of each task stack. This mechanism is usually
17821 not enough for dealing properly with stack overflow situations because
17822 a large local variable could ``jump'' above the guard page.
17823 Furthermore, when the
17824 guard page is hit, there may not be any space left on the stack for executing
17825 the exception propagation code. Enabling stack checking avoids
17826 such situations.
17828 To activate stack checking, compile all units with the gcc option
17829 @option{-fstack-check}. For example:
17831 @smallexample
17832 gcc -c -fstack-check package1.adb
17833 @end smallexample
17835 @noindent
17836 Units compiled with this option will generate extra instructions to check
17837 that any use of the stack (for procedure calls or for declaring local
17838 variables in declare blocks) does not exceed the available stack space.
17839 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17841 For declared tasks, the stack size is controlled by the size
17842 given in an applicable @code{Storage_Size} pragma or by the value specified
17843 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17844 the default size as defined in the GNAT runtime otherwise.
17846 For the environment task, the stack size depends on
17847 system defaults and is unknown to the compiler. Stack checking
17848 may still work correctly if a fixed
17849 size stack is allocated, but this cannot be guaranteed.
17850 @ifclear vms
17851 To ensure that a clean exception is signalled for stack
17852 overflow, set the environment variable
17853 @env{GNAT_STACK_LIMIT} to indicate the maximum
17854 stack area that can be used, as in:
17855 @cindex GNAT_STACK_LIMIT
17857 @smallexample
17858 SET GNAT_STACK_LIMIT 1600
17859 @end smallexample
17861 @noindent
17862 The limit is given in kilobytes, so the above declaration would
17863 set the stack limit of the environment task to 1.6 megabytes.
17864 Note that the only purpose of this usage is to limit the amount
17865 of stack used by the environment task. If it is necessary to
17866 increase the amount of stack for the environment task, then this
17867 is an operating systems issue, and must be addressed with the
17868 appropriate operating systems commands.
17869 @end ifclear
17870 @ifset vms
17871 To have a fixed size stack in the environment task, the stack must be put
17872 in the P0 address space and its size specified.  Use these switches to
17873 create a p0 image:
17875 @smallexample
17876 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17877 @end smallexample
17879 @noindent
17880 The quotes are required to keep case.  The number after @samp{STACK=} is the
17881 size of the environmental task stack in pagelets (512 bytes).  In this example
17882 the stack size is about 2 megabytes.
17884 @noindent
17885 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17886 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17887 more details about the @option{/p0image} qualifier and the @option{stack}
17888 option.
17890 @noindent
17891 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17892 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17893 stack in kilobytes.  For example:
17895 @smallexample
17896 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17897 @end smallexample
17898 @end ifset
17900 @node Static Stack Usage Analysis
17901 @section Static Stack Usage Analysis
17902 @cindex Static Stack Usage Analysis
17903 @cindex -fstack-usage
17905 @noindent
17906 A unit compiled with @option{-fstack-usage} will generate an extra file
17907 that specifies
17908 the maximum amount of stack used, on a per-function basis.
17909 The file has the same
17910 basename as the target object file with a @file{.su} extension.
17911 Each line of this file is made up of three fields:
17913 @itemize
17914 @item
17915 The name of the function.
17916 @item
17917 A number of bytes.
17918 @item
17919 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17920 @end itemize
17922 The second field corresponds to the size of the known part of the function
17923 frame.
17925 The qualifier @code{static} means that the function frame size
17926 is purely static.
17927 It usually means that all local variables have a static size.
17928 In this case, the second field is a reliable measure of the function stack
17929 utilization.
17931 The qualifier @code{dynamic} means that the function frame size is not static.
17932 It happens mainly when some local variables have a dynamic size. When this
17933 qualifier appears alone, the second field is not a reliable measure
17934 of the function stack analysis. When it is qualified with  @code{bounded}, it
17935 means that the second field is a reliable maximum of the function stack
17936 utilization.
17938 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17939 subprogram whose stack usage might be larger than the specified amount of
17940 bytes.  The wording is in keeping with the qualifier documented above.
17942 @node Dynamic Stack Usage Analysis
17943 @section Dynamic Stack Usage Analysis
17945 @noindent
17946 It is possible to measure the maximum amount of stack used by a task, by
17947 adding a switch to @command{gnatbind}, as:
17949 @smallexample
17950 $ gnatbind -u0 file
17951 @end smallexample
17953 @noindent
17954 With this option, at each task termination, its stack usage is  output on
17955 @file{stderr}.
17956 It is not always convenient to output the stack usage when the program
17957 is still running. Hence, it is possible to delay this output until program
17958 termination. for a given number of tasks specified as the argument of the
17959 @option{-u} option. For instance:
17961 @smallexample
17962 $ gnatbind -u100 file
17963 @end smallexample
17965 @noindent
17966 will buffer the stack usage information of the first 100 tasks to terminate and
17967 output this info at program termination. Results are displayed in four
17968 columns:
17970 @noindent
17971 Index | Task Name | Stack Size | Stack Usage
17973 @noindent
17974 where:
17976 @table @emph
17977 @item Index
17978 is a number associated with each task.
17980 @item Task Name
17981 is the name of the task analyzed.
17983 @item Stack Size
17984 is the maximum size for the stack.
17986 @item Stack Usage
17987 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17988 is not entirely analyzed, and it's not possible to know exactly how
17989 much has actually been used.
17991 @end table
17993 @noindent
17994 The environment task stack, e.g., the stack that contains the main unit, is
17995 only processed when the environment variable GNAT_STACK_LIMIT is set.
17997 @noindent
17998 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17999 stack usage reports at run-time. See its body for the details.
18001 @c *********************************
18002 @c *            GNATCHECK          *
18003 @c *********************************
18004 @node Verifying Properties Using gnatcheck
18005 @chapter Verifying Properties Using @command{gnatcheck}
18006 @findex gnatcheck
18007 @cindex @command{gnatcheck}
18009 @noindent
18010 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18011 of Ada source files according to a given set of semantic rules.
18012 @cindex ASIS
18014 In order to check compliance with a given rule, @command{gnatcheck} has to
18015 semantically analyze the Ada sources.
18016 Therefore, checks can only be performed on
18017 legal Ada units. Moreover, when a unit depends semantically upon units located
18018 outside the current directory, the source search path has to be provided when
18019 calling @command{gnatcheck}, either through a specified project file or
18020 through @command{gnatcheck} switches.
18022 For full details, refer to @cite{GNATcheck Reference Manual} document.
18025 @c *********************************
18026 @node Creating Sample Bodies Using gnatstub
18027 @chapter Creating Sample Bodies Using @command{gnatstub}
18028 @findex gnatstub
18030 @noindent
18031 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18032 for library unit declarations.
18034 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
18035 driver (see @ref{The GNAT Driver and Project Files}).
18037 To create a body stub, @command{gnatstub} has to compile the library
18038 unit declaration. Therefore, bodies can be created only for legal
18039 library units. Moreover, if a library unit depends semantically upon
18040 units located outside the current directory, you have to provide
18041 the source search path when calling @command{gnatstub}, see the description
18042 of @command{gnatstub} switches below.
18044 By default, all the program unit body stubs generated by @code{gnatstub}
18045 raise the predefined @code{Program_Error} exception, which will catch
18046 accidental calls of generated stubs. This behavior can be changed with
18047 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
18049 @menu
18050 * Running gnatstub::
18051 * Switches for gnatstub::
18052 @end menu
18054 @node Running gnatstub
18055 @section Running @command{gnatstub}
18057 @noindent
18058 @command{gnatstub} has a command-line interface of the form:
18060 @smallexample
18061 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
18062 @c Expanding @ovar macro inline (explanation in macro def comments)
18063 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18064 @end smallexample
18066 @noindent
18067 where
18068 @table @var
18069 @item filename
18070 is the name of the source file that contains a library unit declaration
18071 for which a body must be created. The file name may contain the path
18072 information.
18073 The file name does not have to follow the GNAT file name conventions. If the
18074 name
18075 does not follow GNAT file naming conventions, the name of the body file must
18076 be provided
18077 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18078 If the file name follows the GNAT file naming
18079 conventions and the name of the body file is not provided,
18080 @command{gnatstub}
18081 creates the name
18082 of the body file from the argument file name by replacing the @file{.ads}
18083 suffix
18084 with the @file{.adb} suffix.
18086 @item directory
18087 indicates the directory in which the body stub is to be placed (the default
18088 is the
18089 current directory)
18091 @item @samp{@var{gcc_switches}} is a list of switches for
18092 @command{gcc}. They will be passed on to all compiler invocations made by
18093 @command{gnatstub} to generate the ASIS trees. Here you can provide
18094 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18095 use the @option{-gnatec} switch to set the configuration file,
18096 use the @option{-gnat05} switch if sources should be compiled in
18097 Ada 2005 mode etc.
18099 @item switches
18100 is an optional sequence of switches as described in the next section
18101 @end table
18103 @node Switches for gnatstub
18104 @section Switches for @command{gnatstub}
18106 @table @option
18107 @c !sort!
18109 @item ^-f^/FULL^
18110 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18111 If the destination directory already contains a file with the name of the
18112 body file
18113 for the argument spec file, replace it with the generated body stub.
18115 @item ^-hs^/HEADER=SPEC^
18116 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18117 Put the comment header (i.e., all the comments preceding the
18118 compilation unit) from the source of the library unit declaration
18119 into the body stub.
18121 @item ^-hg^/HEADER=GENERAL^
18122 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18123 Put a sample comment header into the body stub.
18125 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
18126 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
18127 Use the content of the file as the comment header for a generated body stub.
18129 @ifclear vms
18130 @item -IDIR
18131 @cindex @option{-IDIR} (@command{gnatstub})
18132 @itemx -I-
18133 @cindex @option{-I-} (@command{gnatstub})
18134 @end ifclear
18135 @ifset vms
18136 @item /NOCURRENT_DIRECTORY
18137 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18138 @end ifset
18139 ^These switches have ^This switch has^ the same meaning as in calls to
18140 @command{gcc}.
18141 ^They define ^It defines ^ the source search path in the call to
18142 @command{gcc} issued
18143 by @command{gnatstub} to compile an argument source file.
18145 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18146 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18147 This switch has the same meaning as in calls to @command{gcc}.
18148 It defines the additional configuration file to be passed to the call to
18149 @command{gcc} issued
18150 by @command{gnatstub} to compile an argument source file.
18152 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18153 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18154 (@var{n} is a non-negative integer). Set the maximum line length in the
18155 body stub to @var{n}; the default is 79. The maximum value that can be
18156 specified is 32767. Note that in the special case of configuration
18157 pragma files, the maximum is always 32767 regardless of whether or
18158 not this switch appears.
18160 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18161 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18162 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18163 the generated body sample to @var{n}.
18164 The default indentation is 3.
18166 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18167 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18168 Order local bodies alphabetically. (By default local bodies are ordered
18169 in the same way as the corresponding local specs in the argument spec file.)
18171 @item ^-i^/INDENTATION=^@var{n}
18172 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18173 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18175 @item ^-k^/TREE_FILE=SAVE^
18176 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18177 Do not remove the tree file (i.e., the snapshot of the compiler internal
18178 structures used by @command{gnatstub}) after creating the body stub.
18180 @item ^-l^/LINE_LENGTH=^@var{n}
18181 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18182 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18184 @item ^--no-exception^/NO_EXCEPTION^
18185 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
18186 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18187 This is not always possible for function stubs.
18189 @item ^--no-local-header^/NO_LOCAL_HEADER^
18190 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
18191 Do not place local comment header with unit name before body stub for a
18192 unit.
18194 @item ^-o ^/BODY=^@var{body-name}
18195 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18196 Body file name.  This should be set if the argument file name does not
18197 follow
18198 the GNAT file naming
18199 conventions. If this switch is omitted the default name for the body will be
18200 obtained
18201 from the argument file name according to the GNAT file naming conventions.
18203 @item ^-q^/QUIET^
18204 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18205 Quiet mode: do not generate a confirmation when a body is
18206 successfully created, and do not generate a message when a body is not
18207 required for an
18208 argument unit.
18210 @item ^-r^/TREE_FILE=REUSE^
18211 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18212 Reuse the tree file (if it exists) instead of creating it.  Instead of
18213 creating the tree file for the library unit declaration, @command{gnatstub}
18214 tries to find it in the current directory and use it for creating
18215 a body. If the tree file is not found, no body is created. This option
18216 also implies @option{^-k^/SAVE^}, whether or not
18217 the latter is set explicitly.
18219 @item ^-t^/TREE_FILE=OVERWRITE^
18220 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18221 Overwrite the existing tree file.  If the current directory already
18222 contains the file which, according to the GNAT file naming rules should
18223 be considered as a tree file for the argument source file,
18224 @command{gnatstub}
18225 will refuse to create the tree file needed to create a sample body
18226 unless this option is set.
18228 @item ^-v^/VERBOSE^
18229 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18230 Verbose mode: generate version information.
18232 @end table
18234 @c *********************************
18235 @node Creating Unit Tests Using gnattest
18236 @chapter Creating Unit Tests Using @command{gnattest}
18237 @findex gnattest
18239 @noindent
18240 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18241 as well as a test driver infrastructure (harness). @command{gnattest} creates
18242 a skeleton for each visible subprogram in the packages under consideration when
18243 they do not exist already.
18245 In order to process source files from a project, @command{gnattest} has to
18246 semantically analyze the sources. Therefore, test skeletons can only be
18247 generated for legal Ada units. If a unit is dependent on other units,
18248 those units should be among the source files of the project or of other projects
18249 imported by this one.
18251 Generated skeletons and harnesses are based on the AUnit testing framework.
18252 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18253 for Java or CppUnit for C++. While it is advised that gnattest users read
18254 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18255 For correct operation of @command{gnattest}, AUnit should be installed and
18256 aunit.gpr must be on the project path. This happens automatically when Aunit
18257 is installed at its default location.
18258 @menu
18259 * Running gnattest::
18260 * Switches for gnattest::
18261 * Project Attributes for gnattest::
18262 * Simple Example::
18263 * Setting Up and Tearing Down the Testing Environment::
18264 * Regenerating Tests::
18265 * Default Test Behavior::
18266 * Testing Primitive Operations of Tagged Types::
18267 * Testing Inheritance::
18268 * Tagged Types Substitutability Testing::
18269 * Testing with Contracts::
18270 * Additional Tests::
18271 @ifclear vms
18272 * Support for other platforms/run-times::
18273 @end ifclear
18274 * Current Limitations::
18275 @end menu
18277 @node Running gnattest
18278 @section Running @command{gnattest}
18280 @noindent
18281 @command{gnattest} has a command-line interface of the form
18283 @smallexample
18284 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
18285 @c Expanding @ovar macro inline (explanation in macro def comments)
18286 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18287 @end smallexample
18289 @noindent
18290 where
18291 @table @var
18293 @item -Pprojname
18294 specifies the project defining the location of source files. When no
18295 file names are provided on the command line, all sources in the project
18296 are used as input. This switch is required.
18298 @item filename
18299 is the name of the source file containing the library unit package declaration
18300 for which a test package will be created. The file name may be given with a
18301 path.
18303 @item @samp{@var{gcc_switches}}
18304 is a list of switches for
18305 @command{gcc}. These switches will be passed on to all compiler invocations
18306 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
18307 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18308 use the @option{-gnatec} switch to set the configuration file,
18309 use the @option{-gnat05} switch if sources should be compiled in
18310 Ada 2005 mode, etc.
18312 @item switches
18313 is an optional sequence of switches as described in the next section.
18315 @end table
18317 @command{gnattest} results can be found in two different places.
18319 @itemize @bullet
18320 @item automatic harness:
18321 the harness code, which is located by default in "gnattest/harness" directory
18322 that is created in the object directory of corresponding project file. All of
18323 this code is generated completely automatically and can be destroyed and
18324 regenerated at will. It is not recommended to modify this code manually, since
18325 it could easily be overridden by mistake. The entry point in the harness code is
18326 the project file named @command{test_driver.gpr}. Tests can be compiled and run
18327 using a command such as:
18329 @smallexample
18330 gnatmake -P<harness-dir>/test_driver
18331 test_runner
18332 @end smallexample
18334 Note that you might need to specify the necessary values of scenario variables
18335 when you are not using the AUnit defaults.
18337 @item actual unit test skeletons:
18338 a test skeleton for each visible subprogram is created in a separate file, if it
18339 doesn't exist already. By default, those separate test files are located in a
18340 "gnattest/tests" directory that is created in the object directory of
18341 corresponding project file. For example, if a source file my_unit.ads in
18342 directory src contains a visible subprogram Proc, then the corresponding unit
18343 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
18344 <code> is a signature encoding used to differentiate test names in case of
18345 overloading.
18347 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
18348 this will cause a name conflict with the generated test package.
18349 @end itemize
18351 @node Switches for gnattest
18352 @section Switches for @command{gnattest}
18354 @table @option
18355 @c !sort!
18357 @item --harness-only
18358 @cindex @option{--harness-only} (@command{gnattest})
18359 When this option is given, @command{gnattest} creates a harness for all
18360 sources, treating them as test packages.
18362 @item --additional-tests=@var{projname}
18363 @cindex @option{--additional-tests} (@command{gnattest})
18364 Sources described in @var{projname} are considered potential additional
18365 manual tests to be added to the test suite.
18367 @item -r
18368 @cindex @option{-r} (@command{gnattest})
18369 Recursively consider all sources from all projects.
18371 @item -X@var{name=value}
18372 @cindex @option{-X} (@command{gnattest})
18373 Indicate that external variable @var{name} has the value @var{value}.
18375 @item -q
18376 @cindex @option{-q} (@command{gnattest})
18377 Suppresses noncritical output messages.
18379 @item -v
18380 @cindex @option{-v} (@command{gnattest})
18381 Verbose mode: generates version information.
18383 @item --validate-type-extensions
18384 @cindex @option{--validate-type-extensions} (@command{gnattest})
18385 Enables substitution check: run all tests from all parents in order
18386 to check substitutability.
18388 @item --skeleton-default=@var{val}
18389 @cindex @option{--skeleton-default} (@command{gnattest})
18390 Specifies the default behavior of generated skeletons. @var{val} can be either
18391 "fail" or "pass", "fail" being the default.
18393 @item --tests-root=@var{dirname}
18394 @cindex @option{--tests-root} (@command{gnattest})
18395 The directory hierarchy of tested sources is recreated in the @var{dirname}
18396 directory, and test packages are placed in corresponding directories.
18397 If the @var{dirname} is a relative path, it is considered relative to the object
18398 directory of the project file. When all sources from all projects are taken
18399 recursively from all projects, directory hierarchies of tested sources are
18400 recreated for each project in their object directories and test packages are
18401 placed accordingly.
18403 @item --subdir=@var{dirname}
18404 @cindex @option{--subdir} (@command{gnattest})
18405 Test packages are placed in subdirectories.
18407 @item --tests-dir=@var{dirname}
18408 @cindex @option{--tests-dir} (@command{gnattest})
18409 All test packages are placed in the @var{dirname} directory.
18410 If the @var{dirname} is a relative path, it is considered relative to the object
18411 directory of the project file. When all sources from all projects are taken
18412 recursively from all projects, @var{dirname} directories are created for each
18413 project in their object directories and test packages are placed accordingly.
18415 @item --harness-dir=@var{dirname}
18416 @cindex @option{--harness-dir} (@command{gnattest})
18417 specifies the directory that will hold the harness packages and project file
18418 for the test driver. If the @var{dirname} is a relative path, it is considered
18419 relative to the object directory of the project file.
18421 @item --separates
18422 @cindex @option{--separates} (@command{gnattest})
18423 Bodies of all test routines are generated as separates. Note that this mode is
18424 kept for compatibility reasons only and it is not advised to use it due to
18425 possible problems with hash in names of test skeletons when using an
18426 inconsistent casing. Separate test skeletons can be incorporated to monolith
18427 test package with improved hash being used by using @option{--transition}
18428 switch.
18431 @item --transition
18432 @cindex @option{--transition} (@command{gnattest})
18433 This allows transition from separate test routines to monolith test packages.
18434 All matching test routines are overwritten with contents of corresponding
18435 separates. Note that if separate test routines had any manually added with
18436 clauses they will be moved to the test package body as is and have to be moved
18437 by hand.
18439 @end table
18441 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
18442 mutually exclusive.
18444 @node Project Attributes for gnattest
18445 @section Project Attributes for @command{gnattest}
18447 @noindent
18449 Most of the command-line options can also be passed to the tool by adding
18450 special attributes to the project file. Those attributes should be put in
18451 package gnattest. Here is the list of attributes:
18453 @itemize @bullet
18455 @item Tests_Root
18456 is used to select the same output mode as with the --tests-root option.
18457 This attribute cannot be used together with Subdir or Tests_Dir.
18459 @item Subdir
18460 is used to select the same output mode as with the --subdir option.
18461 This attribute cannot be used together with Tests_Root or Tests_Dir.
18463 @item Tests_Dir
18464 is used to select the same output mode as with the --tests-dir option.
18465 This attribute cannot be used together with Subdir or Tests_Root.
18467 @item Harness_Dir
18468 is used to specify the directory in which to place harness packages and project
18469 file for the test driver, otherwise specified by --harness-dir.
18471 @item Additional_Tests
18472 is used to specify the project file, otherwise given by
18473 --additional-tests switch.
18475 @item Skeletons_Default
18476 is used to specify the default behaviour of test skeletons, otherwise
18477 specified by --skeleton-default option. The value of this attribute
18478 should be either "pass" or "fail".
18480 @end itemize
18482 Each of those attributes can be overridden from the command line if needed.
18483 Other @command{gnattest} switches can also be passed via the project
18484 file as an attribute list called GNATtest_Switches.
18486 @node Simple Example
18487 @section Simple Example
18489 @noindent
18491 Let's take a very simple example using the first @command{gnattest} example
18492 located in:
18494 @smallexample
18495 <install_prefix>/share/examples/gnattest/simple
18496 @end smallexample
18498 This project contains a simple package containing one subprogram. By running gnattest:
18500 @smallexample
18501 $ gnattest --harness-dir=driver -Psimple.gpr
18502 @end smallexample
18504 a test driver is created in directory "driver". It can be compiled and run:
18506 @smallexample
18507 $ cd driver
18508 $ gprbuild -Ptest_driver
18509 $ test_runner
18510 @end smallexample
18512 One failed test with diagnosis "test not implemented" is reported.
18513 Since no special output option was specified, the test package Simple.Tests
18514 is located in:
18516 @smallexample
18517 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
18518 @end smallexample
18520 For each package containing visible subprograms, a child test package is
18521 generated. It contains one test routine per tested subprogram. Each
18522 declaration of a test subprogram has a comment specifying which tested
18523 subprogram it corresponds to. Bodies of test routines are placed in test package
18524 bodies and are surrounded by special comment sections. Those comment sections
18525 should not be removed or modified in order for gnattest to be able to regenerate
18526 test packages and keep already written tests in place.
18527 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
18528 a single statement: a call to procedure Assert. It has two arguments:
18529 the Boolean expression we want to check and the diagnosis message to display if
18530 the condition is false.
18532 That is where actual testing code should be written after a proper setup.
18533 An actual check can be performed by replacing the Assert call with:
18535 @smallexample @c ada
18536 Assert (Inc (1) = 2, "wrong incrementation");
18537 @end smallexample
18539 After recompiling and running the test driver, one successfully passed test
18540 is reported.
18542 @node Setting Up and Tearing Down the Testing Environment
18543 @section Setting Up and Tearing Down the Testing Environment
18545 @noindent
18547 Besides test routines themselves, each test package has a parent package
18548 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
18549 overwritten by the tool. Set_Up is called before each test routine of the
18550 package and Tear_Down is called after each test routine. Those two procedures
18551 can be used to perform necessary initialization and finalization,
18552 memory allocation, etc. Test type declared in Test_Data package is parent type
18553 for the test type of test package and can have user-defined components whose
18554 values can be set by Set_Up routine and used in test routines afterwards.
18556 @node Regenerating Tests
18557 @section Regenerating Tests
18559 @noindent
18561 Bodies of test routines and test_data packages are never overridden after they
18562 have been created once. As long as the name of the subprogram, full expanded Ada
18563 names, and the order of its parameters is the same, and comment sections are
18564 intact the old test routine will fit in its place and no test skeleton will be
18565 generated for the subprogram.
18567 This can be demonstrated with the previous example. By uncommenting declaration
18568 and body of function Dec in simple.ads and simple.adb, running
18569 @command{gnattest} on the project, and then running the test driver:
18571 @smallexample
18572 gnattest --harness-dir=driver -Psimple.gpr
18573 cd driver
18574 gprbuild -Ptest_driver
18575 test_runner
18576 @end smallexample
18578 the old test is not replaced with a stub, nor is it lost, but a new test
18579 skeleton is created for function Dec.
18581 The only way of regenerating tests skeletons is to remove the previously created
18582 tests together with corresponding comment sections.
18584 @node Default Test Behavior
18585 @section Default Test Behavior
18587 @noindent
18589 The generated test driver can treat unimplemented tests in two ways:
18590 either count them all as failed (this is useful to see which tests are still
18591 left to implement) or as passed (to sort out unimplemented ones from those
18592 actually failing).
18594 The test driver accepts a switch to specify this behavior:
18595 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
18596 @command{gnattest}).
18598 The default behavior of the test driver is set with the same switch
18599 as passed to gnattest when generating the test driver.
18601 Passing it to the driver generated on the first example:
18603 @smallexample
18604 test_runner --skeleton-default=pass
18605 @end smallexample
18607 makes both tests pass, even the unimplemented one.
18609 @node Testing Primitive Operations of Tagged Types
18610 @section Testing Primitive Operations of Tagged Types
18612 @noindent
18614 Creation of test skeletons for primitive operations of tagged types entails
18615 a number of features. Test routines for all primitives of a given tagged type
18616 are placed in a separate child package named according to the tagged type. For
18617 example, if you have tagged type T in package P, all tests for primitives
18618 of T will be in P.T_Test_Data.T_Tests.
18620 Consider running gnattest on the second example (note: actual tests for this
18621 example already exist, so there's no need to worry if the tool reports that
18622 no new stubs were generated):
18624 @smallexample
18625 cd <install_prefix>/share/examples/gnattest/tagged_rec
18626 gnattest --harness-dir=driver -Ptagged_rec.gpr
18627 @end smallexample
18629 Taking a closer look at the test type declared in the test package
18630 Speed1.Controller_Test_Data is necessary. It is declared in:
18632 @smallexample
18633 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
18634 @end smallexample
18636 Test types are direct or indirect descendants of
18637 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18638 subprograms, the user doesn't need to be concerned with them. However,
18639 when generating test packages for primitive operations, there are some things
18640 the user needs to know.
18642 Type Test_Controller has components that allow assignment of various
18643 derivations of type Controller. And if you look at the specification of
18644 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18645 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18646 Thus, test types mirror the hierarchy of tested types.
18648 The Set_Up procedure of Test_Data package corresponding to a test package
18649 of primitive operations of type T assigns to Fixture a reference to an
18650 object of that exact type T. Notice, however, that if the tagged type has
18651 discriminants, the Set_Up only has a commented template for setting
18652 up the fixture, since filling the discriminant with actual value is up
18653 to the user.
18655 The knowledge of the structure of test types allows additional testing
18656 without additional effort. Those possibilities are described below.
18658 @node Testing Inheritance
18659 @section Testing Inheritance
18661 @noindent
18663 Since the test type hierarchy mimics the hierarchy of tested types, the
18664 inheritance of tests takes place. An example of such inheritance can be
18665 seen by running the test driver generated for the second example. As previously
18666 mentioned, actual tests are already written for this example.
18668 @smallexample
18669 cd driver
18670 gprbuild -Ptest_driver
18671 test_runner
18672 @end smallexample
18674 There are 6 passed tests while there are only 5 testable subprograms. The test
18675 routine for function Speed has been inherited and run against objects of the
18676 derived type.
18678 @node Tagged Types Substitutability Testing
18679 @section Tagged Types Substitutability Testing
18681 @noindent
18683 Tagged Types Substitutability Testing is a way of verifying the global type
18684 consistency by testing. Global type consistency is a principle stating that if
18685 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18686 then objects of type T may be replaced with objects of type S (that is,
18687 objects of type S may be substituted for objects of type T), without
18688 altering any of the desirable properties of the program. When the properties
18689 of the program are expressed in the form of subprogram preconditions and
18690 postconditions (let's call them pre and post), the principle is formulated as
18691 relations between the pre and post of primitive operations and the pre and post
18692 of their derived operations. The pre of a derived operation should not be
18693 stronger than the original pre, and the post of the derived operation should
18694 not be weaker than the original post. Those relations ensure that verifying if
18695 a dispatching call is safe can be done just by using the pre and post of the
18696 root operation.
18698 Verifying global type consistency by testing consists of running all the unit
18699 tests associated with the primitives of a given tagged type with objects of its
18700 derived types.
18702 In the example used in the previous section, there was clearly a violation of
18703 type consistency. The overriding primitive Adjust_Speed in package Speed2
18704 removes the functionality of the overridden primitive and thus doesn't respect
18705 the consistency principle.
18706 Gnattest has a special option to run overridden parent tests against objects
18707 of the type which have overriding primitives:
18709 @smallexample
18710 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
18711 cd driver
18712 gprbuild -Ptest_driver
18713 test_runner
18714 @end smallexample
18716 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18717 against objects of the derived type.
18719 Non-overridden tests are already inherited for derived test types, so the
18720 --validate-type-extensions enables the application of overriden tests to objects
18721 of derived types.
18723 @node Testing with Contracts
18724 @section Testing with Contracts
18726 @noindent
18728 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
18729 as well as corresponding aspects.
18730 Test routines are generated, one per each Test_Case associated with a tested
18731 subprogram. Those test routines have special wrappers for tested functions
18732 that have composition of pre- and postcondition of the subprogram with
18733 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18734 either count for Nominal mode or do not count for Robustness mode).
18736 The third example demonstrates how this works:
18738 @smallexample
18739 cd <install_prefix>/share/examples/gnattest/contracts
18740 gnattest --harness-dir=driver -Pcontracts.gpr
18741 @end smallexample
18743 Putting actual checks within the range of the contract does not cause any
18744 error reports. For example, for the test routine which corresponds to
18745 test case 1:
18747 @smallexample @c ada
18748 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18749 @end smallexample
18751 and for the test routine corresponding to test case 2:
18753 @smallexample @c ada
18754 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18755 @end smallexample
18757 are acceptable:
18759 @smallexample
18760 cd driver
18761 gprbuild -Ptest_driver
18762 test_runner
18763 @end smallexample
18765 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18766 a precondition violation for test case one. Also, by using any otherwise
18767 correct but positive pair of numbers in the second test routine, you can also
18768 get a precondition violation. Postconditions are checked and reported
18769 the same way.
18771 @node Additional Tests
18772 @section Additional Tests
18774 @noindent
18775 @command{gnattest} can add user-written tests to the main suite of the test
18776 driver. @command{gnattest} traverses the given packages and searches for test
18777 routines. All procedures with a single in out parameter of a type which is
18778 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18779 specifications are added to the suites and are then executed by the test driver.
18780 (Set_Up and Tear_Down are filtered out.)
18782 An example illustrates two ways of creating test harnesses for user-written
18783 tests. Directory additional_tests contains an AUnit-based test driver written
18784 by hand.
18786 @smallexample
18787 <install_prefix>/share/examples/gnattest/additional_tests/
18788 @end smallexample
18790 To create a test driver for already-written tests, use the --harness-only
18791 option:
18793 @smallexample
18794 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18795   --harness-only
18796 gnatmake -Pharness_only/test_driver.gpr
18797 harness_only/test_runner
18798 @end smallexample
18800 Additional tests can also be executed together with generated tests:
18802 @smallexample
18803 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18804   --harness-dir=mixing
18805 gnatmake -Pmixing/test_driver.gpr
18806 mixing/test_runner
18807 @end smallexample
18809 @ifclear vms
18810 @node Support for other platforms/run-times
18811 @section Support for other platforms/run-times
18813 @noindent
18814 @command{gnattest} can be used to generate the test harness for platforms
18815 and run-time libraries others than the default native target with the
18816 default full run-time. For example, when using a limited run-time library
18817 such as Zero FootPrint (ZFP), a simplified harness is generated.
18819 Two variables are used to tell the underlying AUnit framework how to generate
18820 the test harness: @code{PLATFORM}, which identifies the target, and
18821 @code{RUNTIME}, used to determine the run-time library for which the harness
18822 is generated. Corresponding prefix should also be used when calling
18823 @command{gnattest} for non-native targets. For example, the following options
18824 are used to generate the AUnit test harness for a PowerPC ELF target using
18825 the ZFP run-time library:
18827 @smallexample
18828 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
18829 @end smallexample
18830 @end ifclear
18832 @node Current Limitations
18833 @section Current Limitations
18835 @noindent
18837 The tool currently does not support following features:
18839 @itemize @bullet
18840 @item generic tests for generic packages and package instantiations
18841 @item tests for protected subprograms and entries
18843 @end itemize
18845 @c *********************************
18846 @node Performing Dimensionality Analysis in GNAT
18847 @chapter Performing Dimensionality Analysis in GNAT
18848 @noindent
18849 The GNAT compiler now supports dimensionality checking. The user can
18850 specify physical units for objects, and the compiler will verify that uses
18851 of these objects are compatible with their dimensions, in a fashion that is
18852 familiar to engineering practice. The dimensions of algebraic expressions
18853 (including powers with static exponents) are computed from their consistuents.
18855 This feature depends on Ada 2012 aspect specifications, and is available from
18856 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
18857 the user to define a system of units; the aspect Dimension then allows the user
18858 to declare dimensioned quantities within a given system.
18860 The major advantage of this model is that it does not require the declaration of
18861 multiple operators for all possible combinations of types: it is only necessary
18862 to use the proper subtypes in object declarations.
18864 The simplest way to impose dimensionality checking on a computation is to make
18865 use of the package System.Dim.Mks, which is part of the GNAT library. This
18866 package defines a floating-point type MKS_Type, for which a sequence of
18867 dimension names are specified, together with their conventional abbreviations.
18868 The following should be read together with the full specification of the
18869 package, in file s-dimmks.ads.
18871 @smallexample @c ada
18872    type Mks_Type is new Long_Long_Float
18873      with
18874       Dimension_System => (
18875         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
18876         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
18877         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
18878         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
18879         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
18880         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
18881         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
18882 @end smallexample
18884 @noindent
18885 The package then defines a series of subtypes that correspond to these
18886 conventional units. For example:
18887 @smallexample @c ada
18888    subtype Length is Mks_Type
18889      with
18890       Dimension => (Symbol => 'm',
18891         Meter  => 1,
18892         others => 0);
18893 @end smallexample
18894 @noindent
18895 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
18896 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
18897 the SI system).
18899 The package also defines conventional names for values of each unit, for
18900 example:
18902 @smallexample @c ada
18903    m   : constant Length           := 1.0;
18904    kg  : constant Mass             := 1.0;
18905    s   : constant Time             := 1.0;
18906    A   : constant Electric_Current := 1.0;
18907 @end smallexample
18909 @noindent
18910 as well as useful multiples of these units:
18912 @smallexample @c ada
18913    cm  : constant Length := 1.0E-02;
18914    g   : constant Mass   := 1.0E-03;
18915    min : constant Time   := 60.0;
18916    day : constant TIme   := 60.0 * 24.0 * min;
18917   ...
18918 @end smallexample
18920 @noindent
18921 The user can then define a derived unit by providing the aspect that
18922 specifies its dimensions within the MKS system, as well as the string to
18923 be used for output of a value of that unit:
18925 @smallexample @c ada
18926   subtype Acceleration is Mks_Type
18927     with Dimension => ("m/sec^^^2", Meter => 1, Second => -2, others => 0);
18928 @end smallexample
18930 @noindent
18931 Here is a complete example of use:
18933 @smallexample @c ada
18934 with System.Dim.MKS; use System.Dim.Mks;
18935 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
18936 with Text_IO; use Text_IO;
18937 procedure Free_Fall is
18938   subtype Acceleration is Mks_Type
18939     with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
18940   G : constant acceleration := 9.81 * m / (s ** 2);
18941   T : Time := 10.0*s;
18942   Distance : Length;
18943 begin
18944   Put ("Gravitational constant: ");
18945   Put (G, Aft => 2, Exp => 0); Put_Line ("");
18946   Distance := 0.5 * G * T ** 2;
18947   Put ("distance travelled in 10 seconds of free fall ");
18948   Put (Distance, Aft => 2, Exp => 0);
18949   Put_Line ("");
18950 end Free_Fall;
18951 @end smallexample
18953 @noindent
18954 Execution of this program yields:
18955 @smallexample
18956 Gravitational constant:  9.81 m/sec^^^2
18957 distance travelled in 10 seconds of free fall 490.50 m
18958 @end smallexample
18960 @noindent
18961 However, incorrect assignments such as:
18963 @smallexample @c ada
18964    Distance := 5.0;
18965    Distance := 5.0 * kg:
18966 @end smallexample
18968 @noindent
18969 are rejected with the following diagnoses:
18971 @smallexample
18972    Distance := 5.0;
18973       >>> dimensions mismatch in assignment
18974       >>> left-hand side has dimension [L]
18975       >>> right-hand side is dimensionless
18977    Distance := 5.0 * kg:
18978       >>> dimensions mismatch in assignment
18979       >>> left-hand side has dimension [L]
18980       >>> right-hand side has dimension [M]
18981 @end smallexample
18983 @noindent
18984 The dimensions of an expression are properly displayed, even if there is
18985 no explicit subtype for it. If we add to the program:
18987 @smallexample @c ada
18988       Put ("Final velocity: ");
18989       Put (G * T, Aft =>2, Exp =>0);
18990       Put_Line ("");
18991 @end smallexample
18993 @noindent
18994 then the output includes:
18995 @smallexample
18996      Final velocity: 98.10 m.s**(-1)
18997 @end smallexample
18999 @c *********************************
19000 @node Generating Ada Bindings for C and C++ headers
19001 @chapter Generating Ada Bindings for C and C++ headers
19002 @findex binding
19004 @noindent
19005 GNAT now comes with a binding generator for C and C++ headers which is
19006 intended to do 95% of the tedious work of generating Ada specs from C
19007 or C++ header files.
19009 Note that this capability is not intended to generate 100% correct Ada specs,
19010 and will is some cases require manual adjustments, although it can often
19011 be used out of the box in practice.
19013 Some of the known limitations include:
19015 @itemize @bullet
19016 @item only very simple character constant macros are translated into Ada
19017 constants. Function macros (macros with arguments) are partially translated
19018 as comments, to be completed manually if needed.
19019 @item some extensions (e.g. vector types) are not supported
19020 @item pointers to pointers or complex structures are mapped to System.Address
19021 @item identifiers with identical name (except casing) will generate compilation
19022       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19023 @end itemize
19025 The code generated is using the Ada 2005 syntax, which makes it
19026 easier to interface with other languages than previous versions of Ada.
19028 @menu
19029 * Running the binding generator::
19030 * Generating bindings for C++ headers::
19031 * Switches::
19032 @end menu
19034 @node Running the binding generator
19035 @section Running the binding generator
19037 @noindent
19038 The binding generator is part of the @command{gcc} compiler and can be
19039 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19040 spec files for the header files specified on the command line, and all
19041 header files needed by these files transitively. For example:
19043 @smallexample
19044 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19045 $ gcc -c -gnat05 *.ads
19046 @end smallexample
19048 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19049 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19050 correspond to the files @file{/usr/include/time.h},
19051 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19052 mode these Ada specs.
19054 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19055 and will attempt to generate corresponding Ada comments.
19057 If you want to generate a single Ada file and not the transitive closure, you
19058 can use instead the @option{-fdump-ada-spec-slim} switch.
19060 You can optionally specify a parent unit, of which all generated units will
19061 be children, using @code{-fada-spec-parent=}@var{unit}.
19063 Note that we recommend when possible to use the @command{g++} driver to
19064 generate bindings, even for most C headers, since this will in general
19065 generate better Ada specs. For generating bindings for C++ headers, it is
19066 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
19067 is equivalent in this case. If @command{g++} cannot work on your C headers
19068 because of incompatibilities between C and C++, then you can fallback to
19069 @command{gcc} instead.
19071 For an example of better bindings generated from the C++ front-end,
19072 the name of the parameters (when available) are actually ignored by the C
19073 front-end. Consider the following C header:
19075 @smallexample
19076 extern void foo (int variable);
19077 @end smallexample
19079 with the C front-end, @code{variable} is ignored, and the above is handled as:
19081 @smallexample
19082 extern void foo (int);
19083 @end smallexample
19085 generating a generic:
19087 @smallexample
19088 procedure foo (param1 : int);
19089 @end smallexample
19091 with the C++ front-end, the name is available, and we generate:
19093 @smallexample
19094 procedure foo (variable : int);
19095 @end smallexample
19097 In some cases, the generated bindings will be more complete or more meaningful
19098 when defining some macros, which you can do via the @option{-D} switch. This
19099 is for example the case with @file{Xlib.h} under GNU/Linux:
19101 @smallexample
19102 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
19103 @end smallexample
19105 The above will generate more complete bindings than a straight call without
19106 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
19108 In other cases, it is not possible to parse a header file in a stand-alone
19109 manner, because other include files need to be included first. In this
19110 case, the solution is to create a small header file including the needed
19111 @code{#include} and possible @code{#define} directives. For example, to
19112 generate Ada bindings for @file{readline/readline.h}, you need to first
19113 include @file{stdio.h}, so you can create a file with the following two
19114 lines in e.g. @file{readline1.h}:
19116 @smallexample
19117 #include <stdio.h>
19118 #include <readline/readline.h>
19119 @end smallexample
19121 and then generate Ada bindings from this file:
19123 @smallexample
19124 $ g++ -c -fdump-ada-spec readline1.h
19125 @end smallexample
19127 @node Generating bindings for C++ headers
19128 @section Generating bindings for C++ headers
19130 @noindent
19131 Generating bindings for C++ headers is done using the same options, always
19132 with the @command{g++} compiler.
19134 In this mode, C++ classes will be mapped to Ada tagged types, constructors
19135 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
19136 multiple inheritance of abstract classes will be mapped to Ada interfaces
19137 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
19138 information on interfacing to C++).
19140 For example, given the following C++ header file:
19142 @smallexample
19143 @group
19144 @cartouche
19145 class Carnivore @{
19146 public:
19147    virtual int Number_Of_Teeth () = 0;
19150 class Domestic @{
19151 public:
19152    virtual void Set_Owner (char* Name) = 0;
19155 class Animal @{
19156 public:
19157   int Age_Count;
19158   virtual void Set_Age (int New_Age);
19161 class Dog : Animal, Carnivore, Domestic @{
19162  public:
19163   int  Tooth_Count;
19164   char *Owner;
19166   virtual int  Number_Of_Teeth ();
19167   virtual void Set_Owner (char* Name);
19169   Dog();
19171 @end cartouche
19172 @end group
19173 @end smallexample
19175 The corresponding Ada code is generated:
19177 @smallexample @c ada
19178 @group
19179 @cartouche
19180   package Class_Carnivore is
19181     type Carnivore is limited interface;
19182     pragma Import (CPP, Carnivore);
19184     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
19185   end;
19186   use Class_Carnivore;
19188   package Class_Domestic is
19189     type Domestic is limited interface;
19190     pragma Import (CPP, Domestic);
19192     procedure Set_Owner
19193       (this : access Domestic;
19194        Name : Interfaces.C.Strings.chars_ptr) is abstract;
19195   end;
19196   use Class_Domestic;
19198   package Class_Animal is
19199     type Animal is tagged limited record
19200       Age_Count : aliased int;
19201     end record;
19202     pragma Import (CPP, Animal);
19204     procedure Set_Age (this : access Animal; New_Age : int);
19205     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
19206   end;
19207   use Class_Animal;
19209   package Class_Dog is
19210     type Dog is new Animal and Carnivore and Domestic with record
19211       Tooth_Count : aliased int;
19212       Owner : Interfaces.C.Strings.chars_ptr;
19213     end record;
19214     pragma Import (CPP, Dog);
19216     function Number_Of_Teeth (this : access Dog) return int;
19217     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
19219     procedure Set_Owner
19220       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
19221     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
19223     function New_Dog return Dog;
19224     pragma CPP_Constructor (New_Dog);
19225     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
19226   end;
19227   use Class_Dog;
19228 @end cartouche
19229 @end group
19230 @end smallexample
19232 @node Switches
19233 @section Switches
19235 @table @option
19236 @item -fdump-ada-spec
19237 @cindex @option{-fdump-ada-spec} (@command{gcc})
19238 Generate Ada spec files for the given header files transitively (including
19239 all header files that these headers depend upon).
19241 @item -fdump-ada-spec-slim
19242 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
19243 Generate Ada spec files for the header files specified on the command line
19244 only.
19246 @item -fada-spec-parent=@var{unit}
19247 @cindex -fada-spec-parent (@command{gcc})
19248 Specifies that all files generated by @option{-fdump-ada-spec*} are
19249 to be child units of the specified parent unit.
19251 @item -C
19252 @cindex @option{-C} (@command{gcc})
19253 Extract comments from headers and generate Ada comments in the Ada spec files.
19254 @end table
19256 @node Other Utility Programs
19257 @chapter Other Utility Programs
19259 @noindent
19260 This chapter discusses some other utility programs available in the Ada
19261 environment.
19263 @menu
19264 * Using Other Utility Programs with GNAT::
19265 * The External Symbol Naming Scheme of GNAT::
19266 * Converting Ada Files to html with gnathtml::
19267 * Installing gnathtml::
19268 @ifset vms
19269 * LSE::
19270 * Profiling::
19271 @end ifset
19272 @end menu
19274 @node Using Other Utility Programs with GNAT
19275 @section Using Other Utility Programs with GNAT
19277 @noindent
19278 The object files generated by GNAT are in standard system format and in
19279 particular the debugging information uses this format. This means
19280 programs generated by GNAT can be used with existing utilities that
19281 depend on these formats.
19283 @ifclear vms
19284 In general, any utility program that works with C will also often work with
19285 Ada programs generated by GNAT. This includes software utilities such as
19286 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19287 as Purify.
19288 @end ifclear
19290 @node The External Symbol Naming Scheme of GNAT
19291 @section The External Symbol Naming Scheme of GNAT
19293 @noindent
19294 In order to interpret the output from GNAT, when using tools that are
19295 originally intended for use with other languages, it is useful to
19296 understand the conventions used to generate link names from the Ada
19297 entity names.
19299 All link names are in all lowercase letters. With the exception of library
19300 procedure names, the mechanism used is simply to use the full expanded
19301 Ada name with dots replaced by double underscores. For example, suppose
19302 we have the following package spec:
19304 @smallexample @c ada
19305 @group
19306 @cartouche
19307 package QRS is
19308    MN : Integer;
19309 end QRS;
19310 @end cartouche
19311 @end group
19312 @end smallexample
19314 @noindent
19315 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19316 the corresponding link name is @code{qrs__mn}.
19317 @findex Export
19318 Of course if a @code{pragma Export} is used this may be overridden:
19320 @smallexample @c ada
19321 @group
19322 @cartouche
19323 package Exports is
19324    Var1 : Integer;
19325    pragma Export (Var1, C, External_Name => "var1_name");
19326    Var2 : Integer;
19327    pragma Export (Var2, C, Link_Name => "var2_link_name");
19328 end Exports;
19329 @end cartouche
19330 @end group
19331 @end smallexample
19333 @noindent
19334 In this case, the link name for @var{Var1} is whatever link name the
19335 C compiler would assign for the C function @var{var1_name}. This typically
19336 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19337 system conventions, but other possibilities exist. The link name for
19338 @var{Var2} is @var{var2_link_name}, and this is not operating system
19339 dependent.
19341 @findex _main
19342 One exception occurs for library level procedures. A potential ambiguity
19343 arises between the required name @code{_main} for the C main program,
19344 and the name we would otherwise assign to an Ada library level procedure
19345 called @code{Main} (which might well not be the main program).
19347 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19348 names. So if we have a library level procedure such as
19350 @smallexample @c ada
19351 @group
19352 @cartouche
19353 procedure Hello (S : String);
19354 @end cartouche
19355 @end group
19356 @end smallexample
19358 @noindent
19359 the external name of this procedure will be @var{_ada_hello}.
19362 @node Converting Ada Files to html with gnathtml
19363 @section Converting Ada Files to HTML with @code{gnathtml}
19365 @noindent
19366 This @code{Perl} script allows Ada source files to be browsed using
19367 standard Web browsers. For installation procedure, see the section
19368 @xref{Installing gnathtml}.
19370 Ada reserved keywords are highlighted in a bold font and Ada comments in
19371 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19372 switch to suppress the generation of cross-referencing information, user
19373 defined variables and types will appear in a different color; you will
19374 be able to click on any identifier and go to its declaration.
19376 The command line is as follow:
19377 @smallexample
19378 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
19379 @c Expanding @ovar macro inline (explanation in macro def comments)
19380 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
19381 @end smallexample
19383 @noindent
19384 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19385 an html file for every ada file, and a global file called @file{index.htm}.
19386 This file is an index of every identifier defined in the files.
19388 The available ^switches^options^ are the following ones:
19390 @table @option
19391 @item -83
19392 @cindex @option{-83} (@code{gnathtml})
19393 Only the Ada 83 subset of keywords will be highlighted.
19395 @item -cc @var{color}
19396 @cindex @option{-cc} (@code{gnathtml})
19397 This option allows you to change the color used for comments. The default
19398 value is green. The color argument can be any name accepted by html.
19400 @item -d
19401 @cindex @option{-d} (@code{gnathtml})
19402 If the Ada files depend on some other files (for instance through
19403 @code{with} clauses, the latter files will also be converted to html.
19404 Only the files in the user project will be converted to html, not the files
19405 in the run-time library itself.
19407 @item -D
19408 @cindex @option{-D} (@code{gnathtml})
19409 This command is the same as @option{-d} above, but @command{gnathtml} will
19410 also look for files in the run-time library, and generate html files for them.
19412 @item -ext @var{extension}
19413 @cindex @option{-ext} (@code{gnathtml})
19414 This option allows you to change the extension of the generated HTML files.
19415 If you do not specify an extension, it will default to @file{htm}.
19417 @item -f
19418 @cindex @option{-f} (@code{gnathtml})
19419 By default, gnathtml will generate html links only for global entities
19420 ('with'ed units, global variables and types,@dots{}).  If you specify
19421 @option{-f} on the command line, then links will be generated for local
19422 entities too.
19424 @item -l @var{number}
19425 @cindex @option{-l} (@code{gnathtml})
19426 If this ^switch^option^ is provided and @var{number} is not 0, then
19427 @code{gnathtml} will number the html files every @var{number} line.
19429 @item -I @var{dir}
19430 @cindex @option{-I} (@code{gnathtml})
19431 Specify a directory to search for library files (@file{.ALI} files) and
19432 source files. You can provide several -I switches on the command line,
19433 and the directories will be parsed in the order of the command line.
19435 @item -o @var{dir}
19436 @cindex @option{-o} (@code{gnathtml})
19437 Specify the output directory for html files. By default, gnathtml will
19438 saved the generated html files in a subdirectory named @file{html/}.
19440 @item -p @var{file}
19441 @cindex @option{-p} (@code{gnathtml})
19442 If you are using Emacs and the most recent Emacs Ada mode, which provides
19443 a full Integrated Development Environment for compiling, checking,
19444 running and debugging applications, you may use @file{.gpr} files
19445 to give the directories where Emacs can find sources and object files.
19447 Using this ^switch^option^, you can tell gnathtml to use these files.
19448 This allows you to get an html version of your application, even if it
19449 is spread over multiple directories.
19451 @item -sc @var{color}
19452 @cindex @option{-sc} (@code{gnathtml})
19453 This ^switch^option^ allows you to change the color used for symbol
19454 definitions.
19455 The default value is red. The color argument can be any name accepted by html.
19457 @item -t @var{file}
19458 @cindex @option{-t} (@code{gnathtml})
19459 This ^switch^option^ provides the name of a file. This file contains a list of
19460 file names to be converted, and the effect is exactly as though they had
19461 appeared explicitly on the command line. This
19462 is the recommended way to work around the command line length limit on some
19463 systems.
19465 @end table
19467 @node Installing gnathtml
19468 @section Installing @code{gnathtml}
19470 @noindent
19471 @code{Perl} needs to be installed on your machine to run this script.
19472 @code{Perl} is freely available for almost every architecture and
19473 Operating System via the Internet.
19475 On Unix systems, you  may want to modify  the  first line of  the script
19476 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
19477 is. The syntax of this line is:
19478 @smallexample
19479 #!full_path_name_to_perl
19480 @end smallexample
19482 @noindent
19483 Alternatively, you may run the script using the following command line:
19485 @smallexample
19486 @c $ perl gnathtml.pl @ovar{switches} @var{files}
19487 @c Expanding @ovar macro inline (explanation in macro def comments)
19488 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
19489 @end smallexample
19491 @ifset vms
19492 @node LSE
19493 @section LSE
19494 @findex LSE
19496 @noindent
19497 The GNAT distribution provides an Ada 95 template for the HP Language
19498 Sensitive Editor (LSE), a component of DECset. In order to
19499 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19501 @node Profiling
19502 @section Profiling
19503 @findex PCA
19505 @noindent
19506 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19507 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19508 the collection phase with the /DEBUG qualifier.
19510 @smallexample
19511 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19512 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19513 $ RUN/DEBUG <PROGRAM_NAME>
19514 @end smallexample
19515 @noindent
19516 @end ifset
19518 @ifclear vms
19519 @c ******************************
19520 @node Code Coverage and Profiling
19521 @chapter Code Coverage and Profiling
19522 @cindex Code Coverage
19523 @cindex Profiling
19525 @noindent
19526 This chapter describes how to use @code{gcov} - coverage testing tool - and
19527 @code{gprof} - profiler tool - on your Ada programs.
19529 @menu
19530 * Code Coverage of Ada Programs using gcov::
19531 * Profiling an Ada Program using gprof::
19532 @end menu
19534 @node Code Coverage of Ada Programs using gcov
19535 @section Code Coverage of Ada Programs using gcov
19536 @cindex gcov
19537 @cindex -fprofile-arcs
19538 @cindex -ftest-coverage
19539 @cindex -coverage
19540 @cindex Code Coverage
19542 @noindent
19543 @code{gcov} is a test coverage program: it analyzes the execution of a given
19544 program on selected tests, to help you determine the portions of the program
19545 that are still untested.
19547 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
19548 User's Guide. You can refer to this documentation for a more complete
19549 description.
19551 This chapter provides a quick startup guide, and
19552 details some Gnat-specific features.
19554 @menu
19555 * Quick startup guide::
19556 * Gnat specifics::
19557 @end menu
19559 @node Quick startup guide
19560 @subsection Quick startup guide
19562 In order to perform coverage analysis of a program using @code{gcov}, 3
19563 steps are needed:
19565 @itemize @bullet
19566 @item
19567 Code instrumentation during the compilation process
19568 @item
19569 Execution of the instrumented program
19570 @item
19571 Execution of the @code{gcov} tool to generate the result.
19572 @end itemize
19574 The code instrumentation needed by gcov is created at the object level:
19575 The source code is not modified in any way, because the instrumentation code is
19576 inserted by gcc during the compilation process. To compile your code with code
19577 coverage activated, you need to recompile your whole project using the
19578 switches
19579 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19580 @code{-fprofile-arcs}.
19582 @smallexample
19583 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19584    -largs -fprofile-arcs
19585 @end smallexample
19587 This compilation process will create @file{.gcno} files together with
19588 the usual object files.
19590 Once the program is compiled with coverage instrumentation, you can
19591 run it as many times as needed - on portions of a test suite for
19592 example. The first execution will produce @file{.gcda} files at the
19593 same location as the @file{.gcno} files.  The following executions
19594 will update those files, so that a cumulative result of the covered
19595 portions of the program is generated.
19597 Finally, you need to call the @code{gcov} tool. The different options of
19598 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
19600 This will create annotated source files with a @file{.gcov} extension:
19601 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
19603 @node Gnat specifics
19604 @subsection Gnat specifics
19606 Because Ada semantics, portions of the source code may be shared among
19607 several object files. This is the case for example when generics are
19608 involved, when inlining is active  or when declarations generate  initialisation
19609 calls. In order to take
19610 into account this shared code, you need to call @code{gcov} on all
19611 source files of the tested program at once.
19613 The list of source files might exceed the system's maximum command line
19614 length. In order to bypass this limitation, a new mechanism has been
19615 implemented in @code{gcov}: you can now list all your project's files into a
19616 text file, and provide this file to gcov as a parameter,  preceded by a @@
19617 (e.g. @samp{gcov @@mysrclist.txt}).
19619 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
19620 not supported as there can be unresolved symbols during the final link.
19622 @node Profiling an Ada Program using gprof
19623 @section Profiling an Ada Program using gprof
19624 @cindex gprof
19625 @cindex -pg
19626 @cindex Profiling
19628 @noindent
19629 This section is not meant to be an exhaustive documentation of @code{gprof}.
19630 Full documentation for it can be found in the GNU Profiler User's Guide
19631 documentation that is part of this GNAT distribution.
19633 Profiling a program helps determine the parts of a program that are executed
19634 most often, and are therefore the most time-consuming.
19636 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19637 better handle Ada programs and multitasking.
19638 It is currently supported on the following platforms
19639 @itemize @bullet
19640 @item
19641 linux x86/x86_64
19642 @item
19643 solaris sparc/sparc64/x86
19644 @item
19645 windows x86
19646 @end itemize
19648 @noindent
19649 In order to profile a program using @code{gprof}, 3 steps are needed:
19651 @itemize @bullet
19652 @item
19653 Code instrumentation, requiring a full recompilation of the project with the
19654 proper switches.
19655 @item
19656 Execution of the program under the analysis conditions, i.e. with the desired
19657 input.
19658 @item
19659 Analysis of the results using the @code{gprof} tool.
19660 @end itemize
19662 @noindent
19663 The following sections detail the different steps, and indicate how
19664 to interpret the results:
19665 @menu
19666 * Compilation for profiling::
19667 * Program execution::
19668 * Running gprof::
19669 * Interpretation of profiling results::
19670 @end menu
19672 @node Compilation for profiling
19673 @subsection Compilation for profiling
19674 @cindex -pg
19675 @cindex Profiling
19677 In order to profile a program the first step is to tell the compiler
19678 to generate the necessary profiling information. The compiler switch to be used
19679 is @code{-pg}, which must be added to other compilation switches. This
19680 switch needs to be specified both during compilation and link stages, and can
19681 be specified once when using gnatmake:
19683 @smallexample
19684 gnatmake -f -pg -P my_project
19685 @end smallexample
19687 @noindent
19688 Note that only the objects that were compiled with the @samp{-pg} switch will
19689 be profiled; if you need to profile your whole project, use the @samp{-f}
19690 gnatmake switch to force full recompilation.
19692 @node Program execution
19693 @subsection Program execution
19695 @noindent
19696 Once the program has been compiled for profiling, you can run it as usual.
19698 The only constraint imposed by profiling is that the program must terminate
19699 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19700 properly analyzed.
19702 Once the program completes execution, a data file called @file{gmon.out} is
19703 generated in the directory where the program was launched from. If this file
19704 already exists, it will be overwritten.
19706 @node Running gprof
19707 @subsection Running gprof
19709 @noindent
19710 The @code{gprof} tool is called as follow:
19712 @smallexample
19713 gprof my_prog gmon.out
19714 @end smallexample
19716 @noindent
19717 or simpler:
19719 @smallexample
19720 gprof my_prog
19721 @end smallexample
19723 @noindent
19724 The complete form of the gprof command line is the following:
19726 @smallexample
19727 gprof [^switches^options^] [executable [data-file]]
19728 @end smallexample
19730 @noindent
19731 @code{gprof} supports numerous ^switch^options^. The order of these
19732 ^switch^options^ does not matter. The full list of options can be found in
19733 the GNU Profiler User's Guide documentation that comes with this documentation.
19735 The following is the subset of those switches that is most relevant:
19737 @table @option
19739 @item --demangle[=@var{style}]
19740 @itemx --no-demangle
19741 @cindex @option{--demangle} (@code{gprof})
19742 These options control whether symbol names should be demangled when
19743 printing output.  The default is to demangle C++ symbols.  The
19744 @code{--no-demangle} option may be used to turn off demangling. Different
19745 compilers have different mangling styles.  The optional demangling style
19746 argument can be used to choose an appropriate demangling style for your
19747 compiler, in particular Ada symbols generated by GNAT can be demangled using
19748 @code{--demangle=gnat}.
19750 @item -e @var{function_name}
19751 @cindex @option{-e} (@code{gprof})
19752 The @samp{-e @var{function}} option tells @code{gprof} not to print
19753 information about the function @var{function_name} (and its
19754 children@dots{}) in the call graph.  The function will still be listed
19755 as a child of any functions that call it, but its index number will be
19756 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
19757 given; only one @var{function_name} may be indicated with each @samp{-e}
19758 option.
19760 @item -E @var{function_name}
19761 @cindex @option{-E} (@code{gprof})
19762 The @code{-E @var{function}} option works like the @code{-e} option, but
19763 execution time spent in the function (and children who were not called from
19764 anywhere else), will not be used to compute the percentages-of-time for
19765 the call graph.  More than one @samp{-E} option may be given; only one
19766 @var{function_name} may be indicated with each @samp{-E} option.
19768 @item -f @var{function_name}
19769 @cindex @option{-f} (@code{gprof})
19770 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19771 call graph to the function @var{function_name} and its children (and
19772 their children@dots{}).  More than one @samp{-f} option may be given;
19773 only one @var{function_name} may be indicated with each @samp{-f}
19774 option.
19776 @item -F @var{function_name}
19777 @cindex @option{-F} (@code{gprof})
19778 The @samp{-F @var{function}} option works like the @code{-f} option, but
19779 only time spent in the function and its children (and their
19780 children@dots{}) will be used to determine total-time and
19781 percentages-of-time for the call graph.  More than one @samp{-F} option
19782 may be given; only one @var{function_name} may be indicated with each
19783 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
19785 @end table
19787 @node Interpretation of profiling results
19788 @subsection Interpretation of profiling results
19790 @noindent
19792 The results of the profiling analysis are represented by two arrays: the
19793 'flat profile' and the 'call graph'. Full documentation of those outputs
19794 can be found in the GNU Profiler User's Guide.
19796 The flat profile shows the time spent in each function of the program, and how
19797 many time it has been called. This allows you to locate easily the most
19798 time-consuming functions.
19800 The call graph shows, for each subprogram, the subprograms that call it,
19801 and the subprograms that it calls. It also provides an estimate of the time
19802 spent in each of those callers/called subprograms.
19803 @end ifclear
19805 @c ******************************
19806 @node Running and Debugging Ada Programs
19807 @chapter Running and Debugging Ada Programs
19808 @cindex Debugging
19810 @noindent
19811 This chapter discusses how to debug Ada programs.
19812 @ifset vms
19813 It applies to GNAT on the Alpha OpenVMS platform;
19814 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19815 since HP has implemented Ada support in the OpenVMS debugger on I64.
19816 @end ifset
19818 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19820 @enumerate
19821 @item
19822 The illegality may be a violation of the static semantics of Ada. In
19823 that case GNAT diagnoses the constructs in the program that are illegal.
19824 It is then a straightforward matter for the user to modify those parts of
19825 the program.
19827 @item
19828 The illegality may be a violation of the dynamic semantics of Ada. In
19829 that case the program compiles and executes, but may generate incorrect
19830 results, or may terminate abnormally with some exception.
19832 @item
19833 When presented with a program that contains convoluted errors, GNAT
19834 itself may terminate abnormally without providing full diagnostics on
19835 the incorrect user program.
19836 @end enumerate
19838 @menu
19839 * The GNAT Debugger GDB::
19840 * Running GDB::
19841 * Introduction to GDB Commands::
19842 * Using Ada Expressions::
19843 * Calling User-Defined Subprograms::
19844 * Using the Next Command in a Function::
19845 * Ada Exceptions::
19846 * Ada Tasks::
19847 * Debugging Generic Units::
19848 * Remote Debugging using gdbserver::
19849 * GNAT Abnormal Termination or Failure to Terminate::
19850 * Naming Conventions for GNAT Source Files::
19851 * Getting Internal Debugging Information::
19852 * Stack Traceback::
19853 @end menu
19855 @cindex Debugger
19856 @findex gdb
19858 @node The GNAT Debugger GDB
19859 @section The GNAT Debugger GDB
19861 @noindent
19862 @code{GDB} is a general purpose, platform-independent debugger that
19863 can be used to debug mixed-language programs compiled with @command{gcc},
19864 and in particular is capable of debugging Ada programs compiled with
19865 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19866 complex Ada data structures.
19868 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19869 @ifset vms
19870 located in the GNU:[DOCS] directory,
19871 @end ifset
19872 for full details on the usage of @code{GDB}, including a section on
19873 its usage on programs. This manual should be consulted for full
19874 details. The section that follows is a brief introduction to the
19875 philosophy and use of @code{GDB}.
19877 When GNAT programs are compiled, the compiler optionally writes debugging
19878 information into the generated object file, including information on
19879 line numbers, and on declared types and variables. This information is
19880 separate from the generated code. It makes the object files considerably
19881 larger, but it does not add to the size of the actual executable that
19882 will be loaded into memory, and has no impact on run-time performance. The
19883 generation of debug information is triggered by the use of the
19884 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19885 used to carry out the compilations. It is important to emphasize that
19886 the use of these options does not change the generated code.
19888 The debugging information is written in standard system formats that
19889 are used by many tools, including debuggers and profilers. The format
19890 of the information is typically designed to describe C types and
19891 semantics, but GNAT implements a translation scheme which allows full
19892 details about Ada types and variables to be encoded into these
19893 standard C formats. Details of this encoding scheme may be found in
19894 the file exp_dbug.ads in the GNAT source distribution. However, the
19895 details of this encoding are, in general, of no interest to a user,
19896 since @code{GDB} automatically performs the necessary decoding.
19898 When a program is bound and linked, the debugging information is
19899 collected from the object files, and stored in the executable image of
19900 the program. Again, this process significantly increases the size of
19901 the generated executable file, but it does not increase the size of
19902 the executable program itself. Furthermore, if this program is run in
19903 the normal manner, it runs exactly as if the debug information were
19904 not present, and takes no more actual memory.
19906 However, if the program is run under control of @code{GDB}, the
19907 debugger is activated.  The image of the program is loaded, at which
19908 point it is ready to run.  If a run command is given, then the program
19909 will run exactly as it would have if @code{GDB} were not present. This
19910 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19911 entirely non-intrusive until a breakpoint is encountered.  If no
19912 breakpoint is ever hit, the program will run exactly as it would if no
19913 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19914 the debugging information and can respond to user commands to inspect
19915 variables, and more generally to report on the state of execution.
19917 @c **************
19918 @node Running GDB
19919 @section Running GDB
19921 @noindent
19922 This section describes how to initiate the debugger.
19923 @c The above sentence is really just filler, but it was otherwise
19924 @c clumsy to get the first paragraph nonindented given the conditional
19925 @c nature of the description
19927 @ifclear vms
19928 The debugger can be launched from a @code{GPS} menu or
19929 directly from the command line. The description below covers the latter use.
19930 All the commands shown can be used in the @code{GPS} debug console window,
19931 but there are usually more GUI-based ways to achieve the same effect.
19932 @end ifclear
19934 The command to run @code{GDB} is
19936 @smallexample
19937 $ ^gdb program^GDB PROGRAM^
19938 @end smallexample
19940 @noindent
19941 where @code{^program^PROGRAM^} is the name of the executable file. This
19942 activates the debugger and results in a prompt for debugger commands.
19943 The simplest command is simply @code{run}, which causes the program to run
19944 exactly as if the debugger were not present. The following section
19945 describes some of the additional commands that can be given to @code{GDB}.
19947 @c *******************************
19948 @node Introduction to GDB Commands
19949 @section Introduction to GDB Commands
19951 @noindent
19952 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19953 Debugging with GDB, gdb, Debugging with GDB},
19954 @ifset vms
19955 located in the GNU:[DOCS] directory,
19956 @end ifset
19957 for extensive documentation on the use
19958 of these commands, together with examples of their use. Furthermore,
19959 the command @command{help} invoked from within GDB activates a simple help
19960 facility which summarizes the available commands and their options.
19961 In this section we summarize a few of the most commonly
19962 used commands to give an idea of what @code{GDB} is about. You should create
19963 a simple program with debugging information and experiment with the use of
19964 these @code{GDB} commands on the program as you read through the
19965 following section.
19967 @table @code
19968 @item set args @var{arguments}
19969 The @var{arguments} list above is a list of arguments to be passed to
19970 the program on a subsequent run command, just as though the arguments
19971 had been entered on a normal invocation of the program. The @code{set args}
19972 command is not needed if the program does not require arguments.
19974 @item run
19975 The @code{run} command causes execution of the program to start from
19976 the beginning. If the program is already running, that is to say if
19977 you are currently positioned at a breakpoint, then a prompt will ask
19978 for confirmation that you want to abandon the current execution and
19979 restart.
19981 @item breakpoint @var{location}
19982 The breakpoint command sets a breakpoint, that is to say a point at which
19983 execution will halt and @code{GDB} will await further
19984 commands. @var{location} is
19985 either a line number within a file, given in the format @code{file:linenumber},
19986 or it is the name of a subprogram. If you request that a breakpoint be set on
19987 a subprogram that is overloaded, a prompt will ask you to specify on which of
19988 those subprograms you want to breakpoint. You can also
19989 specify that all of them should be breakpointed. If the program is run
19990 and execution encounters the breakpoint, then the program
19991 stops and @code{GDB} signals that the breakpoint was encountered by
19992 printing the line of code before which the program is halted.
19994 @item catch exception @var{name}
19995 This command causes the program execution to stop whenever exception
19996 @var{name} is raised.  If @var{name} is omitted, then the execution is
19997 suspended when any exception is raised.
19999 @item print @var{expression}
20000 This will print the value of the given expression. Most simple
20001 Ada expression formats are properly handled by @code{GDB}, so the expression
20002 can contain function calls, variables, operators, and attribute references.
20004 @item continue
20005 Continues execution following a breakpoint, until the next breakpoint or the
20006 termination of the program.
20008 @item step
20009 Executes a single line after a breakpoint. If the next statement
20010 is a subprogram call, execution continues into (the first statement of)
20011 the called subprogram.
20013 @item next
20014 Executes a single line. If this line is a subprogram call, executes and
20015 returns from the call.
20017 @item list
20018 Lists a few lines around the current source location. In practice, it
20019 is usually more convenient to have a separate edit window open with the
20020 relevant source file displayed. Successive applications of this command
20021 print subsequent lines. The command can be given an argument which is a
20022 line number, in which case it displays a few lines around the specified one.
20024 @item backtrace
20025 Displays a backtrace of the call chain. This command is typically
20026 used after a breakpoint has occurred, to examine the sequence of calls that
20027 leads to the current breakpoint. The display includes one line for each
20028 activation record (frame) corresponding to an active subprogram.
20030 @item up
20031 At a breakpoint, @code{GDB} can display the values of variables local
20032 to the current frame. The command @code{up} can be used to
20033 examine the contents of other active frames, by moving the focus up
20034 the stack, that is to say from callee to caller, one frame at a time.
20036 @item down
20037 Moves the focus of @code{GDB} down from the frame currently being
20038 examined to the frame of its callee (the reverse of the previous command),
20040 @item frame @var{n}
20041 Inspect the frame with the given number. The value 0 denotes the frame
20042 of the current breakpoint, that is to say the top of the call stack.
20044 @end table
20046 @noindent
20047 The above list is a very short introduction to the commands that
20048 @code{GDB} provides. Important additional capabilities, including conditional
20049 breakpoints, the ability to execute command sequences on a breakpoint,
20050 the ability to debug at the machine instruction level and many other
20051 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20052 Debugging with GDB}.  Note that most commands can be abbreviated
20053 (for example, c for continue, bt for backtrace).
20055 @node Using Ada Expressions
20056 @section Using Ada Expressions
20057 @cindex Ada expressions
20059 @noindent
20060 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20061 extensions. The philosophy behind the design of this subset is
20063 @itemize @bullet
20064 @item
20065 That @code{GDB} should provide basic literals and access to operations for
20066 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20067 leaving more sophisticated computations to subprograms written into the
20068 program (which therefore may be called from @code{GDB}).
20070 @item
20071 That type safety and strict adherence to Ada language restrictions
20072 are not particularly important to the @code{GDB} user.
20074 @item
20075 That brevity is important to the @code{GDB} user.
20076 @end itemize
20078 @noindent
20079 Thus, for brevity, the debugger acts as if there were
20080 implicit @code{with} and @code{use} clauses in effect for all user-written
20081 packages, thus making it unnecessary to fully qualify most names with
20082 their packages, regardless of context. Where this causes ambiguity,
20083 @code{GDB} asks the user's intent.
20085 For details on the supported Ada syntax, see @ref{Top,, Debugging with
20086 GDB, gdb, Debugging with GDB}.
20088 @node Calling User-Defined Subprograms
20089 @section Calling User-Defined Subprograms
20091 @noindent
20092 An important capability of @code{GDB} is the ability to call user-defined
20093 subprograms while debugging. This is achieved simply by entering
20094 a subprogram call statement in the form:
20096 @smallexample
20097 call subprogram-name (parameters)
20098 @end smallexample
20100 @noindent
20101 The keyword @code{call} can be omitted in the normal case where the
20102 @code{subprogram-name} does not coincide with any of the predefined
20103 @code{GDB} commands.
20105 The effect is to invoke the given subprogram, passing it the
20106 list of parameters that is supplied. The parameters can be expressions and
20107 can include variables from the program being debugged. The
20108 subprogram must be defined
20109 at the library level within your program, and @code{GDB} will call the
20110 subprogram within the environment of your program execution (which
20111 means that the subprogram is free to access or even modify variables
20112 within your program).
20114 The most important use of this facility is in allowing the inclusion of
20115 debugging routines that are tailored to particular data structures
20116 in your program. Such debugging routines can be written to provide a suitably
20117 high-level description of an abstract type, rather than a low-level dump
20118 of its physical layout. After all, the standard
20119 @code{GDB print} command only knows the physical layout of your
20120 types, not their abstract meaning. Debugging routines can provide information
20121 at the desired semantic level and are thus enormously useful.
20123 For example, when debugging GNAT itself, it is crucial to have access to
20124 the contents of the tree nodes used to represent the program internally.
20125 But tree nodes are represented simply by an integer value (which in turn
20126 is an index into a table of nodes).
20127 Using the @code{print} command on a tree node would simply print this integer
20128 value, which is not very useful. But the PN routine (defined in file
20129 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20130 a useful high level representation of the tree node, which includes the
20131 syntactic category of the node, its position in the source, the integers
20132 that denote descendant nodes and parent node, as well as varied
20133 semantic information. To study this example in more detail, you might want to
20134 look at the body of the PN procedure in the stated file.
20136 @node Using the Next Command in a Function
20137 @section Using the Next Command in a Function
20139 @noindent
20140 When you use the @code{next} command in a function, the current source
20141 location will advance to the next statement as usual. A special case
20142 arises in the case of a @code{return} statement.
20144 Part of the code for a return statement is the ``epilog'' of the function.
20145 This is the code that returns to the caller. There is only one copy of
20146 this epilog code, and it is typically associated with the last return
20147 statement in the function if there is more than one return. In some
20148 implementations, this epilog is associated with the first statement
20149 of the function.
20151 The result is that if you use the @code{next} command from a return
20152 statement that is not the last return statement of the function you
20153 may see a strange apparent jump to the last return statement or to
20154 the start of the function. You should simply ignore this odd jump.
20155 The value returned is always that from the first return statement
20156 that was stepped through.
20158 @node Ada Exceptions
20159 @section Stopping when Ada Exceptions are Raised
20160 @cindex Exceptions
20162 @noindent
20163 You can set catchpoints that stop the program execution when your program
20164 raises selected exceptions.
20166 @table @code
20167 @item catch exception
20168 Set a catchpoint that stops execution whenever (any task in the) program
20169 raises any exception.
20171 @item catch exception @var{name}
20172 Set a catchpoint that stops execution whenever (any task in the) program
20173 raises the exception @var{name}.
20175 @item catch exception unhandled
20176 Set a catchpoint that stops executing whenever (any task in the) program
20177 raises an exception for which there is no handler.
20179 @item info exceptions
20180 @itemx info exceptions @var{regexp}
20181 The @code{info exceptions} command permits the user to examine all defined
20182 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20183 argument, prints out only those exceptions whose name matches @var{regexp}.
20184 @end table
20186 @node Ada Tasks
20187 @section Ada Tasks
20188 @cindex Tasks
20190 @noindent
20191 @code{GDB} allows the following task-related commands:
20193 @table @code
20194 @item info tasks
20195 This command shows a list of current Ada tasks, as in the following example:
20197 @smallexample
20198 @iftex
20199 @leftskip=0cm
20200 @end iftex
20201 (gdb) info tasks
20202   ID       TID P-ID   Thread Pri State                 Name
20203    1   8088000   0   807e000  15 Child Activation Wait main_task
20204    2   80a4000   1   80ae000  15 Accept/Select Wait    b
20205    3   809a800   1   80a4800  15 Child Activation Wait a
20206 *  4   80ae800   3   80b8000  15 Running               c
20207 @end smallexample
20209 @noindent
20210 In this listing, the asterisk before the first task indicates it to be the
20211 currently running task. The first column lists the task ID that is used
20212 to refer to tasks in the following commands.
20214 @item break @var{linespec} task @var{taskid}
20215 @itemx break @var{linespec} task @var{taskid} if @dots{}
20216 @cindex Breakpoints and tasks
20217 These commands are like the @code{break @dots{} thread @dots{}}.
20218 @var{linespec} specifies source lines.
20220 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20221 to specify that you only want @code{GDB} to stop the program when a
20222 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20223 numeric task identifiers assigned by @code{GDB}, shown in the first
20224 column of the @samp{info tasks} display.
20226 If you do not specify @samp{task @var{taskid}} when you set a
20227 breakpoint, the breakpoint applies to @emph{all} tasks of your
20228 program.
20230 You can use the @code{task} qualifier on conditional breakpoints as
20231 well; in this case, place @samp{task @var{taskid}} before the
20232 breakpoint condition (before the @code{if}).
20234 @item task @var{taskno}
20235 @cindex Task switching
20237 This command allows to switch to the task referred by @var{taskno}. In
20238 particular, This allows to browse the backtrace of the specified
20239 task. It is advised to switch back to the original task before
20240 continuing execution otherwise the scheduling of the program may be
20241 perturbed.
20242 @end table
20244 @noindent
20245 For more detailed information on the tasking support,
20246 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
20248 @node Debugging Generic Units
20249 @section Debugging Generic Units
20250 @cindex Debugging Generic Units
20251 @cindex Generics
20253 @noindent
20254 GNAT always uses code expansion for generic instantiation. This means that
20255 each time an instantiation occurs, a complete copy of the original code is
20256 made, with appropriate substitutions of formals by actuals.
20258 It is not possible to refer to the original generic entities in
20259 @code{GDB}, but it is always possible to debug a particular instance of
20260 a generic, by using the appropriate expanded names. For example, if we have
20262 @smallexample @c ada
20263 @group
20264 @cartouche
20265 procedure g is
20267    generic package k is
20268       procedure kp (v1 : in out integer);
20269    end k;
20271    package body k is
20272       procedure kp (v1 : in out integer) is
20273       begin
20274          v1 := v1 + 1;
20275       end kp;
20276    end k;
20278    package k1 is new k;
20279    package k2 is new k;
20281    var : integer := 1;
20283 begin
20284    k1.kp (var);
20285    k2.kp (var);
20286    k1.kp (var);
20287    k2.kp (var);
20288 end;
20289 @end cartouche
20290 @end group
20291 @end smallexample
20293 @noindent
20294 Then to break on a call to procedure kp in the k2 instance, simply
20295 use the command:
20297 @smallexample
20298 (gdb) break g.k2.kp
20299 @end smallexample
20301 @noindent
20302 When the breakpoint occurs, you can step through the code of the
20303 instance in the normal manner and examine the values of local variables, as for
20304 other units.
20306 @node Remote Debugging using gdbserver
20307 @section Remote Debugging using gdbserver
20308 @cindex Remote Debugging using gdbserver
20310 @noindent
20311 On platforms where gdbserver is supported, it is possible to use this tool
20312 to debug your application remotely.  This can be useful in situations
20313 where the program needs to be run on a target host that is different
20314 from the host used for development, particularly when the target has
20315 a limited amount of resources (either CPU and/or memory).
20317 To do so, start your program using gdbserver on the target machine.
20318 gdbserver then automatically suspends the execution of your program
20319 at its entry point, waiting for a debugger to connect to it.  The
20320 following commands starts an application and tells gdbserver to
20321 wait for a connection with the debugger on localhost port 4444.
20323 @smallexample
20324 $ gdbserver localhost:4444 program
20325 Process program created; pid = 5685
20326 Listening on port 4444
20327 @end smallexample
20329 Once gdbserver has started listening, we can tell the debugger to establish
20330 a connection with this gdbserver, and then start the same debugging session
20331 as if the program was being debugged on the same host, directly under
20332 the control of GDB.
20334 @smallexample
20335 $ gdb program
20336 (gdb) target remote targethost:4444
20337 Remote debugging using targethost:4444
20338 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
20339 (gdb) b foo.adb:3
20340 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
20341 (gdb) continue
20342 Continuing.
20344 Breakpoint 1, foo () at foo.adb:4
20345 4       end foo;
20346 @end smallexample
20348 It is also possible to use gdbserver to attach to an already running
20349 program, in which case the execution of that program is simply suspended
20350 until the connection between the debugger and gdbserver is established.
20352 For more information on how to use gdbserver, @ref{Top, Server, Using
20353 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
20354 for gdbserver on x86-linux, x86-windows and x86_64-linux.
20356 @node GNAT Abnormal Termination or Failure to Terminate
20357 @section GNAT Abnormal Termination or Failure to Terminate
20358 @cindex GNAT Abnormal Termination or Failure to Terminate
20360 @noindent
20361 When presented with programs that contain serious errors in syntax
20362 or semantics,
20363 GNAT may on rare occasions  experience problems in operation, such
20364 as aborting with a
20365 segmentation fault or illegal memory access, raising an internal
20366 exception, terminating abnormally, or failing to terminate at all.
20367 In such cases, you can activate
20368 various features of GNAT that can help you pinpoint the construct in your
20369 program that is the likely source of the problem.
20371 The following strategies are presented in increasing order of
20372 difficulty, corresponding to your experience in using GNAT and your
20373 familiarity with compiler internals.
20375 @enumerate
20376 @item
20377 Run @command{gcc} with the @option{-gnatf}. This first
20378 switch causes all errors on a given line to be reported. In its absence,
20379 only the first error on a line is displayed.
20381 The @option{-gnatdO} switch causes errors to be displayed as soon as they
20382 are encountered, rather than after compilation is terminated. If GNAT
20383 terminates prematurely or goes into an infinite loop, the last error
20384 message displayed may help to pinpoint the culprit.
20386 @item
20387 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
20388 mode, @command{gcc} produces ongoing information about the progress of the
20389 compilation and provides the name of each procedure as code is
20390 generated. This switch allows you to find which Ada procedure was being
20391 compiled when it encountered a code generation problem.
20393 @item
20394 @cindex @option{-gnatdc} switch
20395 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
20396 switch that does for the front-end what @option{^-v^VERBOSE^} does
20397 for the back end. The system prints the name of each unit,
20398 either a compilation unit or nested unit, as it is being analyzed.
20399 @item
20400 Finally, you can start
20401 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
20402 front-end of GNAT, and can be run independently (normally it is just
20403 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
20404 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
20405 @code{where} command is the first line of attack; the variable
20406 @code{lineno} (seen by @code{print lineno}), used by the second phase of
20407 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
20408 which the execution stopped, and @code{input_file name} indicates the name of
20409 the source file.
20410 @end enumerate
20412 @node Naming Conventions for GNAT Source Files
20413 @section Naming Conventions for GNAT Source Files
20415 @noindent
20416 In order to examine the workings of the GNAT system, the following
20417 brief description of its organization may be helpful:
20419 @itemize @bullet
20420 @item
20421 Files with prefix @file{^sc^SC^} contain the lexical scanner.
20423 @item
20424 All files prefixed with @file{^par^PAR^} are components of the parser. The
20425 numbers correspond to chapters of the Ada Reference Manual. For example,
20426 parsing of select statements can be found in @file{par-ch9.adb}.
20428 @item
20429 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
20430 numbers correspond to chapters of the Ada standard. For example, all
20431 issues involving context clauses can be found in @file{sem_ch10.adb}. In
20432 addition, some features of the language require sufficient special processing
20433 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
20434 dynamic dispatching, etc.
20436 @item
20437 All files prefixed with @file{^exp^EXP^} perform normalization and
20438 expansion of the intermediate representation (abstract syntax tree, or AST).
20439 these files use the same numbering scheme as the parser and semantics files.
20440 For example, the construction of record initialization procedures is done in
20441 @file{exp_ch3.adb}.
20443 @item
20444 The files prefixed with @file{^bind^BIND^} implement the binder, which
20445 verifies the consistency of the compilation, determines an order of
20446 elaboration, and generates the bind file.
20448 @item
20449 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20450 data structures used by the front-end.
20452 @item
20453 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20454 the abstract syntax tree as produced by the parser.
20456 @item
20457 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20458 all entities, computed during semantic analysis.
20460 @item
20461 Library management issues are dealt with in files with prefix
20462 @file{^lib^LIB^}.
20464 @item
20465 @findex Ada
20466 @cindex Annex A
20467 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20468 defined in Annex A.
20470 @item
20471 @findex Interfaces
20472 @cindex Annex B
20473 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20474 defined in Annex B.
20476 @item
20477 @findex System
20478 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20479 both language-defined children and GNAT run-time routines.
20481 @item
20482 @findex GNAT
20483 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
20484 general-purpose packages, fully documented in their specs. All
20485 the other @file{.c} files are modifications of common @command{gcc} files.
20486 @end itemize
20488 @node Getting Internal Debugging Information
20489 @section Getting Internal Debugging Information
20491 @noindent
20492 Most compilers have internal debugging switches and modes. GNAT
20493 does also, except GNAT internal debugging switches and modes are not
20494 secret. A summary and full description of all the compiler and binder
20495 debug flags are in the file @file{debug.adb}. You must obtain the
20496 sources of the compiler to see the full detailed effects of these flags.
20498 The switches that print the source of the program (reconstructed from
20499 the internal tree) are of general interest for user programs, as are the
20500 options to print
20501 the full internal tree, and the entity table (the symbol table
20502 information). The reconstructed source provides a readable version of the
20503 program after the front-end has completed analysis and  expansion,
20504 and is useful when studying the performance of specific constructs.
20505 For example, constraint checks are indicated, complex aggregates
20506 are replaced with loops and assignments, and tasking primitives
20507 are replaced with run-time calls.
20509 @node Stack Traceback
20510 @section Stack Traceback
20511 @cindex traceback
20512 @cindex stack traceback
20513 @cindex stack unwinding
20515 @noindent
20516 Traceback is a mechanism to display the sequence of subprogram calls that
20517 leads to a specified execution point in a program. Often (but not always)
20518 the execution point is an instruction at which an exception has been raised.
20519 This mechanism is also known as @i{stack unwinding} because it obtains
20520 its information by scanning the run-time stack and recovering the activation
20521 records of all active subprograms. Stack unwinding is one of the most
20522 important tools for program debugging.
20524 The first entry stored in traceback corresponds to the deepest calling level,
20525 that is to say the subprogram currently executing the instruction
20526 from which we want to obtain the traceback.
20528 Note that there is no runtime performance penalty when stack traceback
20529 is enabled, and no exception is raised during program execution.
20531 @menu
20532 * Non-Symbolic Traceback::
20533 * Symbolic Traceback::
20534 @end menu
20536 @node Non-Symbolic Traceback
20537 @subsection Non-Symbolic Traceback
20538 @cindex traceback, non-symbolic
20540 @noindent
20541 Note: this feature is not supported on all platforms. See
20542 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20543 platforms.
20545 @menu
20546 * Tracebacks From an Unhandled Exception::
20547 * Tracebacks From Exception Occurrences (non-symbolic)::
20548 * Tracebacks From Anywhere in a Program (non-symbolic)::
20549 @end menu
20551 @node Tracebacks From an Unhandled Exception
20552 @subsubsection Tracebacks From an Unhandled Exception
20554 @noindent
20555 A runtime non-symbolic traceback is a list of addresses of call instructions.
20556 To enable this feature you must use the @option{-E}
20557 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20558 of exception information. You can retrieve this information using the
20559 @code{addr2line} tool.
20561 Here is a simple example:
20563 @smallexample @c ada
20564 @cartouche
20565 procedure STB is
20567    procedure P1 is
20568    begin
20569       raise Constraint_Error;
20570    end P1;
20572    procedure P2 is
20573    begin
20574       P1;
20575    end P2;
20577 begin
20578    P2;
20579 end STB;
20580 @end cartouche
20581 @end smallexample
20583 @smallexample
20584 $ gnatmake stb -bargs -E
20585 $ stb
20587 Execution terminated by unhandled exception
20588 Exception name: CONSTRAINT_ERROR
20589 Message: stb.adb:5
20590 Call stack traceback locations:
20591 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20592 @end smallexample
20594 @noindent
20595 As we see the traceback lists a sequence of addresses for the unhandled
20596 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20597 guess that this exception come from procedure P1. To translate these
20598 addresses into the source lines where the calls appear, the
20599 @code{addr2line} tool, described below, is invaluable. The use of this tool
20600 requires the program to be compiled with debug information.
20602 @smallexample
20603 $ gnatmake -g stb -bargs -E
20604 $ stb
20606 Execution terminated by unhandled exception
20607 Exception name: CONSTRAINT_ERROR
20608 Message: stb.adb:5
20609 Call stack traceback locations:
20610 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20612 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20613    0x4011f1 0x77e892a4
20615 00401373 at d:/stb/stb.adb:5
20616 0040138B at d:/stb/stb.adb:10
20617 0040139C at d:/stb/stb.adb:14
20618 00401335 at d:/stb/b~stb.adb:104
20619 004011C4 at /build/@dots{}/crt1.c:200
20620 004011F1 at /build/@dots{}/crt1.c:222
20621 77E892A4 in ?? at ??:0
20622 @end smallexample
20624 @noindent
20625 The @code{addr2line} tool has several other useful options:
20627 @table @code
20628 @item --functions
20629 to get the function name corresponding to any location
20631 @item --demangle=gnat
20632 to use the gnat decoding mode for the function names. Note that
20633 for binutils version 2.9.x the option is simply @option{--demangle}.
20634 @end table
20636 @smallexample
20637 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20638    0x40139c 0x401335 0x4011c4 0x4011f1
20640 00401373 in stb.p1 at d:/stb/stb.adb:5
20641 0040138B in stb.p2 at d:/stb/stb.adb:10
20642 0040139C in stb at d:/stb/stb.adb:14
20643 00401335 in main at d:/stb/b~stb.adb:104
20644 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
20645 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
20646 @end smallexample
20648 @noindent
20649 From this traceback we can see that the exception was raised in
20650 @file{stb.adb} at line 5, which was reached from a procedure call in
20651 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20652 which contains the call to the main program.
20653 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20654 and the output will vary from platform to platform.
20656 It is also possible to use @code{GDB} with these traceback addresses to debug
20657 the program. For example, we can break at a given code location, as reported
20658 in the stack traceback:
20660 @smallexample
20661 $ gdb -nw stb
20662 @ifclear vms
20663 @noindent
20664 Furthermore, this feature is not implemented inside Windows DLL. Only
20665 the non-symbolic traceback is reported in this case.
20666 @end ifclear
20668 (gdb) break *0x401373
20669 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20670 @end smallexample
20672 @noindent
20673 It is important to note that the stack traceback addresses
20674 do not change when debug information is included. This is particularly useful
20675 because it makes it possible to release software without debug information (to
20676 minimize object size), get a field report that includes a stack traceback
20677 whenever an internal bug occurs, and then be able to retrieve the sequence
20678 of calls with the same program compiled with debug information.
20680 @node Tracebacks From Exception Occurrences (non-symbolic)
20681 @subsubsection Tracebacks From Exception Occurrences
20683 @noindent
20684 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20685 The stack traceback is attached to the exception information string, and can
20686 be retrieved in an exception handler within the Ada program, by means of the
20687 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20689 @smallexample @c ada
20690 with Ada.Text_IO;
20691 with Ada.Exceptions;
20693 procedure STB is
20695    use Ada;
20696    use Ada.Exceptions;
20698    procedure P1 is
20699       K : Positive := 1;
20700    begin
20701       K := K - 1;
20702    exception
20703       when E : others =>
20704          Text_IO.Put_Line (Exception_Information (E));
20705    end P1;
20707    procedure P2 is
20708    begin
20709       P1;
20710    end P2;
20712 begin
20713    P2;
20714 end STB;
20715 @end smallexample
20717 @noindent
20718 This program will output:
20720 @smallexample
20721 $ stb
20723 Exception name: CONSTRAINT_ERROR
20724 Message: stb.adb:12
20725 Call stack traceback locations:
20726 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20727 @end smallexample
20729 @node Tracebacks From Anywhere in a Program (non-symbolic)
20730 @subsubsection Tracebacks From Anywhere in a Program
20732 @noindent
20733 It is also possible to retrieve a stack traceback from anywhere in a
20734 program. For this you need to
20735 use the @code{GNAT.Traceback} API. This package includes a procedure called
20736 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20737 display procedures described below. It is not necessary to use the
20738 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20739 is invoked explicitly.
20741 @noindent
20742 In the following example we compute a traceback at a specific location in
20743 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20744 convert addresses to strings:
20746 @smallexample @c ada
20747 with Ada.Text_IO;
20748 with GNAT.Traceback;
20749 with GNAT.Debug_Utilities;
20751 procedure STB is
20753    use Ada;
20754    use GNAT;
20755    use GNAT.Traceback;
20757    procedure P1 is
20758       TB  : Tracebacks_Array (1 .. 10);
20759       --  We are asking for a maximum of 10 stack frames.
20760       Len : Natural;
20761       --  Len will receive the actual number of stack frames returned.
20762    begin
20763       Call_Chain (TB, Len);
20765       Text_IO.Put ("In STB.P1 : ");
20767       for K in 1 .. Len loop
20768          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20769          Text_IO.Put (' ');
20770       end loop;
20772       Text_IO.New_Line;
20773    end P1;
20775    procedure P2 is
20776    begin
20777       P1;
20778    end P2;
20780 begin
20781    P2;
20782 end STB;
20783 @end smallexample
20785 @smallexample
20786 $ gnatmake -g stb
20787 $ stb
20789 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20790 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20791 @end smallexample
20793 @noindent
20794 You can then get further information by invoking the @code{addr2line}
20795 tool as described earlier (note that the hexadecimal addresses
20796 need to be specified in C format, with a leading ``0x'').
20798 @node Symbolic Traceback
20799 @subsection Symbolic Traceback
20800 @cindex traceback, symbolic
20802 @noindent
20803 A symbolic traceback is a stack traceback in which procedure names are
20804 associated with each code location.
20806 @noindent
20807 Note that this feature is not supported on all platforms. See
20808 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20809 list of currently supported platforms.
20811 @noindent
20812 Note that the symbolic traceback requires that the program be compiled
20813 with debug information. If it is not compiled with debug information
20814 only the non-symbolic information will be valid.
20816 @menu
20817 * Tracebacks From Exception Occurrences (symbolic)::
20818 * Tracebacks From Anywhere in a Program (symbolic)::
20819 @end menu
20821 @node Tracebacks From Exception Occurrences (symbolic)
20822 @subsubsection Tracebacks From Exception Occurrences
20824 @smallexample @c ada
20825 with Ada.Text_IO;
20826 with GNAT.Traceback.Symbolic;
20828 procedure STB is
20830    procedure P1 is
20831    begin
20832       raise Constraint_Error;
20833    end P1;
20835    procedure P2 is
20836    begin
20837       P1;
20838    end P2;
20840    procedure P3 is
20841    begin
20842       P2;
20843    end P3;
20845 begin
20846    P3;
20847 exception
20848    when E : others =>
20849       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20850 end STB;
20851 @end smallexample
20853 @smallexample
20854 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20855 $ stb
20857 0040149F in stb.p1 at stb.adb:8
20858 004014B7 in stb.p2 at stb.adb:13
20859 004014CF in stb.p3 at stb.adb:18
20860 004015DD in ada.stb at stb.adb:22
20861 00401461 in main at b~stb.adb:168
20862 004011C4 in __mingw_CRTStartup at crt1.c:200
20863 004011F1 in mainCRTStartup at crt1.c:222
20864 77E892A4 in ?? at ??:0
20865 @end smallexample
20867 @noindent
20868 In the above example the ``.\'' syntax in the @command{gnatmake} command
20869 is currently required by @command{addr2line} for files that are in
20870 the current working directory.
20871 Moreover, the exact sequence of linker options may vary from platform
20872 to platform.
20873 The above @option{-largs} section is for Windows platforms. By contrast,
20874 under Unix there is no need for the @option{-largs} section.
20875 Differences across platforms are due to details of linker implementation.
20877 @node Tracebacks From Anywhere in a Program (symbolic)
20878 @subsubsection Tracebacks From Anywhere in a Program
20880 @noindent
20881 It is possible to get a symbolic stack traceback
20882 from anywhere in a program, just as for non-symbolic tracebacks.
20883 The first step is to obtain a non-symbolic
20884 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20885 information. Here is an example:
20887 @smallexample @c ada
20888 with Ada.Text_IO;
20889 with GNAT.Traceback;
20890 with GNAT.Traceback.Symbolic;
20892 procedure STB is
20894    use Ada;
20895    use GNAT.Traceback;
20896    use GNAT.Traceback.Symbolic;
20898    procedure P1 is
20899       TB  : Tracebacks_Array (1 .. 10);
20900       --  We are asking for a maximum of 10 stack frames.
20901       Len : Natural;
20902       --  Len will receive the actual number of stack frames returned.
20903    begin
20904       Call_Chain (TB, Len);
20905       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20906    end P1;
20908    procedure P2 is
20909    begin
20910       P1;
20911    end P2;
20913 begin
20914    P2;
20915 end STB;
20916 @end smallexample
20918 @c ******************************
20919 @ifset vms
20920 @node Compatibility with HP Ada
20921 @chapter Compatibility with HP Ada
20922 @cindex Compatibility
20924 @noindent
20925 @cindex DEC Ada
20926 @cindex HP Ada
20927 @cindex Compatibility between GNAT and HP Ada
20928 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20929 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20930 GNAT is highly compatible
20931 with HP Ada, and it should generally be straightforward to port code
20932 from the HP Ada environment to GNAT. However, there are a few language
20933 and implementation differences of which the user must be aware. These
20934 differences are discussed in this chapter. In
20935 addition, the operating environment and command structure for the
20936 compiler are different, and these differences are also discussed.
20938 For further details on these and other compatibility issues,
20939 see Appendix E of the HP publication
20940 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20942 Except where otherwise indicated, the description of GNAT for OpenVMS
20943 applies to both the Alpha and I64 platforms.
20945 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20946 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20948 The discussion in this chapter addresses specifically the implementation
20949 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20950 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20951 GNAT always follows the Alpha implementation.
20953 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20954 attributes are recognized, although only a subset of them can sensibly
20955 be implemented.  The description of pragmas in
20956 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20957 indicates whether or not they are applicable to non-VMS systems.
20959 @menu
20960 * Ada Language Compatibility::
20961 * Differences in the Definition of Package System::
20962 * Language-Related Features::
20963 * The Package STANDARD::
20964 * The Package SYSTEM::
20965 * Tasking and Task-Related Features::
20966 * Pragmas and Pragma-Related Features::
20967 * Library of Predefined Units::
20968 * Bindings::
20969 * Main Program Definition::
20970 * Implementation-Defined Attributes::
20971 * Compiler and Run-Time Interfacing::
20972 * Program Compilation and Library Management::
20973 * Input-Output::
20974 * Implementation Limits::
20975 * Tools and Utilities::
20976 @end menu
20978 @node Ada Language Compatibility
20979 @section Ada Language Compatibility
20981 @noindent
20982 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20983 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20984 with Ada 83, and therefore Ada 83 programs will compile
20985 and run under GNAT with
20986 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20987 provides details on specific incompatibilities.
20989 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20990 as well as the pragma @code{ADA_83}, to force the compiler to
20991 operate in Ada 83 mode. This mode does not guarantee complete
20992 conformance to Ada 83, but in practice is sufficient to
20993 eliminate most sources of incompatibilities.
20994 In particular, it eliminates the recognition of the
20995 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20996 in Ada 83 programs is legal, and handles the cases of packages
20997 with optional bodies, and generics that instantiate unconstrained
20998 types without the use of @code{(<>)}.
21000 @node Differences in the Definition of Package System
21001 @section Differences in the Definition of Package @code{System}
21003 @noindent
21004 An Ada compiler is allowed to add
21005 implementation-dependent declarations to package @code{System}.
21006 In normal mode,
21007 GNAT does not take advantage of this permission, and the version of
21008 @code{System} provided by GNAT exactly matches that defined in the Ada
21009 Reference Manual.
21011 However, HP Ada adds an extensive set of declarations to package
21012 @code{System},
21013 as fully documented in the HP Ada manuals. To minimize changes required
21014 for programs that make use of these extensions, GNAT provides the pragma
21015 @code{Extend_System} for extending the definition of package System. By using:
21016 @cindex pragma @code{Extend_System}
21017 @cindex @code{Extend_System} pragma
21019 @smallexample @c ada
21020 @group
21021 @cartouche
21022 pragma Extend_System (Aux_DEC);
21023 @end cartouche
21024 @end group
21025 @end smallexample
21027 @noindent
21028 the set of definitions in @code{System} is extended to include those in
21029 package @code{System.Aux_DEC}.
21030 @cindex @code{System.Aux_DEC} package
21031 @cindex @code{Aux_DEC} package (child of @code{System})
21032 These definitions are incorporated directly into package @code{System},
21033 as though they had been declared there. For a
21034 list of the declarations added, see the spec of this package,
21035 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21036 @cindex @file{s-auxdec.ads} file
21037 The pragma @code{Extend_System} is a configuration pragma, which means that
21038 it can be placed in the file @file{gnat.adc}, so that it will automatically
21039 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21040 for further details.
21042 An alternative approach that avoids the use of the non-standard
21043 @code{Extend_System} pragma is to add a context clause to the unit that
21044 references these facilities:
21046 @smallexample @c ada
21047 @cartouche
21048 with System.Aux_DEC;
21049 use  System.Aux_DEC;
21050 @end cartouche
21051 @end smallexample
21053 @noindent
21054 The effect is not quite semantically identical to incorporating
21055 the declarations directly into package @code{System},
21056 but most programs will not notice a difference
21057 unless they use prefix notation (e.g.@: @code{System.Integer_8})
21058 to reference the entities directly in package @code{System}.
21059 For units containing such references,
21060 the prefixes must either be removed, or the pragma @code{Extend_System}
21061 must be used.
21063 @node Language-Related Features
21064 @section Language-Related Features
21066 @noindent
21067 The following sections highlight differences in types,
21068 representations of types, operations, alignment, and
21069 related topics.
21071 @menu
21072 * Integer Types and Representations::
21073 * Floating-Point Types and Representations::
21074 * Pragmas Float_Representation and Long_Float::
21075 * Fixed-Point Types and Representations::
21076 * Record and Array Component Alignment::
21077 * Address Clauses::
21078 * Other Representation Clauses::
21079 @end menu
21081 @node Integer Types and Representations
21082 @subsection Integer Types and Representations
21084 @noindent
21085 The set of predefined integer types is identical in HP Ada and GNAT.
21086 Furthermore the representation of these integer types is also identical,
21087 including the capability of size clauses forcing biased representation.
21089 In addition,
21090 HP Ada for OpenVMS Alpha systems has defined the
21091 following additional integer types in package @code{System}:
21093 @itemize @bullet
21095 @item
21096 @code{INTEGER_8}
21098 @item
21099 @code{INTEGER_16}
21101 @item
21102 @code{INTEGER_32}
21104 @item
21105 @code{INTEGER_64}
21107 @item
21108 @code{LARGEST_INTEGER}
21109 @end itemize
21111 @noindent
21112 In GNAT, the first four of these types may be obtained from the
21113 standard Ada package @code{Interfaces}.
21114 Alternatively, by use of the pragma @code{Extend_System}, identical
21115 declarations can be referenced directly in package @code{System}.
21116 On both GNAT and HP Ada, the maximum integer size is 64 bits.
21118 @node Floating-Point Types and Representations
21119 @subsection Floating-Point Types and Representations
21120 @cindex Floating-Point types
21122 @noindent
21123 The set of predefined floating-point types is identical in HP Ada and GNAT.
21124 Furthermore the representation of these floating-point
21125 types is also identical. One important difference is that the default
21126 representation for HP Ada is @code{VAX_Float}, but the default representation
21127 for GNAT is IEEE.
21129 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
21130 pragma @code{Float_Representation} as described in the HP Ada
21131 documentation.
21132 For example, the declarations:
21134 @smallexample @c ada
21135 @cartouche
21136 type F_Float is digits 6;
21137 pragma Float_Representation (VAX_Float, F_Float);
21138 @end cartouche
21139 @end smallexample
21141 @noindent
21142 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21143 format.
21144 This set of declarations actually appears in @code{System.Aux_DEC},
21145 which contains
21146 the full set of additional floating-point declarations provided in
21147 the HP Ada version of package @code{System}.
21148 This and similar declarations may be accessed in a user program
21149 by using pragma @code{Extend_System}. The use of this
21150 pragma, and the related pragma @code{Long_Float} is described in further
21151 detail in the following section.
21153 @node Pragmas Float_Representation and Long_Float
21154 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
21156 @noindent
21157 HP Ada provides the pragma @code{Float_Representation}, which
21158 acts as a program library switch to allow control over
21159 the internal representation chosen for the predefined
21160 floating-point types declared in the package @code{Standard}.
21161 The format of this pragma is as follows:
21163 @smallexample @c ada
21164 @cartouche
21165 pragma Float_Representation(VAX_Float | IEEE_Float);
21166 @end cartouche
21167 @end smallexample
21169 @noindent
21170 This pragma controls the representation of floating-point
21171 types as follows:
21173 @itemize @bullet
21174 @item
21175 @code{VAX_Float} specifies that floating-point
21176 types are represented by default with the VAX system hardware types
21177 @code{F-floating}, @code{D-floating}, @code{G-floating}.
21178 Note that the @code{H-floating}
21179 type was available only on VAX systems, and is not available
21180 in either HP Ada or GNAT.
21182 @item
21183 @code{IEEE_Float} specifies that floating-point
21184 types are represented by default with the IEEE single and
21185 double floating-point types.
21186 @end itemize
21188 @noindent
21189 GNAT provides an identical implementation of the pragma
21190 @code{Float_Representation}, except that it functions as a
21191 configuration pragma. Note that the
21192 notion of configuration pragma corresponds closely to the
21193 HP Ada notion of a program library switch.
21195 When no pragma is used in GNAT, the default is @code{IEEE_Float},
21196 which is different
21197 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
21198 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
21199 advisable to change the format of numbers passed to standard library
21200 routines, and if necessary explicit type conversions may be needed.
21202 The use of @code{IEEE_Float} is recommended in GNAT since it is more
21203 efficient, and (given that it conforms to an international standard)
21204 potentially more portable.
21205 The situation in which @code{VAX_Float} may be useful is in interfacing
21206 to existing code and data that expect the use of @code{VAX_Float}.
21207 In such a situation use the predefined @code{VAX_Float}
21208 types in package @code{System}, as extended by
21209 @code{Extend_System}. For example, use @code{System.F_Float}
21210 to specify the 32-bit @code{F-Float} format.
21212 @noindent
21213 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
21214 to allow control over the internal representation chosen
21215 for the predefined type @code{Long_Float} and for floating-point
21216 type declarations with digits specified in the range 7 .. 15.
21217 The format of this pragma is as follows:
21219 @smallexample @c ada
21220 @cartouche
21221 pragma Long_Float (D_FLOAT | G_FLOAT);
21222 @end cartouche
21223 @end smallexample
21225 @node Fixed-Point Types and Representations
21226 @subsection Fixed-Point Types and Representations
21228 @noindent
21229 On HP Ada for OpenVMS Alpha systems, rounding is
21230 away from zero for both positive and negative numbers.
21231 Therefore, @code{+0.5} rounds to @code{1},
21232 and @code{-0.5} rounds to @code{-1}.
21234 On GNAT the results of operations
21235 on fixed-point types are in accordance with the Ada
21236 rules. In particular, results of operations on decimal
21237 fixed-point types are truncated.
21239 @node Record and Array Component Alignment
21240 @subsection Record and Array Component Alignment
21242 @noindent
21243 On HP Ada for OpenVMS Alpha, all non-composite components
21244 are aligned on natural boundaries. For example, 1-byte
21245 components are aligned on byte boundaries, 2-byte
21246 components on 2-byte boundaries, 4-byte components on 4-byte
21247 byte boundaries, and so on. The OpenVMS Alpha hardware
21248 runs more efficiently with naturally aligned data.
21250 On GNAT, alignment rules are compatible
21251 with HP Ada for OpenVMS Alpha.
21253 @node Address Clauses
21254 @subsection Address Clauses
21256 @noindent
21257 In HP Ada and GNAT, address clauses are supported for
21258 objects and imported subprograms.
21259 The predefined type @code{System.Address} is a private type
21260 in both compilers on Alpha OpenVMS, with the same representation
21261 (it is simply a machine pointer). Addition, subtraction, and comparison
21262 operations are available in the standard Ada package
21263 @code{System.Storage_Elements}, or in package @code{System}
21264 if it is extended to include @code{System.Aux_DEC} using a
21265 pragma @code{Extend_System} as previously described.
21267 Note that code that @code{with}'s both this extended package @code{System}
21268 and the package @code{System.Storage_Elements} should not @code{use}
21269 both packages, or ambiguities will result. In general it is better
21270 not to mix these two sets of facilities. The Ada package was
21271 designed specifically to provide the kind of features that HP Ada
21272 adds directly to package @code{System}.
21274 The type @code{System.Address} is a 64-bit integer type in GNAT for
21275 I64 OpenVMS.  For more information,
21276 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21278 GNAT is compatible with HP Ada in its handling of address
21279 clauses, except for some limitations in
21280 the form of address clauses for composite objects with
21281 initialization. Such address clauses are easily replaced
21282 by the use of an explicitly-defined constant as described
21283 in the Ada Reference Manual (13.1(22)). For example, the sequence
21284 of declarations:
21286 @smallexample @c ada
21287 @cartouche
21288 X, Y : Integer := Init_Func;
21289 Q : String (X .. Y) := "abc";
21290 @dots{}
21291 for Q'Address use Compute_Address;
21292 @end cartouche
21293 @end smallexample
21295 @noindent
21296 will be rejected by GNAT, since the address cannot be computed at the time
21297 that @code{Q} is declared. To achieve the intended effect, write instead:
21299 @smallexample @c ada
21300 @group
21301 @cartouche
21302 X, Y : Integer := Init_Func;
21303 Q_Address : constant Address := Compute_Address;
21304 Q : String (X .. Y) := "abc";
21305 @dots{}
21306 for Q'Address use Q_Address;
21307 @end cartouche
21308 @end group
21309 @end smallexample
21311 @noindent
21312 which will be accepted by GNAT (and other Ada compilers), and is also
21313 compatible with Ada 83. A fuller description of the restrictions
21314 on address specifications is found in @ref{Top, GNAT Reference Manual,
21315 About This Guide, gnat_rm, GNAT Reference Manual}.
21317 @node Other Representation Clauses
21318 @subsection Other Representation Clauses
21320 @noindent
21321 GNAT implements in a compatible manner all the representation
21322 clauses supported by HP Ada. In addition, GNAT
21323 implements the representation clause forms that were introduced in Ada 95,
21324 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
21326 @node The Package STANDARD
21327 @section The Package @code{STANDARD}
21329 @noindent
21330 The package @code{STANDARD}, as implemented by HP Ada, is fully
21331 described in the @cite{Ada Reference Manual} and in the
21332 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
21333 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
21335 In addition, HP Ada supports the Latin-1 character set in
21336 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
21337 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
21338 the type @code{WIDE_CHARACTER}.
21340 The floating-point types supported by GNAT are those
21341 supported by HP Ada, but the defaults are different, and are controlled by
21342 pragmas. See @ref{Floating-Point Types and Representations}, for details.
21344 @node The Package SYSTEM
21345 @section The Package @code{SYSTEM}
21347 @noindent
21348 HP Ada provides a specific version of the package
21349 @code{SYSTEM} for each platform on which the language is implemented.
21350 For the complete spec of the package @code{SYSTEM}, see
21351 Appendix F of the @cite{HP Ada Language Reference Manual}.
21353 On HP Ada, the package @code{SYSTEM} includes the following conversion
21354 functions:
21355 @itemize @bullet
21356 @item @code{TO_ADDRESS(INTEGER)}
21358 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
21360 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
21362 @item @code{TO_INTEGER(ADDRESS)}
21364 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
21366 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
21367 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
21368 @end itemize
21370 @noindent
21371 By default, GNAT supplies a version of @code{SYSTEM} that matches
21372 the definition given in the @cite{Ada Reference Manual}.
21373 This
21374 is a subset of the HP system definitions, which is as
21375 close as possible to the original definitions. The only difference
21376 is that the definition of @code{SYSTEM_NAME} is different:
21378 @smallexample @c ada
21379 @cartouche
21380 type Name is (SYSTEM_NAME_GNAT);
21381 System_Name : constant Name := SYSTEM_NAME_GNAT;
21382 @end cartouche
21383 @end smallexample
21385 @noindent
21386 Also, GNAT adds the Ada declarations for
21387 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
21389 However, the use of the following pragma causes GNAT
21390 to extend the definition of package @code{SYSTEM} so that it
21391 encompasses the full set of HP-specific extensions,
21392 including the functions listed above:
21394 @smallexample @c ada
21395 @cartouche
21396 pragma Extend_System (Aux_DEC);
21397 @end cartouche
21398 @end smallexample
21400 @noindent
21401 The pragma @code{Extend_System} is a configuration pragma that
21402 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
21403 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
21405 HP Ada does not allow the recompilation of the package
21406 @code{SYSTEM}. Instead HP Ada provides several pragmas
21407 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
21408 to modify values in the package @code{SYSTEM}.
21409 On OpenVMS Alpha systems, the pragma
21410 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
21411 its single argument.
21413 GNAT does permit the recompilation of package @code{SYSTEM} using
21414 the special switch @option{-gnatg}, and this switch can be used if
21415 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
21416 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
21417 or @code{MEMORY_SIZE} by any other means.
21419 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
21420 enumeration literal @code{SYSTEM_NAME_GNAT}.
21422 The definitions provided by the use of
21424 @smallexample @c ada
21425 pragma Extend_System (AUX_Dec);
21426 @end smallexample
21428 @noindent
21429 are virtually identical to those provided by the HP Ada 83 package
21430 @code{SYSTEM}. One important difference is that the name of the
21431 @code{TO_ADDRESS}
21432 function for type @code{UNSIGNED_LONGWORD} is changed to
21433 @code{TO_ADDRESS_LONG}.
21434 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
21435 discussion of why this change was necessary.
21437 @noindent
21438 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
21439 is in fact
21440 an extension to Ada 83 not strictly compatible with the reference manual.
21441 GNAT, in order to be exactly compatible with the standard,
21442 does not provide this capability. In HP Ada 83, the
21443 point of this definition is to deal with a call like:
21445 @smallexample @c ada
21446 TO_ADDRESS (16#12777#);
21447 @end smallexample
21449 @noindent
21450 Normally, according to Ada 83 semantics, one would expect this to be
21451 ambiguous, since it matches both the @code{INTEGER} and
21452 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
21453 However, in HP Ada 83, there is no ambiguity, since the
21454 definition using @i{universal_integer} takes precedence.
21456 In GNAT, since the version with @i{universal_integer} cannot be supplied,
21457 it is
21458 not possible to be 100% compatible. Since there are many programs using
21459 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
21460 GNAT was
21461 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
21462 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
21464 @smallexample @c ada
21465 function To_Address (X : Integer) return Address;
21466 pragma Pure_Function (To_Address);
21468 function To_Address_Long (X : Unsigned_Longword) return Address;
21469 pragma Pure_Function (To_Address_Long);
21470 @end smallexample
21472 @noindent
21473 This means that programs using @code{TO_ADDRESS} for
21474 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
21476 @node Tasking and Task-Related Features
21477 @section Tasking and Task-Related Features
21479 @noindent
21480 This section compares the treatment of tasking in GNAT
21481 and in HP Ada for OpenVMS Alpha.
21482 The GNAT description applies to both Alpha and I64 OpenVMS.
21483 For detailed information on tasking in
21484 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
21485 relevant run-time reference manual.
21487 @menu
21488 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
21489 * Assigning Task IDs::
21490 * Task IDs and Delays::
21491 * Task-Related Pragmas::
21492 * Scheduling and Task Priority::
21493 * The Task Stack::
21494 * External Interrupts::
21495 @end menu
21497 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21498 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21500 @noindent
21501 On OpenVMS Alpha systems, each Ada task (except a passive
21502 task) is implemented as a single stream of execution
21503 that is created and managed by the kernel. On these
21504 systems, HP Ada tasking support is based on DECthreads,
21505 an implementation of the POSIX standard for threads.
21507 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
21508 code that calls DECthreads routines can be used together.
21509 The interaction between Ada tasks and DECthreads routines
21510 can have some benefits. For example when on OpenVMS Alpha,
21511 HP Ada can call C code that is already threaded.
21513 GNAT uses the facilities of DECthreads,
21514 and Ada tasks are mapped to threads.
21516 @node Assigning Task IDs
21517 @subsection Assigning Task IDs
21519 @noindent
21520 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
21521 the environment task that executes the main program. On
21522 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21523 that have been created but are not yet activated.
21525 On OpenVMS Alpha systems, task IDs are assigned at
21526 activation. On GNAT systems, task IDs are also assigned at
21527 task creation but do not have the same form or values as
21528 task ID values in HP Ada. There is no null task, and the
21529 environment task does not have a specific task ID value.
21531 @node Task IDs and Delays
21532 @subsection Task IDs and Delays
21534 @noindent
21535 On OpenVMS Alpha systems, tasking delays are implemented
21536 using Timer System Services. The Task ID is used for the
21537 identification of the timer request (the @code{REQIDT} parameter).
21538 If Timers are used in the application take care not to use
21539 @code{0} for the identification, because cancelling such a timer
21540 will cancel all timers and may lead to unpredictable results.
21542 @node Task-Related Pragmas
21543 @subsection Task-Related Pragmas
21545 @noindent
21546 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21547 specification of the size of the guard area for a task
21548 stack. (The guard area forms an area of memory that has no
21549 read or write access and thus helps in the detection of
21550 stack overflow.) On OpenVMS Alpha systems, if the pragma
21551 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21552 area is created. In the absence of a pragma @code{TASK_STORAGE},
21553 a default guard area is created.
21555 GNAT supplies the following task-related pragmas:
21557 @itemize @bullet
21558 @item  @code{TASK_INFO}
21560 This pragma appears within a task definition and
21561 applies to the task in which it appears. The argument
21562 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21564 @item  @code{TASK_STORAGE}
21566 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
21567 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21568 @code{SUPPRESS}, and @code{VOLATILE}.
21569 @end itemize
21570 @node Scheduling and Task Priority
21571 @subsection Scheduling and Task Priority
21573 @noindent
21574 HP Ada implements the Ada language requirement that
21575 when two tasks are eligible for execution and they have
21576 different priorities, the lower priority task does not
21577 execute while the higher priority task is waiting. The HP
21578 Ada Run-Time Library keeps a task running until either the
21579 task is suspended or a higher priority task becomes ready.
21581 On OpenVMS Alpha systems, the default strategy is round-
21582 robin with preemption. Tasks of equal priority take turns
21583 at the processor. A task is run for a certain period of
21584 time and then placed at the tail of the ready queue for
21585 its priority level.
21587 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21588 which can be used to enable or disable round-robin
21589 scheduling of tasks with the same priority.
21590 See the relevant HP Ada run-time reference manual for
21591 information on using the pragmas to control HP Ada task
21592 scheduling.
21594 GNAT follows the scheduling rules of Annex D (Real-Time
21595 Annex) of the @cite{Ada Reference Manual}. In general, this
21596 scheduling strategy is fully compatible with HP Ada
21597 although it provides some additional constraints (as
21598 fully documented in Annex D).
21599 GNAT implements time slicing control in a manner compatible with
21600 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21601 are identical to the HP Ada 83 pragma of the same name.
21602 Note that it is not possible to mix GNAT tasking and
21603 HP Ada 83 tasking in the same program, since the two run-time
21604 libraries are not compatible.
21606 @node The Task Stack
21607 @subsection The Task Stack
21609 @noindent
21610 In HP Ada, a task stack is allocated each time a
21611 non-passive task is activated. As soon as the task is
21612 terminated, the storage for the task stack is deallocated.
21613 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21614 a default stack size is used. Also, regardless of the size
21615 specified, some additional space is allocated for task
21616 management purposes. On OpenVMS Alpha systems, at least
21617 one page is allocated.
21619 GNAT handles task stacks in a similar manner. In accordance with
21620 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
21621 an alternative method for controlling the task stack size.
21622 The specification of the attribute @code{T'STORAGE_SIZE} is also
21623 supported in a manner compatible with HP Ada.
21625 @node External Interrupts
21626 @subsection External Interrupts
21628 @noindent
21629 On HP Ada, external interrupts can be associated with task entries.
21630 GNAT is compatible with HP Ada in its handling of external interrupts.
21632 @node Pragmas and Pragma-Related Features
21633 @section Pragmas and Pragma-Related Features
21635 @noindent
21636 Both HP Ada and GNAT supply all language-defined pragmas
21637 as specified by the Ada 83 standard. GNAT also supplies all
21638 language-defined pragmas introduced by Ada 95 and Ada 2005.
21639 In addition, GNAT implements the implementation-defined pragmas
21640 from HP Ada 83.
21642 @itemize @bullet
21643 @item  @code{AST_ENTRY}
21645 @item  @code{COMMON_OBJECT}
21647 @item  @code{COMPONENT_ALIGNMENT}
21649 @item  @code{EXPORT_EXCEPTION}
21651 @item  @code{EXPORT_FUNCTION}
21653 @item  @code{EXPORT_OBJECT}
21655 @item  @code{EXPORT_PROCEDURE}
21657 @item  @code{EXPORT_VALUED_PROCEDURE}
21659 @item  @code{FLOAT_REPRESENTATION}
21661 @item  @code{IDENT}
21663 @item  @code{IMPORT_EXCEPTION}
21665 @item  @code{IMPORT_FUNCTION}
21667 @item  @code{IMPORT_OBJECT}
21669 @item  @code{IMPORT_PROCEDURE}
21671 @item  @code{IMPORT_VALUED_PROCEDURE}
21673 @item  @code{INLINE_GENERIC}
21675 @item  @code{INTERFACE_NAME}
21677 @item  @code{LONG_FLOAT}
21679 @item  @code{MAIN_STORAGE}
21681 @item  @code{PASSIVE}
21683 @item  @code{PSECT_OBJECT}
21685 @item  @code{SHARE_GENERIC}
21687 @item  @code{SUPPRESS_ALL}
21689 @item  @code{TASK_STORAGE}
21691 @item  @code{TIME_SLICE}
21693 @item  @code{TITLE}
21694 @end itemize
21696 @noindent
21697 These pragmas are all fully implemented, with the exception of @code{TITLE},
21698 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21699 recognized, but which have no
21700 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21701 use of Ada protected objects. In GNAT, all generics are inlined.
21703 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21704 a separate subprogram specification which must appear before the
21705 subprogram body.
21707 GNAT also supplies a number of implementation-defined pragmas including the
21708 following:
21710 @itemize @bullet
21711 @item  @code{ABORT_DEFER}
21713 @item  @code{ADA_83}
21715 @item  @code{ADA_95}
21717 @item  @code{ADA_05}
21719 @item  @code{Ada_2005}
21721 @item  @code{Ada_12}
21723 @item  @code{Ada_2012}
21725 @item  @code{ANNOTATE}
21727 @item  @code{ASSERT}
21729 @item  @code{C_PASS_BY_COPY}
21731 @item  @code{CPP_CLASS}
21733 @item  @code{CPP_CONSTRUCTOR}
21735 @item  @code{CPP_DESTRUCTOR}
21737 @item  @code{DEBUG}
21739 @item  @code{EXTEND_SYSTEM}
21741 @item  @code{LINKER_ALIAS}
21743 @item  @code{LINKER_SECTION}
21745 @item  @code{MACHINE_ATTRIBUTE}
21747 @item  @code{NO_RETURN}
21749 @item  @code{PURE_FUNCTION}
21751 @item  @code{SOURCE_FILE_NAME}
21753 @item  @code{SOURCE_REFERENCE}
21755 @item  @code{TASK_INFO}
21757 @item  @code{UNCHECKED_UNION}
21759 @item  @code{UNIMPLEMENTED_UNIT}
21761 @item  @code{UNIVERSAL_DATA}
21763 @item  @code{UNSUPPRESS}
21765 @item  @code{WARNINGS}
21767 @item  @code{WEAK_EXTERNAL}
21768 @end itemize
21770 @noindent
21771 For full details on these and other GNAT implementation-defined pragmas,
21772 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21773 Manual}.
21775 @menu
21776 * Restrictions on the Pragma INLINE::
21777 * Restrictions on the Pragma INTERFACE::
21778 * Restrictions on the Pragma SYSTEM_NAME::
21779 @end menu
21781 @node Restrictions on the Pragma INLINE
21782 @subsection Restrictions on Pragma @code{INLINE}
21784 @noindent
21785 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21786 @itemize @bullet
21787 @item  Parameters cannot have a task type.
21789 @item  Function results cannot be task types, unconstrained
21790 array types, or unconstrained types with discriminants.
21792 @item  Bodies cannot declare the following:
21793 @itemize @bullet
21794 @item  Subprogram body or stub (imported subprogram is allowed)
21796 @item  Tasks
21798 @item  Generic declarations
21800 @item  Instantiations
21802 @item  Exceptions
21804 @item  Access types (types derived from access types allowed)
21806 @item  Array or record types
21808 @item  Dependent tasks
21810 @item  Direct recursive calls of subprogram or containing
21811 subprogram, directly or via a renaming
21813 @end itemize
21814 @end itemize
21816 @noindent
21817 In GNAT, the only restriction on pragma @code{INLINE} is that the
21818 body must occur before the call if both are in the same
21819 unit, and the size must be appropriately small. There are
21820 no other specific restrictions which cause subprograms to
21821 be incapable of being inlined.
21823 @node  Restrictions on the Pragma INTERFACE
21824 @subsection  Restrictions on Pragma @code{INTERFACE}
21826 @noindent
21827 The following restrictions on pragma @code{INTERFACE}
21828 are enforced by both HP Ada and GNAT:
21829 @itemize @bullet
21830 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21831 Default is the default on OpenVMS Alpha systems.
21833 @item  Parameter passing: Language specifies default
21834 mechanisms but can be overridden with an @code{EXPORT} pragma.
21836 @itemize @bullet
21837 @item  Ada: Use internal Ada rules.
21839 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21840 record or task type. Result cannot be a string, an
21841 array, or a record.
21843 @item  Fortran: Parameters cannot have a task type. Result cannot
21844 be a string, an array, or a record.
21845 @end itemize
21846 @end itemize
21848 @noindent
21849 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21850 record parameters for all languages.
21852 @node  Restrictions on the Pragma SYSTEM_NAME
21853 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21855 @noindent
21856 For HP Ada for OpenVMS Alpha, the enumeration literal
21857 for the type @code{NAME} is @code{OPENVMS_AXP}.
21858 In GNAT, the enumeration
21859 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21861 @node  Library of Predefined Units
21862 @section  Library of Predefined Units
21864 @noindent
21865 A library of predefined units is provided as part of the
21866 HP Ada and GNAT implementations. HP Ada does not provide
21867 the package @code{MACHINE_CODE} but instead recommends importing
21868 assembler code.
21870 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21871 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21872 version.
21873 The HP Ada Predefined Library units are modified to remove post-Ada 83
21874 incompatibilities and to make them interoperable with GNAT
21875 (@pxref{Changes to DECLIB}, for details).
21876 The units are located in the @file{DECLIB} directory.
21878 The GNAT RTL is contained in
21879 the @file{ADALIB} directory, and
21880 the default search path is set up to find @code{DECLIB} units in preference
21881 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21882 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21884 @menu
21885 * Changes to DECLIB::
21886 @end menu
21888 @node Changes to DECLIB
21889 @subsection Changes to @code{DECLIB}
21891 @noindent
21892 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21893 compatibility are minor and include the following:
21895 @itemize @bullet
21896 @item  Adjusting the location of pragmas and record representation
21897 clauses to obey Ada 95 (and thus Ada 2005) rules
21899 @item  Adding the proper notation to generic formal parameters
21900 that take unconstrained types in instantiation
21902 @item  Adding pragma @code{ELABORATE_BODY} to package specs
21903 that have package bodies not otherwise allowed
21905 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21906 ``@code{PROTECTD}''.
21907 Currently these are found only in the @code{STARLET} package spec.
21909 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21910 where the address size is constrained to 32 bits.
21911 @end itemize
21913 @noindent
21914 None of the above changes is visible to users.
21916 @node Bindings
21917 @section Bindings
21919 @noindent
21920 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21921 @itemize @bullet
21923 @item  Command Language Interpreter (CLI interface)
21925 @item  DECtalk Run-Time Library (DTK interface)
21927 @item  Librarian utility routines (LBR interface)
21929 @item  General Purpose Run-Time Library (LIB interface)
21931 @item  Math Run-Time Library (MTH interface)
21933 @item  National Character Set Run-Time Library (NCS interface)
21935 @item  Compiled Code Support Run-Time Library (OTS interface)
21937 @item  Parallel Processing Run-Time Library (PPL interface)
21939 @item  Screen Management Run-Time Library (SMG interface)
21941 @item  Sort Run-Time Library (SOR interface)
21943 @item  String Run-Time Library (STR interface)
21945 @item STARLET System Library
21946 @findex Starlet
21948 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21950 @item  X Windows Toolkit (XT interface)
21952 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21953 @end itemize
21955 @noindent
21956 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21957 directory, on both the Alpha and I64 OpenVMS platforms.
21959 The X components of DECLIB compatibility package are located in a separate
21960 library, called XDECGNAT, which is not linked with by default; this library
21961 must be explicitly linked with any application that makes use of any X facilities,
21962 with a command similar to
21964 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21966 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21967 in the
21968 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21969 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21970 @code{Xt}, and @code{X_Lib}
21971 causing the default X/Motif sharable image libraries to be linked in. This
21972 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21973 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21975 It may be necessary to edit these options files to update or correct the
21976 library names if, for example, the newer X/Motif bindings from
21977 @file{ADA$EXAMPLES}
21978 had been (previous to installing GNAT) copied and renamed to supersede the
21979 default @file{ADA$PREDEFINED} versions.
21981 @menu
21982 * Shared Libraries and Options Files::
21983 * Interfaces to C::
21984 @end menu
21986 @node Shared Libraries and Options Files
21987 @subsection Shared Libraries and Options Files
21989 @noindent
21990 When using the HP Ada
21991 predefined X and Motif bindings, the linking with their sharable images is
21992 done automatically by @command{GNAT LINK}.
21993 When using other X and Motif bindings, you need
21994 to add the corresponding sharable images to the command line for
21995 @code{GNAT LINK}. When linking with shared libraries, or with
21996 @file{.OPT} files, you must
21997 also add them to the command line for @command{GNAT LINK}.
21999 A shared library to be used with GNAT is built in the same way as other
22000 libraries under VMS. The VMS Link command can be used in standard fashion.
22002 @node Interfaces to C
22003 @subsection Interfaces to C
22005 @noindent
22006 HP Ada
22007 provides the following Ada types and operations:
22009 @itemize @bullet
22010 @item C types package (@code{C_TYPES})
22012 @item C strings (@code{C_TYPES.NULL_TERMINATED})
22014 @item Other_types (@code{SHORT_INT})
22015 @end itemize
22017 @noindent
22018 Interfacing to C with GNAT, you can use the above approach
22019 described for HP Ada or the facilities of Annex B of
22020 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
22021 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22022 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
22024 The @option{-gnatF} qualifier forces default and explicit
22025 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22026 to be uppercased for compatibility with the default behavior
22027 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22029 @node Main Program Definition
22030 @section Main Program Definition
22032 @noindent
22033 The following section discusses differences in the
22034 definition of main programs on HP Ada and GNAT.
22035 On HP Ada, main programs are defined to meet the
22036 following conditions:
22037 @itemize @bullet
22038 @item  Procedure with no formal parameters (returns @code{0} upon
22039 normal completion)
22041 @item  Procedure with no formal parameters (returns @code{42} when
22042 an unhandled exception is raised)
22044 @item  Function with no formal parameters whose returned value
22045 is of a discrete type
22047 @item  Procedure with one @code{out} formal of a discrete type for
22048 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
22050 @end itemize
22052 @noindent
22053 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22054 a main function or main procedure returns a discrete
22055 value whose size is less than 64 bits (32 on VAX systems),
22056 the value is zero- or sign-extended as appropriate.
22057 On GNAT, main programs are defined as follows:
22058 @itemize @bullet
22059 @item  Must be a non-generic, parameterless subprogram that
22060 is either a procedure or function returning an Ada
22061 @code{STANDARD.INTEGER} (the predefined type)
22063 @item  Cannot be a generic subprogram or an instantiation of a
22064 generic subprogram
22065 @end itemize
22067 @node Implementation-Defined Attributes
22068 @section Implementation-Defined Attributes
22070 @noindent
22071 GNAT provides all HP Ada implementation-defined
22072 attributes.
22074 @node Compiler and Run-Time Interfacing
22075 @section Compiler and Run-Time Interfacing
22077 @noindent
22078 HP Ada provides the following qualifiers to pass options to the linker
22079 (ACS LINK):
22080 @itemize @bullet
22081 @item  @option{/WAIT} and @option{/SUBMIT}
22083 @item  @option{/COMMAND}
22085 @item  @option{/@r{[}NO@r{]}MAP}
22087 @item  @option{/OUTPUT=@var{file-spec}}
22089 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22090 @end itemize
22092 @noindent
22093 To pass options to the linker, GNAT provides the following
22094 switches:
22096 @itemize @bullet
22097 @item   @option{/EXECUTABLE=@var{exec-name}}
22099 @item   @option{/VERBOSE}
22101 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22102 @end itemize
22104 @noindent
22105 For more information on these switches, see
22106 @ref{Switches for gnatlink}.
22107 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
22108 to control optimization. HP Ada also supplies the
22109 following pragmas:
22110 @itemize @bullet
22111 @item  @code{OPTIMIZE}
22113 @item  @code{INLINE}
22115 @item  @code{INLINE_GENERIC}
22117 @item  @code{SUPPRESS_ALL}
22119 @item  @code{PASSIVE}
22120 @end itemize
22122 @noindent
22123 In GNAT, optimization is controlled strictly by command
22124 line parameters, as described in the corresponding section of this guide.
22125 The HP pragmas for control of optimization are
22126 recognized but ignored.
22128 Note that in GNAT, the default is optimization off, whereas in HP Ada
22129 the default is that optimization is turned on.
22131 @node Program Compilation and Library Management
22132 @section Program Compilation and Library Management
22134 @noindent
22135 HP Ada and GNAT provide a comparable set of commands to
22136 build programs. HP Ada also provides a program library,
22137 which is a concept that does not exist on GNAT. Instead,
22138 GNAT provides directories of sources that are compiled as
22139 needed.
22141 The following table summarizes
22142 the HP Ada commands and provides
22143 equivalent GNAT commands. In this table, some GNAT
22144 equivalents reflect the fact that GNAT does not use the
22145 concept of a program library. Instead, it uses a model
22146 in which collections of source and object files are used
22147 in a manner consistent with other languages like C and
22148 Fortran. Therefore, standard system file commands are used
22149 to manipulate these elements. Those GNAT commands are marked with
22150 an asterisk.
22151 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
22153 @need 1500
22154 @multitable @columnfractions .35 .65
22156 @item @emph{HP Ada Command}
22157 @tab @emph{GNAT Equivalent / Description}
22159 @item @command{ADA}
22160 @tab @command{GNAT COMPILE}@*
22161 Invokes the compiler to compile one or more Ada source files.
22163 @item @command{ACS ATTACH}@*
22164 @tab [No equivalent]@*
22165 Switches control of terminal from current process running the program
22166 library manager.
22168 @item @command{ACS CHECK}
22169 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
22170 Forms the execution closure of one
22171 or more compiled units and checks completeness and currency.
22173 @item @command{ACS COMPILE}
22174 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22175 Forms the execution closure of one or
22176 more specified units, checks completeness and currency,
22177 identifies units that have revised source files, compiles same,
22178 and recompiles units that are or will become obsolete.
22179 Also completes incomplete generic instantiations.
22181 @item @command{ACS COPY FOREIGN}
22182 @tab Copy (*)@*
22183 Copies a foreign object file into the program library as a
22184 library unit body.
22186 @item @command{ACS COPY UNIT}
22187 @tab Copy (*)@*
22188 Copies a compiled unit from one program library to another.
22190 @item @command{ACS CREATE LIBRARY}
22191 @tab Create /directory (*)@*
22192 Creates a program library.
22194 @item @command{ACS CREATE SUBLIBRARY}
22195 @tab Create /directory (*)@*
22196 Creates a program sublibrary.
22198 @item @command{ACS DELETE LIBRARY}
22199 @tab @*
22200 Deletes a program library and its contents.
22202 @item @command{ACS DELETE SUBLIBRARY}
22203 @tab @*
22204 Deletes a program sublibrary and its contents.
22206 @item @command{ACS DELETE UNIT}
22207 @tab Delete file (*)@*
22208 On OpenVMS systems, deletes one or more compiled units from
22209 the current program library.
22211 @item @command{ACS DIRECTORY}
22212 @tab Directory (*)@*
22213 On OpenVMS systems, lists units contained in the current
22214 program library.
22216 @item @command{ACS ENTER FOREIGN}
22217 @tab Copy (*)@*
22218 Allows the import of a foreign body as an Ada library
22219 spec and enters a reference to a pointer.
22221 @item @command{ACS ENTER UNIT}
22222 @tab Copy (*)@*
22223 Enters a reference (pointer) from the current program library to
22224 a unit compiled into another program library.
22226 @item @command{ACS EXIT}
22227 @tab [No equivalent]@*
22228 Exits from the program library manager.
22230 @item @command{ACS EXPORT}
22231 @tab Copy (*)@*
22232 Creates an object file that contains system-specific object code
22233 for one or more units. With GNAT, object files can simply be copied
22234 into the desired directory.
22236 @item @command{ACS EXTRACT SOURCE}
22237 @tab Copy (*)@*
22238 Allows access to the copied source file for each Ada compilation unit
22240 @item @command{ACS HELP}
22241 @tab @command{HELP GNAT}@*
22242 Provides online help.
22244 @item @command{ACS LINK}
22245 @tab @command{GNAT LINK}@*
22246 Links an object file containing Ada units into an executable file.
22248 @item @command{ACS LOAD}
22249 @tab Copy (*)@*
22250 Loads (partially compiles) Ada units into the program library.
22251 Allows loading a program from a collection of files into a library
22252 without knowing the relationship among units.
22254 @item @command{ACS MERGE}
22255 @tab Copy (*)@*
22256 Merges into the current program library, one or more units from
22257 another library where they were modified.
22259 @item @command{ACS RECOMPILE}
22260 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22261 Recompiles from   external or copied source files any obsolete
22262 unit in the closure. Also, completes any incomplete generic
22263 instantiations.
22265 @item @command{ACS REENTER}
22266 @tab @command{GNAT MAKE}@*
22267 Reenters current references to units compiled after last entered
22268 with the @command{ACS ENTER UNIT} command.
22270 @item @command{ACS SET LIBRARY}
22271 @tab Set default (*)@*
22272 Defines a program library to be the compilation context as well
22273 as the target library for compiler output and commands in general.
22275 @item @command{ACS SET PRAGMA}
22276 @tab Edit @file{gnat.adc} (*)@*
22277 Redefines specified  values of the library characteristics
22278 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
22279 and @code{Float_Representation}.
22281 @item @command{ACS SET SOURCE}
22282 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
22283 Defines the source file search list for the @command{ACS COMPILE} command.
22285 @item @command{ACS SHOW LIBRARY}
22286 @tab Directory (*)@*
22287 Lists information about one or more program libraries.
22289 @item @command{ACS SHOW PROGRAM}
22290 @tab [No equivalent]@*
22291 Lists information about the execution closure of one or
22292 more units in the program library.
22294 @item @command{ACS SHOW SOURCE}
22295 @tab Show logical @code{ADA_INCLUDE_PATH}@*
22296 Shows the source file search used when compiling units.
22298 @item @command{ACS SHOW VERSION}
22299 @tab Compile with @option{VERBOSE} option
22300 Displays the version number of the compiler and program library
22301 manager used.
22303 @item @command{ACS SPAWN}
22304 @tab [No equivalent]@*
22305 Creates a subprocess of the current process (same as @command{DCL SPAWN}
22306 command).
22308 @item @command{ACS VERIFY}
22309 @tab [No equivalent]@*
22310 Performs a series of consistency checks on a program library to
22311 determine whether the library structure and library files are in
22312 valid form.
22313 @end multitable
22315 @noindent
22317 @node Input-Output
22318 @section Input-Output
22320 @noindent
22321 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22322 Management Services (RMS) to perform operations on
22323 external files.
22325 @noindent
22326 HP Ada and GNAT predefine an identical set of input-
22327 output packages. To make the use of the
22328 generic @code{TEXT_IO} operations more convenient, HP Ada
22329 provides predefined library packages that instantiate the
22330 integer and floating-point operations for the predefined
22331 integer and floating-point types as shown in the following table.
22333 @multitable @columnfractions .45 .55
22334 @item @emph{Package Name} @tab Instantiation
22336 @item @code{INTEGER_TEXT_IO}
22337 @tab @code{INTEGER_IO(INTEGER)}
22339 @item @code{SHORT_INTEGER_TEXT_IO}
22340 @tab @code{INTEGER_IO(SHORT_INTEGER)}
22342 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
22343 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
22345 @item @code{FLOAT_TEXT_IO}
22346 @tab @code{FLOAT_IO(FLOAT)}
22348 @item @code{LONG_FLOAT_TEXT_IO}
22349 @tab @code{FLOAT_IO(LONG_FLOAT)}
22350 @end multitable
22352 @noindent
22353 The HP Ada predefined packages and their operations
22354 are implemented using OpenVMS Alpha files and input-output
22355 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
22356 Familiarity with the following is recommended:
22357 @itemize @bullet
22358 @item  RMS file organizations and access methods
22360 @item  OpenVMS file specifications and directories
22362 @item  OpenVMS File Definition Language (FDL)
22363 @end itemize
22365 @noindent
22366 GNAT provides I/O facilities that are completely
22367 compatible with HP Ada. The distribution includes the
22368 standard HP Ada versions of all I/O packages, operating
22369 in a manner compatible with HP Ada. In particular, the
22370 following packages are by default the HP Ada (Ada 83)
22371 versions of these packages rather than the renamings
22372 suggested in Annex J of the Ada Reference Manual:
22373 @itemize @bullet
22374 @item  @code{TEXT_IO}
22376 @item  @code{SEQUENTIAL_IO}
22378 @item  @code{DIRECT_IO}
22379 @end itemize
22381 @noindent
22382 The use of the standard child package syntax (for
22383 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
22384 packages.
22385 GNAT provides HP-compatible predefined instantiations
22386 of the @code{TEXT_IO} packages, and also
22387 provides the standard predefined instantiations required
22388 by the @cite{Ada Reference Manual}.
22390 For further information on how GNAT interfaces to the file
22391 system or how I/O is implemented in programs written in
22392 mixed languages, see @ref{Implementation of the Standard I/O,,,
22393 gnat_rm, GNAT Reference Manual}.
22394 This chapter covers the following:
22395 @itemize @bullet
22396 @item  Standard I/O packages
22398 @item  @code{FORM} strings
22400 @item  @code{ADA.DIRECT_IO}
22402 @item  @code{ADA.SEQUENTIAL_IO}
22404 @item  @code{ADA.TEXT_IO}
22406 @item  Stream pointer positioning
22408 @item  Reading and writing non-regular files
22410 @item  @code{GET_IMMEDIATE}
22412 @item  Treating @code{TEXT_IO} files as streams
22414 @item  Shared files
22416 @item  Open modes
22417 @end itemize
22419 @node Implementation Limits
22420 @section Implementation Limits
22422 @noindent
22423 The following table lists implementation limits for HP Ada
22424 and GNAT systems.
22425 @multitable @columnfractions .60 .20 .20
22426 @sp 1
22427 @item  @emph{Compilation Parameter}
22428 @tab   @emph{HP Ada}
22429 @tab   @emph{GNAT}
22430 @sp 1
22432 @item  In a subprogram or entry  declaration, maximum number of
22433 formal parameters that are of an unconstrained record type
22434 @tab   32
22435 @tab   No set limit
22436 @sp 1
22438 @item  Maximum identifier length (number of characters)
22439 @tab   255
22440 @tab   32766
22441 @sp 1
22443 @item  Maximum number of characters in a source line
22444 @tab   255
22445 @tab   32766
22446 @sp 1
22448 @item  Maximum collection size   (number of bytes)
22449 @tab   2**31-1
22450 @tab   2**31-1
22451 @sp 1
22453 @item  Maximum number of discriminants for a record type
22454 @tab   245
22455 @tab   No set limit
22456 @sp 1
22458 @item  Maximum number of formal parameters in an entry or
22459 subprogram declaration
22460 @tab   246
22461 @tab    No set limit
22462 @sp 1
22464 @item  Maximum number of dimensions in an array type
22465 @tab   255
22466 @tab   No set limit
22467 @sp 1
22469 @item  Maximum number of library  units and subunits in a compilation.
22470 @tab   4095
22471 @tab   No set limit
22472 @sp 1
22474 @item  Maximum number of library units and subunits in an execution.
22475 @tab   16383
22476 @tab   No set limit
22477 @sp 1
22479 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22480 or @code{PSECT_OBJECT}
22481 @tab   32757
22482 @tab   No set limit
22483 @sp 1
22485 @item  Maximum number of enumeration literals in an enumeration type
22486 definition
22487 @tab   65535
22488 @tab   No set limit
22489 @sp 1
22491 @item  Maximum number of lines in a source file
22492 @tab   65534
22493 @tab   No set limit
22494 @sp 1
22496 @item  Maximum number of bits in any object
22497 @tab   2**31-1
22498 @tab   2**31-1
22499 @sp 1
22501 @item  Maximum size of the static portion of a stack frame (approximate)
22502 @tab   2**31-1
22503 @tab   2**31-1
22504 @end multitable
22506 @node Tools and Utilities
22507 @section Tools and Utilities
22509 @noindent
22510 The following table lists some of the OpenVMS development tools
22511 available for HP Ada, and the corresponding tools for
22512 use with @value{EDITION} on Alpha and I64 platforms.
22513 Aside from the debugger, all the OpenVMS tools identified are part
22514 of the DECset package.
22516 @iftex
22517 @c Specify table in TeX since Texinfo does a poor job
22518 @tex
22519 \smallskip
22520 \smallskip
22521 \settabs\+Language-Sensitive Editor\quad
22522    &Product with HP Ada\quad
22523    &\cr
22524 \+\it Tool
22525    &\it Product with HP Ada
22526    & \it Product with @value{EDITION}\cr
22527 \smallskip
22528 \+Code Management System
22529    &HP CMS
22530    & HP CMS\cr
22531 \smallskip
22532 \+Language-Sensitive Editor
22533    &HP LSE
22534    & emacs or HP LSE (Alpha)\cr
22536    &
22537    & HP LSE (I64)\cr
22538 \smallskip
22539 \+Debugger
22540    &OpenVMS Debug
22541    & gdb (Alpha),\cr
22543    &
22544    & OpenVMS Debug (I64)\cr
22545 \smallskip
22546 \+Source Code Analyzer /
22547    &HP SCA
22548    & GNAT XREF\cr
22549 \+Cross Referencer
22550    &
22551    &\cr
22552 \smallskip
22553 \+Test Manager
22554    &HP Digital Test
22555    & HP DTM\cr
22557    &Manager (DTM)
22558    &\cr
22559 \smallskip
22560 \+Performance and
22561    & HP PCA
22562    & HP PCA\cr
22563 \+Coverage Analyzer
22564    &
22565    &\cr
22566 \smallskip
22567 \+Module Management
22568    & HP MMS
22569    & Not applicable\cr
22570 \+ System
22571    &
22572    &\cr
22573 \smallskip
22574 \smallskip
22575 @end tex
22576 @end iftex
22578 @ifnottex
22579 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
22580 @c the TeX version above for the printed version
22581 @flushleft
22582 @c @multitable @columnfractions .3 .4 .4
22583 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22584 @item @i{Tool}
22585 @tab @i{Tool with HP Ada}
22586 @tab @i{Tool with @value{EDITION}}
22587 @item Code Management@*System
22588 @tab HP CMS
22589 @tab HP CMS
22590 @item Language-Sensitive@*Editor
22591 @tab HP LSE
22592 @tab emacs or HP LSE (Alpha)
22593 @item
22594 @tab
22595 @tab HP LSE (I64)
22596 @item Debugger
22597 @tab OpenVMS Debug
22598 @tab gdb (Alpha),
22599 @item
22600 @tab
22601 @tab OpenVMS Debug (I64)
22602 @item Source Code Analyzer /@*Cross Referencer
22603 @tab HP SCA
22604 @tab GNAT XREF
22605 @item Test Manager
22606 @tab HP Digital Test@*Manager (DTM)
22607 @tab HP DTM
22608 @item Performance and@*Coverage Analyzer
22609 @tab HP PCA
22610 @tab HP PCA
22611 @item Module Management@*System
22612 @tab HP MMS
22613 @tab Not applicable
22614 @end multitable
22615 @end flushleft
22616 @end ifnottex
22618 @end ifset
22620 @c **************************************
22621 @node Platform-Specific Information for the Run-Time Libraries
22622 @appendix Platform-Specific Information for the Run-Time Libraries
22623 @cindex Tasking and threads libraries
22624 @cindex Threads libraries and tasking
22625 @cindex Run-time libraries (platform-specific information)
22627 @noindent
22628 The GNAT run-time implementation may vary with respect to both the
22629 underlying threads library and the exception handling scheme.
22630 For threads support, one or more of the following are supplied:
22631 @itemize @bullet
22632 @item @b{native threads library}, a binding to the thread package from
22633 the underlying operating system
22635 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22636 POSIX thread package
22637 @end itemize
22639 @noindent
22640 For exception handling, either or both of two models are supplied:
22641 @itemize @bullet
22642 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22643 Most programs should experience a substantial speed improvement by
22644 being compiled with a ZCX run-time.
22645 This is especially true for
22646 tasking applications or applications with many exception handlers.}
22647 @cindex Zero-Cost Exceptions
22648 @cindex ZCX (Zero-Cost Exceptions)
22649 which uses binder-generated tables that
22650 are interrogated at run time to locate a handler
22652 @item @b{setjmp / longjmp} (``SJLJ''),
22653 @cindex setjmp/longjmp Exception Model
22654 @cindex SJLJ (setjmp/longjmp Exception Model)
22655 which uses dynamically-set data to establish
22656 the set of handlers
22657 @end itemize
22659 @noindent
22660 This appendix summarizes which combinations of threads and exception support
22661 are supplied on various GNAT platforms.
22662 It then shows how to select a particular library either
22663 permanently or temporarily,
22664 explains the properties of (and tradeoffs among) the various threads
22665 libraries, and provides some additional
22666 information about several specific platforms.
22668 @menu
22669 * Summary of Run-Time Configurations::
22670 * Specifying a Run-Time Library::
22671 * Choosing the Scheduling Policy::
22672 * Solaris-Specific Considerations::
22673 * Linux-Specific Considerations::
22674 * AIX-Specific Considerations::
22675 * RTX-Specific Considerations::
22676 * HP-UX-Specific Considerations::
22677 @end menu
22679 @node Summary of Run-Time Configurations
22680 @section Summary of Run-Time Configurations
22682 @multitable @columnfractions .30 .70
22683 @item @b{alpha-openvms}
22684 @item @code{@ @ }@i{rts-native (default)}
22685 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22686 @item @code{@ @ @ @ }Exceptions @tab ZCX
22688 @item @code{@ @ }@i{rts-sjlj}
22689 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22690 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22692 @item @b{ia64-hp_linux}
22693 @item @code{@ @ }@i{rts-native (default)}
22694 @item @code{@ @ @ @ }Tasking    @tab pthread library
22695 @item @code{@ @ @ @ }Exceptions @tab ZCX
22697 @item @b{ia64-hpux}
22698 @item @code{@ @ }@i{rts-native (default)}
22699 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22700 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22702 @item @b{ia64-openvms}
22703 @item @code{@ @ }@i{rts-native (default)}
22704 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22705 @item @code{@ @ @ @ }Exceptions @tab ZCX
22707 @item @b{ia64-sgi_linux}
22708 @item @code{@ @ }@i{rts-native (default)}
22709 @item @code{@ @ @ @ }Tasking    @tab pthread library
22710 @item @code{@ @ @ @ }Exceptions @tab ZCX
22712 @item @b{pa-hpux}
22713 @item @code{@ @ }@i{rts-native (default)}
22714 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22715 @item @code{@ @ @ @ }Exceptions @tab ZCX
22717 @item @code{@ @ }@i{rts-sjlj}
22718 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22719 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22721 @item @b{ppc-aix}
22722 @item @code{@ @ }@i{rts-native (default)}
22723 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22724 @item @code{@ @ @ @ }Exceptions @tab ZCX
22726 @item @code{@ @ }@i{rts-sjlj}
22727 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22728 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22730 @item @b{ppc-darwin}
22731 @item @code{@ @ }@i{rts-native (default)}
22732 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22733 @item @code{@ @ @ @ }Exceptions @tab ZCX
22735 @item @b{sparc-solaris}  @tab
22736 @item @code{@ @ }@i{rts-native (default)}
22737 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22738 @item @code{@ @ @ @ }Exceptions @tab ZCX
22740 @item @code{@ @ }@i{rts-pthread}
22741 @item @code{@ @ @ @ }Tasking    @tab pthread library
22742 @item @code{@ @ @ @ }Exceptions @tab ZCX
22744 @item @code{@ @ }@i{rts-sjlj}
22745 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22746 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22748 @item @b{sparc64-solaris}  @tab
22749 @item @code{@ @ }@i{rts-native (default)}
22750 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22751 @item @code{@ @ @ @ }Exceptions @tab ZCX
22753 @item @b{x86-linux}
22754 @item @code{@ @ }@i{rts-native (default)}
22755 @item @code{@ @ @ @ }Tasking    @tab pthread library
22756 @item @code{@ @ @ @ }Exceptions @tab ZCX
22758 @item @code{@ @ }@i{rts-sjlj}
22759 @item @code{@ @ @ @ }Tasking    @tab pthread library
22760 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22762 @item @b{x86-lynx}
22763 @item @code{@ @ }@i{rts-native (default)}
22764 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22765 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22767 @item @b{x86-solaris}
22768 @item @code{@ @ }@i{rts-native (default)}
22769 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22770 @item @code{@ @ @ @ }Exceptions @tab ZCX
22772 @item @code{@ @ }@i{rts-sjlj}
22773 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22774 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22776 @item @b{x86-windows}
22777 @item @code{@ @ }@i{rts-native (default)}
22778 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22779 @item @code{@ @ @ @ }Exceptions @tab ZCX
22781 @item @code{@ @ }@i{rts-sjlj}
22782 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22783 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22785 @item @b{x86-windows-rtx}
22786 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22787 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22788 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22790 @item @code{@ @ }@i{rts-rtx-w32}
22791 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22792 @item @code{@ @ @ @ }Exceptions @tab ZCX
22794 @item @b{x86_64-linux}
22795 @item @code{@ @ }@i{rts-native (default)}
22796 @item @code{@ @ @ @ }Tasking    @tab pthread library
22797 @item @code{@ @ @ @ }Exceptions @tab ZCX
22799 @item @code{@ @ }@i{rts-sjlj}
22800 @item @code{@ @ @ @ }Tasking    @tab pthread library
22801 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22803 @end multitable
22805 @node Specifying a Run-Time Library
22806 @section Specifying a Run-Time Library
22808 @noindent
22809 The @file{adainclude} subdirectory containing the sources of the GNAT
22810 run-time library, and the @file{adalib} subdirectory containing the
22811 @file{ALI} files and the static and/or shared GNAT library, are located
22812 in the gcc target-dependent area:
22814 @smallexample
22815 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22816 @end smallexample
22818 @noindent
22819 As indicated above, on some platforms several run-time libraries are supplied.
22820 These libraries are installed in the target dependent area and
22821 contain a complete source and binary subdirectory. The detailed description
22822 below explains the differences between the different libraries in terms of
22823 their thread support.
22825 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22826 This default run time is selected by the means of soft links.
22827 For example on x86-linux:
22829 @smallexample
22830 @group
22831  $(target-dir)
22832      |
22833      +--- adainclude----------+
22834      |                        |
22835      +--- adalib-----------+  |
22836      |                     |  |
22837      +--- rts-native       |  |
22838      |    |                |  |
22839      |    +--- adainclude <---+
22840      |    |                |
22841      |    +--- adalib <----+
22842      |
22843      +--- rts-sjlj
22844           |
22845           +--- adainclude
22846           |
22847           +--- adalib
22848 @end group
22849 @end smallexample
22851 @noindent
22852 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22853 these soft links can be modified with the following commands:
22855 @smallexample
22856 $ cd $target
22857 $ rm -f adainclude adalib
22858 $ ln -s rts-sjlj/adainclude adainclude
22859 $ ln -s rts-sjlj/adalib adalib
22860 @end smallexample
22862 @noindent
22863 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22864 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22865 @file{$target/ada_object_path}.
22867 Selecting another run-time library temporarily can be
22868 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22869 @cindex @option{--RTS} option
22871 @node Choosing the Scheduling Policy
22872 @section Choosing the Scheduling Policy
22874 @noindent
22875 When using a POSIX threads implementation, you have a choice of several
22876 scheduling policies: @code{SCHED_FIFO},
22877 @cindex @code{SCHED_FIFO} scheduling policy
22878 @code{SCHED_RR}
22879 @cindex @code{SCHED_RR} scheduling policy
22880 and @code{SCHED_OTHER}.
22881 @cindex @code{SCHED_OTHER} scheduling policy
22882 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22883 or @code{SCHED_RR} requires special (e.g., root) privileges.
22885 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22886 @code{SCHED_FIFO},
22887 @cindex @code{SCHED_FIFO} scheduling policy
22888 you can use one of the following:
22890 @itemize @bullet
22891 @item
22892 @code{pragma Time_Slice (0.0)}
22893 @cindex pragma Time_Slice
22894 @item
22895 the corresponding binder option @option{-T0}
22896 @cindex @option{-T0} option
22897 @item
22898 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22899 @cindex pragma Task_Dispatching_Policy
22900 @end itemize
22902 @noindent
22903 To specify @code{SCHED_RR},
22904 @cindex @code{SCHED_RR} scheduling policy
22905 you should use @code{pragma Time_Slice} with a
22906 value greater than @code{0.0}, or else use the corresponding @option{-T}
22907 binder option.
22909 @node Solaris-Specific Considerations
22910 @section Solaris-Specific Considerations
22911 @cindex Solaris Sparc threads libraries
22913 @noindent
22914 This section addresses some topics related to the various threads libraries
22915 on Sparc Solaris.
22917 @menu
22918 * Solaris Threads Issues::
22919 @end menu
22921 @node Solaris Threads Issues
22922 @subsection Solaris Threads Issues
22924 @noindent
22925 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22926 library based on POSIX threads --- @emph{rts-pthread}.
22927 @cindex rts-pthread threads library
22928 This run-time library has the advantage of being mostly shared across all
22929 POSIX-compliant thread implementations, and it also provides under
22930 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22931 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22932 and @code{PTHREAD_PRIO_PROTECT}
22933 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22934 semantics that can be selected using the predefined pragma
22935 @code{Locking_Policy}
22936 @cindex pragma Locking_Policy (under rts-pthread)
22937 with respectively
22938 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22939 @cindex @code{Inheritance_Locking} (under rts-pthread)
22940 @cindex @code{Ceiling_Locking} (under rts-pthread)
22942 As explained above, the native run-time library is based on the Solaris thread
22943 library (@code{libthread}) and is the default library.
22945 When the Solaris threads library is used (this is the default), programs
22946 compiled with GNAT can automatically take advantage of
22947 and can thus execute on multiple processors.
22948 The user can alternatively specify a processor on which the program should run
22949 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22950 is made by
22951 setting the environment variable @env{GNAT_PROCESSOR}
22952 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22953 to one of the following:
22955 @table @code
22956 @item -2
22957 Use the default configuration (run the program on all
22958 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22959 unset
22961 @item -1
22962 Let the run-time implementation choose one processor and run the program on
22963 that processor
22965 @item 0 .. Last_Proc
22966 Run the program on the specified processor.
22967 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22968 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22969 @end table
22971 @node Linux-Specific Considerations
22972 @section Linux-Specific Considerations
22973 @cindex Linux threads libraries
22975 @noindent
22976 On GNU/Linux without NPTL support (usually system with GNU C Library
22977 older than 2.3), the signal model is not POSIX compliant, which means
22978 that to send a signal to the process, you need to send the signal to all
22979 threads, e.g.@: by using @code{killpg()}.
22981 @node AIX-Specific Considerations
22982 @section AIX-Specific Considerations
22983 @cindex AIX resolver library
22985 @noindent
22986 On AIX, the resolver library initializes some internal structure on
22987 the first call to @code{get*by*} functions, which are used to implement
22988 @code{GNAT.Sockets.Get_Host_By_Name} and
22989 @code{GNAT.Sockets.Get_Host_By_Address}.
22990 If such initialization occurs within an Ada task, and the stack size for
22991 the task is the default size, a stack overflow may occur.
22993 To avoid this overflow, the user should either ensure that the first call
22994 to @code{GNAT.Sockets.Get_Host_By_Name} or
22995 @code{GNAT.Sockets.Get_Host_By_Addrss}
22996 occurs in the environment task, or use @code{pragma Storage_Size} to
22997 specify a sufficiently large size for the stack of the task that contains
22998 this call.
23000 @node RTX-Specific Considerations
23001 @section RTX-Specific Considerations
23002 @cindex RTX libraries
23004 @noindent
23005 The Real-time Extension (RTX) to Windows is based on the Windows Win32
23006 API. Applications can be built to work in two different modes:
23008 @itemize @bullet
23009 @item
23010 Windows executables that run in Ring 3 to utilize memory protection
23011 (@emph{rts-rtx-w32}).
23013 @item
23014 Real-time subsystem (RTSS) executables that run in Ring 0, where
23015 performance can be optimized with RTSS applications taking precedent
23016 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
23017 the Microsoft linker to handle RTSS libraries.
23019 @end itemize
23021 @node HP-UX-Specific Considerations
23022 @section HP-UX-Specific Considerations
23023 @cindex HP-UX Scheduling
23025 @noindent
23026 On HP-UX, appropriate privileges are required to change the scheduling
23027 parameters of a task. The calling process must have appropriate
23028 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
23029 successfully change the scheduling parameters.
23031 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
23032 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
23033 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
23035 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
23036 one of the following:
23038 @itemize @bullet
23039 @item
23040 @code{pragma Time_Slice (0.0)}
23041 @cindex pragma Time_Slice
23042 @item
23043 the corresponding binder option @option{-T0}
23044 @cindex @option{-T0} option
23045 @item
23046 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23047 @cindex pragma Task_Dispatching_Policy
23048 @end itemize
23050 @noindent
23051 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
23052 you should use @code{pragma Time_Slice} with a
23053 value greater than @code{0.0}, or use the corresponding @option{-T}
23054 binder option, or set the @code{pragma Task_Dispatching_Policy
23055 (Round_Robin_Within_Priorities)}.
23057 @c *******************************
23058 @node Example of Binder Output File
23059 @appendix Example of Binder Output File
23061 @noindent
23062 This Appendix displays the source code for @command{gnatbind}'s output
23063 file generated for a simple ``Hello World'' program.
23064 Comments have been added for clarification purposes.
23066 @smallexample @c adanocomment
23067 @iftex
23068 @leftskip=0cm
23069 @end iftex
23070 --  The package is called Ada_Main unless this name is actually used
23071 --  as a unit name in the partition, in which case some other unique
23072 --  name is used.
23074 with System;
23075 package ada_main is
23077    Elab_Final_Code : Integer;
23078    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
23080    --  The main program saves the parameters (argument count,
23081    --  argument values, environment pointer) in global variables
23082    --  for later access by other units including
23083    --  Ada.Command_Line.
23085    gnat_argc : Integer;
23086    gnat_argv : System.Address;
23087    gnat_envp : System.Address;
23089    --  The actual variables are stored in a library routine. This
23090    --  is useful for some shared library situations, where there
23091    --  are problems if variables are not in the library.
23093    pragma Import (C, gnat_argc);
23094    pragma Import (C, gnat_argv);
23095    pragma Import (C, gnat_envp);
23097    --  The exit status is similarly an external location
23099    gnat_exit_status : Integer;
23100    pragma Import (C, gnat_exit_status);
23102    GNAT_Version : constant String :=
23103                     "GNAT Version: 6.0.0w (20061115)";
23104    pragma Export (C, GNAT_Version, "__gnat_version");
23106    --  This is the generated adafinal routine that performs
23107    --  finalization at the end of execution. In the case where
23108    --  Ada is the main program, this main program makes a call
23109    --  to adafinal at program termination.
23111    procedure adafinal;
23112    pragma Export (C, adafinal, "adafinal");
23114    --  This is the generated adainit routine that performs
23115    --  initialization at the start of execution. In the case
23116    --  where Ada is the main program, this main program makes
23117    --  a call to adainit at program startup.
23119    procedure adainit;
23120    pragma Export (C, adainit, "adainit");
23122    --  This routine is called at the start of execution. It is
23123    --  a dummy routine that is used by the debugger to breakpoint
23124    --  at the start of execution.
23126    procedure Break_Start;
23127    pragma Import (C, Break_Start, "__gnat_break_start");
23129    --  This is the actual generated main program (it would be
23130    --  suppressed if the no main program switch were used). As
23131    --  required by standard system conventions, this program has
23132    --  the external name main.
23134    function main
23135      (argc : Integer;
23136       argv : System.Address;
23137       envp : System.Address)
23138       return Integer;
23139    pragma Export (C, main, "main");
23141    --  The following set of constants give the version
23142    --  identification values for every unit in the bound
23143    --  partition. This identification is computed from all
23144    --  dependent semantic units, and corresponds to the
23145    --  string that would be returned by use of the
23146    --  Body_Version or Version attributes.
23148    type Version_32 is mod 2 ** 32;
23149    u00001 : constant Version_32 := 16#7880BEB3#;
23150    u00002 : constant Version_32 := 16#0D24CBD0#;
23151    u00003 : constant Version_32 := 16#3283DBEB#;
23152    u00004 : constant Version_32 := 16#2359F9ED#;
23153    u00005 : constant Version_32 := 16#664FB847#;
23154    u00006 : constant Version_32 := 16#68E803DF#;
23155    u00007 : constant Version_32 := 16#5572E604#;
23156    u00008 : constant Version_32 := 16#46B173D8#;
23157    u00009 : constant Version_32 := 16#156A40CF#;
23158    u00010 : constant Version_32 := 16#033DABE0#;
23159    u00011 : constant Version_32 := 16#6AB38FEA#;
23160    u00012 : constant Version_32 := 16#22B6217D#;
23161    u00013 : constant Version_32 := 16#68A22947#;
23162    u00014 : constant Version_32 := 16#18CC4A56#;
23163    u00015 : constant Version_32 := 16#08258E1B#;
23164    u00016 : constant Version_32 := 16#367D5222#;
23165    u00017 : constant Version_32 := 16#20C9ECA4#;
23166    u00018 : constant Version_32 := 16#50D32CB6#;
23167    u00019 : constant Version_32 := 16#39A8BB77#;
23168    u00020 : constant Version_32 := 16#5CF8FA2B#;
23169    u00021 : constant Version_32 := 16#2F1EB794#;
23170    u00022 : constant Version_32 := 16#31AB6444#;
23171    u00023 : constant Version_32 := 16#1574B6E9#;
23172    u00024 : constant Version_32 := 16#5109C189#;
23173    u00025 : constant Version_32 := 16#56D770CD#;
23174    u00026 : constant Version_32 := 16#02F9DE3D#;
23175    u00027 : constant Version_32 := 16#08AB6B2C#;
23176    u00028 : constant Version_32 := 16#3FA37670#;
23177    u00029 : constant Version_32 := 16#476457A0#;
23178    u00030 : constant Version_32 := 16#731E1B6E#;
23179    u00031 : constant Version_32 := 16#23C2E789#;
23180    u00032 : constant Version_32 := 16#0F1BD6A1#;
23181    u00033 : constant Version_32 := 16#7C25DE96#;
23182    u00034 : constant Version_32 := 16#39ADFFA2#;
23183    u00035 : constant Version_32 := 16#571DE3E7#;
23184    u00036 : constant Version_32 := 16#5EB646AB#;
23185    u00037 : constant Version_32 := 16#4249379B#;
23186    u00038 : constant Version_32 := 16#0357E00A#;
23187    u00039 : constant Version_32 := 16#3784FB72#;
23188    u00040 : constant Version_32 := 16#2E723019#;
23189    u00041 : constant Version_32 := 16#623358EA#;
23190    u00042 : constant Version_32 := 16#107F9465#;
23191    u00043 : constant Version_32 := 16#6843F68A#;
23192    u00044 : constant Version_32 := 16#63305874#;
23193    u00045 : constant Version_32 := 16#31E56CE1#;
23194    u00046 : constant Version_32 := 16#02917970#;
23195    u00047 : constant Version_32 := 16#6CCBA70E#;
23196    u00048 : constant Version_32 := 16#41CD4204#;
23197    u00049 : constant Version_32 := 16#572E3F58#;
23198    u00050 : constant Version_32 := 16#20729FF5#;
23199    u00051 : constant Version_32 := 16#1D4F93E8#;
23200    u00052 : constant Version_32 := 16#30B2EC3D#;
23201    u00053 : constant Version_32 := 16#34054F96#;
23202    u00054 : constant Version_32 := 16#5A199860#;
23203    u00055 : constant Version_32 := 16#0E7F912B#;
23204    u00056 : constant Version_32 := 16#5760634A#;
23205    u00057 : constant Version_32 := 16#5D851835#;
23207    --  The following Export pragmas export the version numbers
23208    --  with symbolic names ending in B (for body) or S
23209    --  (for spec) so that they can be located in a link. The
23210    --  information provided here is sufficient to track down
23211    --  the exact versions of units used in a given build.
23213    pragma Export (C, u00001, "helloB");
23214    pragma Export (C, u00002, "system__standard_libraryB");
23215    pragma Export (C, u00003, "system__standard_libraryS");
23216    pragma Export (C, u00004, "adaS");
23217    pragma Export (C, u00005, "ada__text_ioB");
23218    pragma Export (C, u00006, "ada__text_ioS");
23219    pragma Export (C, u00007, "ada__exceptionsB");
23220    pragma Export (C, u00008, "ada__exceptionsS");
23221    pragma Export (C, u00009, "gnatS");
23222    pragma Export (C, u00010, "gnat__heap_sort_aB");
23223    pragma Export (C, u00011, "gnat__heap_sort_aS");
23224    pragma Export (C, u00012, "systemS");
23225    pragma Export (C, u00013, "system__exception_tableB");
23226    pragma Export (C, u00014, "system__exception_tableS");
23227    pragma Export (C, u00015, "gnat__htableB");
23228    pragma Export (C, u00016, "gnat__htableS");
23229    pragma Export (C, u00017, "system__exceptionsS");
23230    pragma Export (C, u00018, "system__machine_state_operationsB");
23231    pragma Export (C, u00019, "system__machine_state_operationsS");
23232    pragma Export (C, u00020, "system__machine_codeS");
23233    pragma Export (C, u00021, "system__storage_elementsB");
23234    pragma Export (C, u00022, "system__storage_elementsS");
23235    pragma Export (C, u00023, "system__secondary_stackB");
23236    pragma Export (C, u00024, "system__secondary_stackS");
23237    pragma Export (C, u00025, "system__parametersB");
23238    pragma Export (C, u00026, "system__parametersS");
23239    pragma Export (C, u00027, "system__soft_linksB");
23240    pragma Export (C, u00028, "system__soft_linksS");
23241    pragma Export (C, u00029, "system__stack_checkingB");
23242    pragma Export (C, u00030, "system__stack_checkingS");
23243    pragma Export (C, u00031, "system__tracebackB");
23244    pragma Export (C, u00032, "system__tracebackS");
23245    pragma Export (C, u00033, "ada__streamsS");
23246    pragma Export (C, u00034, "ada__tagsB");
23247    pragma Export (C, u00035, "ada__tagsS");
23248    pragma Export (C, u00036, "system__string_opsB");
23249    pragma Export (C, u00037, "system__string_opsS");
23250    pragma Export (C, u00038, "interfacesS");
23251    pragma Export (C, u00039, "interfaces__c_streamsB");
23252    pragma Export (C, u00040, "interfaces__c_streamsS");
23253    pragma Export (C, u00041, "system__file_ioB");
23254    pragma Export (C, u00042, "system__file_ioS");
23255    pragma Export (C, u00043, "ada__finalizationB");
23256    pragma Export (C, u00044, "ada__finalizationS");
23257    pragma Export (C, u00045, "system__finalization_rootB");
23258    pragma Export (C, u00046, "system__finalization_rootS");
23259    pragma Export (C, u00047, "system__finalization_implementationB");
23260    pragma Export (C, u00048, "system__finalization_implementationS");
23261    pragma Export (C, u00049, "system__string_ops_concat_3B");
23262    pragma Export (C, u00050, "system__string_ops_concat_3S");
23263    pragma Export (C, u00051, "system__stream_attributesB");
23264    pragma Export (C, u00052, "system__stream_attributesS");
23265    pragma Export (C, u00053, "ada__io_exceptionsS");
23266    pragma Export (C, u00054, "system__unsigned_typesS");
23267    pragma Export (C, u00055, "system__file_control_blockS");
23268    pragma Export (C, u00056, "ada__finalization__list_controllerB");
23269    pragma Export (C, u00057, "ada__finalization__list_controllerS");
23271    -- BEGIN ELABORATION ORDER
23272    -- ada (spec)
23273    -- gnat (spec)
23274    -- gnat.heap_sort_a (spec)
23275    -- gnat.heap_sort_a (body)
23276    -- gnat.htable (spec)
23277    -- gnat.htable (body)
23278    -- interfaces (spec)
23279    -- system (spec)
23280    -- system.machine_code (spec)
23281    -- system.parameters (spec)
23282    -- system.parameters (body)
23283    -- interfaces.c_streams (spec)
23284    -- interfaces.c_streams (body)
23285    -- system.standard_library (spec)
23286    -- ada.exceptions (spec)
23287    -- system.exception_table (spec)
23288    -- system.exception_table (body)
23289    -- ada.io_exceptions (spec)
23290    -- system.exceptions (spec)
23291    -- system.storage_elements (spec)
23292    -- system.storage_elements (body)
23293    -- system.machine_state_operations (spec)
23294    -- system.machine_state_operations (body)
23295    -- system.secondary_stack (spec)
23296    -- system.stack_checking (spec)
23297    -- system.soft_links (spec)
23298    -- system.soft_links (body)
23299    -- system.stack_checking (body)
23300    -- system.secondary_stack (body)
23301    -- system.standard_library (body)
23302    -- system.string_ops (spec)
23303    -- system.string_ops (body)
23304    -- ada.tags (spec)
23305    -- ada.tags (body)
23306    -- ada.streams (spec)
23307    -- system.finalization_root (spec)
23308    -- system.finalization_root (body)
23309    -- system.string_ops_concat_3 (spec)
23310    -- system.string_ops_concat_3 (body)
23311    -- system.traceback (spec)
23312    -- system.traceback (body)
23313    -- ada.exceptions (body)
23314    -- system.unsigned_types (spec)
23315    -- system.stream_attributes (spec)
23316    -- system.stream_attributes (body)
23317    -- system.finalization_implementation (spec)
23318    -- system.finalization_implementation (body)
23319    -- ada.finalization (spec)
23320    -- ada.finalization (body)
23321    -- ada.finalization.list_controller (spec)
23322    -- ada.finalization.list_controller (body)
23323    -- system.file_control_block (spec)
23324    -- system.file_io (spec)
23325    -- system.file_io (body)
23326    -- ada.text_io (spec)
23327    -- ada.text_io (body)
23328    -- hello (body)
23329    -- END ELABORATION ORDER
23331 end ada_main;
23333 --  The following source file name pragmas allow the generated file
23334 --  names to be unique for different main programs. They are needed
23335 --  since the package name will always be Ada_Main.
23337 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
23338 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
23340 --  Generated package body for Ada_Main starts here
23342 package body ada_main is
23344    --  The actual finalization is performed by calling the
23345    --  library routine in System.Standard_Library.Adafinal
23347    procedure Do_Finalize;
23348    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
23350    -------------
23351    -- adainit --
23352    -------------
23354 @findex adainit
23355    procedure adainit is
23357       --  These booleans are set to True once the associated unit has
23358       --  been elaborated. It is also used to avoid elaborating the
23359       --  same unit twice.
23361       E040 : Boolean;
23362       pragma Import (Ada, E040, "interfaces__c_streams_E");
23364       E008 : Boolean;
23365       pragma Import (Ada, E008, "ada__exceptions_E");
23367       E014 : Boolean;
23368       pragma Import (Ada, E014, "system__exception_table_E");
23370       E053 : Boolean;
23371       pragma Import (Ada, E053, "ada__io_exceptions_E");
23373       E017 : Boolean;
23374       pragma Import (Ada, E017, "system__exceptions_E");
23376       E024 : Boolean;
23377       pragma Import (Ada, E024, "system__secondary_stack_E");
23379       E030 : Boolean;
23380       pragma Import (Ada, E030, "system__stack_checking_E");
23382       E028 : Boolean;
23383       pragma Import (Ada, E028, "system__soft_links_E");
23385       E035 : Boolean;
23386       pragma Import (Ada, E035, "ada__tags_E");
23388       E033 : Boolean;
23389       pragma Import (Ada, E033, "ada__streams_E");
23391       E046 : Boolean;
23392       pragma Import (Ada, E046, "system__finalization_root_E");
23394       E048 : Boolean;
23395       pragma Import (Ada, E048, "system__finalization_implementation_E");
23397       E044 : Boolean;
23398       pragma Import (Ada, E044, "ada__finalization_E");
23400       E057 : Boolean;
23401       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23403       E055 : Boolean;
23404       pragma Import (Ada, E055, "system__file_control_block_E");
23406       E042 : Boolean;
23407       pragma Import (Ada, E042, "system__file_io_E");
23409       E006 : Boolean;
23410       pragma Import (Ada, E006, "ada__text_io_E");
23412       --  Set_Globals is a library routine that stores away the
23413       --  value of the indicated set of global values in global
23414       --  variables within the library.
23416       procedure Set_Globals
23417         (Main_Priority            : Integer;
23418          Time_Slice_Value         : Integer;
23419          WC_Encoding              : Character;
23420          Locking_Policy           : Character;
23421          Queuing_Policy           : Character;
23422          Task_Dispatching_Policy  : Character;
23423          Adafinal                 : System.Address;
23424          Unreserve_All_Interrupts : Integer;
23425          Exception_Tracebacks     : Integer);
23426 @findex __gnat_set_globals
23427       pragma Import (C, Set_Globals, "__gnat_set_globals");
23429       --  SDP_Table_Build is a library routine used to build the
23430       --  exception tables. See unit Ada.Exceptions in files
23431       --  a-except.ads/adb for full details of how zero cost
23432       --  exception handling works. This procedure, the call to
23433       --  it, and the two following tables are all omitted if the
23434       --  build is in longjmp/setjmp exception mode.
23436 @findex SDP_Table_Build
23437 @findex Zero Cost Exceptions
23438       procedure SDP_Table_Build
23439         (SDP_Addresses   : System.Address;
23440          SDP_Count       : Natural;
23441          Elab_Addresses  : System.Address;
23442          Elab_Addr_Count : Natural);
23443       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
23445       --  Table of Unit_Exception_Table addresses. Used for zero
23446       --  cost exception handling to build the top level table.
23448       ST : aliased constant array (1 .. 23) of System.Address := (
23449         Hello'UET_Address,
23450         Ada.Text_Io'UET_Address,
23451         Ada.Exceptions'UET_Address,
23452         Gnat.Heap_Sort_A'UET_Address,
23453         System.Exception_Table'UET_Address,
23454         System.Machine_State_Operations'UET_Address,
23455         System.Secondary_Stack'UET_Address,
23456         System.Parameters'UET_Address,
23457         System.Soft_Links'UET_Address,
23458         System.Stack_Checking'UET_Address,
23459         System.Traceback'UET_Address,
23460         Ada.Streams'UET_Address,
23461         Ada.Tags'UET_Address,
23462         System.String_Ops'UET_Address,
23463         Interfaces.C_Streams'UET_Address,
23464         System.File_Io'UET_Address,
23465         Ada.Finalization'UET_Address,
23466         System.Finalization_Root'UET_Address,
23467         System.Finalization_Implementation'UET_Address,
23468         System.String_Ops_Concat_3'UET_Address,
23469         System.Stream_Attributes'UET_Address,
23470         System.File_Control_Block'UET_Address,
23471         Ada.Finalization.List_Controller'UET_Address);
23473       --  Table of addresses of elaboration routines. Used for
23474       --  zero cost exception handling to make sure these
23475       --  addresses are included in the top level procedure
23476       --  address table.
23478       EA : aliased constant array (1 .. 23) of System.Address := (
23479         adainit'Code_Address,
23480         Do_Finalize'Code_Address,
23481         Ada.Exceptions'Elab_Spec'Address,
23482         System.Exceptions'Elab_Spec'Address,
23483         Interfaces.C_Streams'Elab_Spec'Address,
23484         System.Exception_Table'Elab_Body'Address,
23485         Ada.Io_Exceptions'Elab_Spec'Address,
23486         System.Stack_Checking'Elab_Spec'Address,
23487         System.Soft_Links'Elab_Body'Address,
23488         System.Secondary_Stack'Elab_Body'Address,
23489         Ada.Tags'Elab_Spec'Address,
23490         Ada.Tags'Elab_Body'Address,
23491         Ada.Streams'Elab_Spec'Address,
23492         System.Finalization_Root'Elab_Spec'Address,
23493         Ada.Exceptions'Elab_Body'Address,
23494         System.Finalization_Implementation'Elab_Spec'Address,
23495         System.Finalization_Implementation'Elab_Body'Address,
23496         Ada.Finalization'Elab_Spec'Address,
23497         Ada.Finalization.List_Controller'Elab_Spec'Address,
23498         System.File_Control_Block'Elab_Spec'Address,
23499         System.File_Io'Elab_Body'Address,
23500         Ada.Text_Io'Elab_Spec'Address,
23501         Ada.Text_Io'Elab_Body'Address);
23503    --  Start of processing for adainit
23505    begin
23507       --  Call SDP_Table_Build to build the top level procedure
23508       --  table for zero cost exception handling (omitted in
23509       --  longjmp/setjmp mode).
23511       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23513       --  Call Set_Globals to record various information for
23514       --  this partition.  The values are derived by the binder
23515       --  from information stored in the ali files by the compiler.
23517 @findex __gnat_set_globals
23518       Set_Globals
23519         (Main_Priority            => -1,
23520          --  Priority of main program, -1 if no pragma Priority used
23522          Time_Slice_Value         => -1,
23523          --  Time slice from Time_Slice pragma, -1 if none used
23525          WC_Encoding              => 'b',
23526          --  Wide_Character encoding used, default is brackets
23528          Locking_Policy           => ' ',
23529          --  Locking_Policy used, default of space means not
23530          --  specified, otherwise it is the first character of
23531          --  the policy name.
23533          Queuing_Policy           => ' ',
23534          --  Queuing_Policy used, default of space means not
23535          --  specified, otherwise it is the first character of
23536          --  the policy name.
23538          Task_Dispatching_Policy  => ' ',
23539          --  Task_Dispatching_Policy used, default of space means
23540          --  not specified, otherwise first character of the
23541          --  policy name.
23543          Adafinal                 => System.Null_Address,
23544          --  Address of Adafinal routine, not used anymore
23546          Unreserve_All_Interrupts => 0,
23547          --  Set true if pragma Unreserve_All_Interrupts was used
23549          Exception_Tracebacks     => 0);
23550          --  Indicates if exception tracebacks are enabled
23552       Elab_Final_Code := 1;
23554       --  Now we have the elaboration calls for all units in the partition.
23555       --  The Elab_Spec and Elab_Body attributes generate references to the
23556       --  implicit elaboration procedures generated by the compiler for
23557       --  each unit that requires elaboration.
23559       if not E040 then
23560          Interfaces.C_Streams'Elab_Spec;
23561       end if;
23562       E040 := True;
23563       if not E008 then
23564          Ada.Exceptions'Elab_Spec;
23565       end if;
23566       if not E014 then
23567          System.Exception_Table'Elab_Body;
23568          E014 := True;
23569       end if;
23570       if not E053 then
23571          Ada.Io_Exceptions'Elab_Spec;
23572          E053 := True;
23573       end if;
23574       if not E017 then
23575          System.Exceptions'Elab_Spec;
23576          E017 := True;
23577       end if;
23578       if not E030 then
23579          System.Stack_Checking'Elab_Spec;
23580       end if;
23581       if not E028 then
23582          System.Soft_Links'Elab_Body;
23583          E028 := True;
23584       end if;
23585       E030 := True;
23586       if not E024 then
23587          System.Secondary_Stack'Elab_Body;
23588          E024 := True;
23589       end if;
23590       if not E035 then
23591          Ada.Tags'Elab_Spec;
23592       end if;
23593       if not E035 then
23594          Ada.Tags'Elab_Body;
23595          E035 := True;
23596       end if;
23597       if not E033 then
23598          Ada.Streams'Elab_Spec;
23599          E033 := True;
23600       end if;
23601       if not E046 then
23602          System.Finalization_Root'Elab_Spec;
23603       end if;
23604       E046 := True;
23605       if not E008 then
23606          Ada.Exceptions'Elab_Body;
23607          E008 := True;
23608       end if;
23609       if not E048 then
23610          System.Finalization_Implementation'Elab_Spec;
23611       end if;
23612       if not E048 then
23613          System.Finalization_Implementation'Elab_Body;
23614          E048 := True;
23615       end if;
23616       if not E044 then
23617          Ada.Finalization'Elab_Spec;
23618       end if;
23619       E044 := True;
23620       if not E057 then
23621          Ada.Finalization.List_Controller'Elab_Spec;
23622       end if;
23623       E057 := True;
23624       if not E055 then
23625          System.File_Control_Block'Elab_Spec;
23626          E055 := True;
23627       end if;
23628       if not E042 then
23629          System.File_Io'Elab_Body;
23630          E042 := True;
23631       end if;
23632       if not E006 then
23633          Ada.Text_Io'Elab_Spec;
23634       end if;
23635       if not E006 then
23636          Ada.Text_Io'Elab_Body;
23637          E006 := True;
23638       end if;
23640       Elab_Final_Code := 0;
23641    end adainit;
23643    --------------
23644    -- adafinal --
23645    --------------
23647 @findex adafinal
23648    procedure adafinal is
23649    begin
23650       Do_Finalize;
23651    end adafinal;
23653    ----------
23654    -- main --
23655    ----------
23657    --  main is actually a function, as in the ANSI C standard,
23658    --  defined to return the exit status. The three parameters
23659    --  are the argument count, argument values and environment
23660    --  pointer.
23662 @findex Main Program
23663    function main
23664      (argc : Integer;
23665       argv : System.Address;
23666       envp : System.Address)
23667       return Integer
23668    is
23669       --  The initialize routine performs low level system
23670       --  initialization using a standard library routine which
23671       --  sets up signal handling and performs any other
23672       --  required setup. The routine can be found in file
23673       --  a-init.c.
23675 @findex __gnat_initialize
23676       procedure initialize;
23677       pragma Import (C, initialize, "__gnat_initialize");
23679       --  The finalize routine performs low level system
23680       --  finalization using a standard library routine. The
23681       --  routine is found in file a-final.c and in the standard
23682       --  distribution is a dummy routine that does nothing, so
23683       --  really this is a hook for special user finalization.
23685 @findex __gnat_finalize
23686       procedure finalize;
23687       pragma Import (C, finalize, "__gnat_finalize");
23689       --  We get to the main program of the partition by using
23690       --  pragma Import because if we try to with the unit and
23691       --  call it Ada style, then not only do we waste time
23692       --  recompiling it, but also, we don't really know the right
23693       --  switches (e.g.@: identifier character set) to be used
23694       --  to compile it.
23696       procedure Ada_Main_Program;
23697       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23699    --  Start of processing for main
23701    begin
23702       --  Save global variables
23704       gnat_argc := argc;
23705       gnat_argv := argv;
23706       gnat_envp := envp;
23708       --  Call low level system initialization
23710       Initialize;
23712       --  Call our generated Ada initialization routine
23714       adainit;
23716       --  This is the point at which we want the debugger to get
23717       --  control
23719       Break_Start;
23721       --  Now we call the main program of the partition
23723       Ada_Main_Program;
23725       --  Perform Ada finalization
23727       adafinal;
23729       --  Perform low level system finalization
23731       Finalize;
23733       --  Return the proper exit status
23734       return (gnat_exit_status);
23735    end;
23737 --  This section is entirely comments, so it has no effect on the
23738 --  compilation of the Ada_Main package. It provides the list of
23739 --  object files and linker options, as well as some standard
23740 --  libraries needed for the link. The gnatlink utility parses
23741 --  this b~hello.adb file to read these comment lines to generate
23742 --  the appropriate command line arguments for the call to the
23743 --  system linker. The BEGIN/END lines are used for sentinels for
23744 --  this parsing operation.
23746 --  The exact file names will of course depend on the environment,
23747 --  host/target and location of files on the host system.
23749 @findex Object file list
23750 -- BEGIN Object file/option list
23751    --   ./hello.o
23752    --   -L./
23753    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23754    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23755 -- END Object file/option list
23757 end ada_main;
23758 @end smallexample
23760 @noindent
23761 The Ada code in the above example is exactly what is generated by the
23762 binder. We have added comments to more clearly indicate the function
23763 of each part of the generated @code{Ada_Main} package.
23765 The code is standard Ada in all respects, and can be processed by any
23766 tools that handle Ada. In particular, it is possible to use the debugger
23767 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23768 suppose that for reasons that you do not understand, your program is crashing
23769 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23770 you can place a breakpoint on the call:
23772 @smallexample @c ada
23773 Ada.Text_Io'Elab_Body;
23774 @end smallexample
23776 @noindent
23777 and trace the elaboration routine for this package to find out where
23778 the problem might be (more usually of course you would be debugging
23779 elaboration code in your own application).
23781 @node Elaboration Order Handling in GNAT
23782 @appendix Elaboration Order Handling in GNAT
23783 @cindex Order of elaboration
23784 @cindex Elaboration control
23786 @menu
23787 * Elaboration Code::
23788 * Checking the Elaboration Order::
23789 * Controlling the Elaboration Order::
23790 * Controlling Elaboration in GNAT - Internal Calls::
23791 * Controlling Elaboration in GNAT - External Calls::
23792 * Default Behavior in GNAT - Ensuring Safety::
23793 * Treatment of Pragma Elaborate::
23794 * Elaboration Issues for Library Tasks::
23795 * Mixing Elaboration Models::
23796 * What to Do If the Default Elaboration Behavior Fails::
23797 * Elaboration for Dispatching Calls::
23798 * Summary of Procedures for Elaboration Control::
23799 * Other Elaboration Order Considerations::
23800 @end menu
23802 @noindent
23803 This chapter describes the handling of elaboration code in Ada and
23804 in GNAT, and discusses how the order of elaboration of program units can
23805 be controlled in GNAT, either automatically or with explicit programming
23806 features.
23808 @node Elaboration Code
23809 @section Elaboration Code
23811 @noindent
23812 Ada provides rather general mechanisms for executing code at elaboration
23813 time, that is to say before the main program starts executing. Such code arises
23814 in three contexts:
23816 @table @asis
23817 @item Initializers for variables.
23818 Variables declared at the library level, in package specs or bodies, can
23819 require initialization that is performed at elaboration time, as in:
23820 @smallexample @c ada
23821 @cartouche
23822 Sqrt_Half : Float := Sqrt (0.5);
23823 @end cartouche
23824 @end smallexample
23826 @item Package initialization code
23827 Code in a @code{BEGIN-END} section at the outer level of a package body is
23828 executed as part of the package body elaboration code.
23830 @item Library level task allocators
23831 Tasks that are declared using task allocators at the library level
23832 start executing immediately and hence can execute at elaboration time.
23833 @end table
23835 @noindent
23836 Subprogram calls are possible in any of these contexts, which means that
23837 any arbitrary part of the program may be executed as part of the elaboration
23838 code. It is even possible to write a program which does all its work at
23839 elaboration time, with a null main program, although stylistically this
23840 would usually be considered an inappropriate way to structure
23841 a program.
23843 An important concern arises in the context of elaboration code:
23844 we have to be sure that it is executed in an appropriate order. What we
23845 have is a series of elaboration code sections, potentially one section
23846 for each unit in the program. It is important that these execute
23847 in the correct order. Correctness here means that, taking the above
23848 example of the declaration of @code{Sqrt_Half},
23849 if some other piece of
23850 elaboration code references @code{Sqrt_Half},
23851 then it must run after the
23852 section of elaboration code that contains the declaration of
23853 @code{Sqrt_Half}.
23855 There would never be any order of elaboration problem if we made a rule
23856 that whenever you @code{with} a unit, you must elaborate both the spec and body
23857 of that unit before elaborating the unit doing the @code{with}'ing:
23859 @smallexample @c ada
23860 @group
23861 @cartouche
23862 with Unit_1;
23863 package Unit_2 is @dots{}
23864 @end cartouche
23865 @end group
23866 @end smallexample
23868 @noindent
23869 would require that both the body and spec of @code{Unit_1} be elaborated
23870 before the spec of @code{Unit_2}. However, a rule like that would be far too
23871 restrictive. In particular, it would make it impossible to have routines
23872 in separate packages that were mutually recursive.
23874 You might think that a clever enough compiler could look at the actual
23875 elaboration code and determine an appropriate correct order of elaboration,
23876 but in the general case, this is not possible. Consider the following
23877 example.
23879 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23880 that references
23881 the variable @code{Sqrt_1}, which is declared in the elaboration code
23882 of the body of @code{Unit_1}:
23884 @smallexample @c ada
23885 @cartouche
23886 Sqrt_1 : Float := Sqrt (0.1);
23887 @end cartouche
23888 @end smallexample
23890 @noindent
23891 The elaboration code of the body of @code{Unit_1} also contains:
23893 @smallexample @c ada
23894 @group
23895 @cartouche
23896 if expression_1 = 1 then
23897    Q := Unit_2.Func_2;
23898 end if;
23899 @end cartouche
23900 @end group
23901 @end smallexample
23903 @noindent
23904 @code{Unit_2} is exactly parallel,
23905 it has a procedure @code{Func_2} that references
23906 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23907 the body @code{Unit_2}:
23909 @smallexample @c ada
23910 @cartouche
23911 Sqrt_2 : Float := Sqrt (0.1);
23912 @end cartouche
23913 @end smallexample
23915 @noindent
23916 The elaboration code of the body of @code{Unit_2} also contains:
23918 @smallexample @c ada
23919 @group
23920 @cartouche
23921 if expression_2 = 2 then
23922    Q := Unit_1.Func_1;
23923 end if;
23924 @end cartouche
23925 @end group
23926 @end smallexample
23928 @noindent
23929 Now the question is, which of the following orders of elaboration is
23930 acceptable:
23932 @smallexample
23933 @group
23934 Spec of Unit_1
23935 Spec of Unit_2
23936 Body of Unit_1
23937 Body of Unit_2
23938 @end group
23939 @end smallexample
23941 @noindent
23944 @smallexample
23945 @group
23946 Spec of Unit_2
23947 Spec of Unit_1
23948 Body of Unit_2
23949 Body of Unit_1
23950 @end group
23951 @end smallexample
23953 @noindent
23954 If you carefully analyze the flow here, you will see that you cannot tell
23955 at compile time the answer to this question.
23956 If @code{expression_1} is not equal to 1,
23957 and @code{expression_2} is not equal to 2,
23958 then either order is acceptable, because neither of the function calls is
23959 executed. If both tests evaluate to true, then neither order is acceptable
23960 and in fact there is no correct order.
23962 If one of the two expressions is true, and the other is false, then one
23963 of the above orders is correct, and the other is incorrect. For example,
23964 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23965 then the call to @code{Func_1}
23966 will occur, but not the call to @code{Func_2.}
23967 This means that it is essential
23968 to elaborate the body of @code{Unit_1} before
23969 the body of @code{Unit_2}, so the first
23970 order of elaboration is correct and the second is wrong.
23972 By making @code{expression_1} and @code{expression_2}
23973 depend on input data, or perhaps
23974 the time of day, we can make it impossible for the compiler or binder
23975 to figure out which of these expressions will be true, and hence it
23976 is impossible to guarantee a safe order of elaboration at run time.
23978 @node Checking the Elaboration Order
23979 @section Checking the Elaboration Order
23981 @noindent
23982 In some languages that involve the same kind of elaboration problems,
23983 e.g.@: Java and C++, the programmer is expected to worry about these
23984 ordering problems himself, and it is common to
23985 write a program in which an incorrect elaboration order  gives
23986 surprising results, because it references variables before they
23987 are initialized.
23988 Ada is designed to be a safe language, and a programmer-beware approach is
23989 clearly not sufficient. Consequently, the language provides three lines
23990 of defense:
23992 @table @asis
23993 @item Standard rules
23994 Some standard rules restrict the possible choice of elaboration
23995 order. In particular, if you @code{with} a unit, then its spec is always
23996 elaborated before the unit doing the @code{with}. Similarly, a parent
23997 spec is always elaborated before the child spec, and finally
23998 a spec is always elaborated before its corresponding body.
24000 @item Dynamic elaboration checks
24001 @cindex Elaboration checks
24002 @cindex Checks, elaboration
24003 Dynamic checks are made at run time, so that if some entity is accessed
24004 before it is elaborated (typically  by means of a subprogram call)
24005 then the exception (@code{Program_Error}) is raised.
24007 @item Elaboration control
24008 Facilities are provided for the programmer to specify the desired order
24009 of elaboration.
24010 @end table
24012 Let's look at these facilities in more detail. First, the rules for
24013 dynamic checking. One possible rule would be simply to say that the
24014 exception is raised if you access a variable which has not yet been
24015 elaborated. The trouble with this approach is that it could require
24016 expensive checks on every variable reference. Instead Ada has two
24017 rules which are a little more restrictive, but easier to check, and
24018 easier to state:
24020 @table @asis
24021 @item Restrictions on calls
24022 A subprogram can only be called at elaboration time if its body
24023 has been elaborated. The rules for elaboration given above guarantee
24024 that the spec of the subprogram has been elaborated before the
24025 call, but not the body. If this rule is violated, then the
24026 exception @code{Program_Error} is raised.
24028 @item Restrictions on instantiations
24029 A generic unit can only be instantiated if the body of the generic
24030 unit has been elaborated. Again, the rules for elaboration given above
24031 guarantee that the spec of the generic unit has been elaborated
24032 before the instantiation, but not the body. If this rule is
24033 violated, then the exception @code{Program_Error} is raised.
24034 @end table
24036 @noindent
24037 The idea is that if the body has been elaborated, then any variables
24038 it references must have been elaborated; by checking for the body being
24039 elaborated we guarantee that none of its references causes any
24040 trouble. As we noted above, this is a little too restrictive, because a
24041 subprogram that has no non-local references in its body may in fact be safe
24042 to call. However, it really would be unsafe to rely on this, because
24043 it would mean that the caller was aware of details of the implementation
24044 in the body. This goes against the basic tenets of Ada.
24046 A plausible implementation can be described as follows.
24047 A Boolean variable is associated with each subprogram
24048 and each generic unit. This variable is initialized to False, and is set to
24049 True at the point body is elaborated. Every call or instantiation checks the
24050 variable, and raises @code{Program_Error} if the variable is False.
24052 Note that one might think that it would be good enough to have one Boolean
24053 variable for each package, but that would not deal with cases of trying
24054 to call a body in the same package as the call
24055 that has not been elaborated yet.
24056 Of course a compiler may be able to do enough analysis to optimize away
24057 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24058 does such optimizations, but still the easiest conceptual model is to
24059 think of there being one variable per subprogram.
24061 @node Controlling the Elaboration Order
24062 @section Controlling the Elaboration Order
24064 @noindent
24065 In the previous section we discussed the rules in Ada which ensure
24066 that @code{Program_Error} is raised if an incorrect elaboration order is
24067 chosen. This prevents erroneous executions, but we need mechanisms to
24068 specify a correct execution and avoid the exception altogether.
24069 To achieve this, Ada provides a number of features for controlling
24070 the order of elaboration. We discuss these features in this section.
24072 First, there are several ways of indicating to the compiler that a given
24073 unit has no elaboration problems:
24075 @table @asis
24076 @item packages that do not require a body
24077 A library package that does not require a body does not permit
24078 a body (this rule was introduced in Ada 95).
24079 Thus if we have a such a package, as in:
24081 @smallexample @c ada
24082 @group
24083 @cartouche
24084 package Definitions is
24085    generic
24086       type m is new integer;
24087    package Subp is
24088       type a is array (1 .. 10) of m;
24089       type b is array (1 .. 20) of m;
24090    end Subp;
24091 end Definitions;
24092 @end cartouche
24093 @end group
24094 @end smallexample
24096 @noindent
24097 A package that @code{with}'s @code{Definitions} may safely instantiate
24098 @code{Definitions.Subp} because the compiler can determine that there
24099 definitely is no package body to worry about in this case
24101 @item pragma Pure
24102 @cindex pragma Pure
24103 @findex Pure
24104 Places sufficient restrictions on a unit to guarantee that
24105 no call to any subprogram in the unit can result in an
24106 elaboration problem. This means that the compiler does not need
24107 to worry about the point of elaboration of such units, and in
24108 particular, does not need to check any calls to any subprograms
24109 in this unit.
24111 @item pragma Preelaborate
24112 @findex Preelaborate
24113 @cindex pragma Preelaborate
24114 This pragma places slightly less stringent restrictions on a unit than
24115 does pragma Pure,
24116 but these restrictions are still sufficient to ensure that there
24117 are no elaboration problems with any calls to the unit.
24119 @item pragma Elaborate_Body
24120 @findex Elaborate_Body
24121 @cindex pragma Elaborate_Body
24122 This pragma requires that the body of a unit be elaborated immediately
24123 after its spec. Suppose a unit @code{A} has such a pragma,
24124 and unit @code{B} does
24125 a @code{with} of unit @code{A}. Recall that the standard rules require
24126 the spec of unit @code{A}
24127 to be elaborated before the @code{with}'ing unit; given the pragma in
24128 @code{A}, we also know that the body of @code{A}
24129 will be elaborated before @code{B}, so
24130 that calls to @code{A} are safe and do not need a check.
24131 @end table
24133 @noindent
24134 Note that,
24135 unlike pragma @code{Pure} and pragma @code{Preelaborate},
24136 the use of
24137 @code{Elaborate_Body} does not guarantee that the program is
24138 free of elaboration problems, because it may not be possible
24139 to satisfy the requested elaboration order.
24140 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
24141 If a programmer
24142 marks @code{Unit_1} as @code{Elaborate_Body},
24143 and not @code{Unit_2,} then the order of
24144 elaboration will be:
24146 @smallexample
24147 @group
24148 Spec of Unit_2
24149 Spec of Unit_1
24150 Body of Unit_1
24151 Body of Unit_2
24152 @end group
24153 @end smallexample
24155 @noindent
24156 Now that means that the call to @code{Func_1} in @code{Unit_2}
24157 need not be checked,
24158 it must be safe. But the call to @code{Func_2} in
24159 @code{Unit_1} may still fail if
24160 @code{Expression_1} is equal to 1,
24161 and the programmer must still take
24162 responsibility for this not being the case.
24164 If all units carry a pragma @code{Elaborate_Body}, then all problems are
24165 eliminated, except for calls entirely within a body, which are
24166 in any case fully under programmer control. However, using the pragma
24167 everywhere is not always possible.
24168 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
24169 we marked both of them as having pragma @code{Elaborate_Body}, then
24170 clearly there would be no possible elaboration order.
24172 The above pragmas allow a server to guarantee safe use by clients, and
24173 clearly this is the preferable approach. Consequently a good rule
24174 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
24175 and if this is not possible,
24176 mark them as @code{Elaborate_Body} if possible.
24177 As we have seen, there are situations where neither of these
24178 three pragmas can be used.
24179 So we also provide methods for clients to control the
24180 order of elaboration of the servers on which they depend:
24182 @table @asis
24183 @item pragma Elaborate (unit)
24184 @findex Elaborate
24185 @cindex pragma Elaborate
24186 This pragma is placed in the context clause, after a @code{with} clause,
24187 and it requires that the body of the named unit be elaborated before
24188 the unit in which the pragma occurs. The idea is to use this pragma
24189 if the current unit calls at elaboration time, directly or indirectly,
24190 some subprogram in the named unit.
24192 @item pragma Elaborate_All (unit)
24193 @findex Elaborate_All
24194 @cindex pragma Elaborate_All
24195 This is a stronger version of the Elaborate pragma. Consider the
24196 following example:
24198 @smallexample
24199 Unit A @code{with}'s unit B and calls B.Func in elab code
24200 Unit B @code{with}'s unit C, and B.Func calls C.Func
24201 @end smallexample
24203 @noindent
24204 Now if we put a pragma @code{Elaborate (B)}
24205 in unit @code{A}, this ensures that the
24206 body of @code{B} is elaborated before the call, but not the
24207 body of @code{C}, so
24208 the call to @code{C.Func} could still cause @code{Program_Error} to
24209 be raised.
24211 The effect of a pragma @code{Elaborate_All} is stronger, it requires
24212 not only that the body of the named unit be elaborated before the
24213 unit doing the @code{with}, but also the bodies of all units that the
24214 named unit uses, following @code{with} links transitively. For example,
24215 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
24216 then it requires
24217 not only that the body of @code{B} be elaborated before @code{A},
24218 but also the
24219 body of @code{C}, because @code{B} @code{with}'s @code{C}.
24220 @end table
24222 @noindent
24223 We are now in a position to give a usage rule in Ada for avoiding
24224 elaboration problems, at least if dynamic dispatching and access to
24225 subprogram values are not used. We will handle these cases separately
24226 later.
24228 The rule is simple. If a unit has elaboration code that can directly or
24229 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
24230 a generic package in a @code{with}'ed unit,
24231 then if the @code{with}'ed unit does not have
24232 pragma @code{Pure} or @code{Preelaborate}, then the client should have
24233 a pragma @code{Elaborate_All}
24234 for the @code{with}'ed unit. By following this rule a client is
24235 assured that calls can be made without risk of an exception.
24237 For generic subprogram instantiations, the rule can be relaxed to
24238 require only a pragma @code{Elaborate} since elaborating the body
24239 of a subprogram cannot cause any transitive elaboration (we are
24240 not calling the subprogram in this case, just elaborating its
24241 declaration).
24243 If this rule is not followed, then a program may be in one of four
24244 states:
24246 @table @asis
24247 @item No order exists
24248 No order of elaboration exists which follows the rules, taking into
24249 account any @code{Elaborate}, @code{Elaborate_All},
24250 or @code{Elaborate_Body} pragmas. In
24251 this case, an Ada compiler must diagnose the situation at bind
24252 time, and refuse to build an executable program.
24254 @item One or more orders exist, all incorrect
24255 One or more acceptable elaboration orders exist, and all of them
24256 generate an elaboration order problem. In this case, the binder
24257 can build an executable program, but @code{Program_Error} will be raised
24258 when the program is run.
24260 @item Several orders exist, some right, some incorrect
24261 One or more acceptable elaboration orders exists, and some of them
24262 work, and some do not. The programmer has not controlled
24263 the order of elaboration, so the binder may or may not pick one of
24264 the correct orders, and the program may or may not raise an
24265 exception when it is run. This is the worst case, because it means
24266 that the program may fail when moved to another compiler, or even
24267 another version of the same compiler.
24269 @item One or more orders exists, all correct
24270 One ore more acceptable elaboration orders exist, and all of them
24271 work. In this case the program runs successfully. This state of
24272 affairs can be guaranteed by following the rule we gave above, but
24273 may be true even if the rule is not followed.
24274 @end table
24276 @noindent
24277 Note that one additional advantage of following our rules on the use
24278 of @code{Elaborate} and @code{Elaborate_All}
24279 is that the program continues to stay in the ideal (all orders OK) state
24280 even if maintenance
24281 changes some bodies of some units. Conversely, if a program that does
24282 not follow this rule happens to be safe at some point, this state of affairs
24283 may deteriorate silently as a result of maintenance changes.
24285 You may have noticed that the above discussion did not mention
24286 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
24287 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
24288 code in the body makes calls to some other unit, so it is still necessary
24289 to use @code{Elaborate_All} on such units.
24291 @node Controlling Elaboration in GNAT - Internal Calls
24292 @section Controlling Elaboration in GNAT - Internal Calls
24294 @noindent
24295 In the case of internal calls, i.e., calls within a single package, the
24296 programmer has full control over the order of elaboration, and it is up
24297 to the programmer to elaborate declarations in an appropriate order. For
24298 example writing:
24300 @smallexample @c ada
24301 @group
24302 @cartouche
24303 function One return Float;
24305 Q : Float := One;
24307 function One return Float is
24308 begin
24309      return 1.0;
24310 end One;
24311 @end cartouche
24312 @end group
24313 @end smallexample
24315 @noindent
24316 will obviously raise @code{Program_Error} at run time, because function
24317 One will be called before its body is elaborated. In this case GNAT will
24318 generate a warning that the call will raise @code{Program_Error}:
24320 @smallexample
24321 @group
24322 @cartouche
24323  1. procedure y is
24324  2.    function One return Float;
24325  3.
24326  4.    Q : Float := One;
24327                     |
24328     >>> warning: cannot call "One" before body is elaborated
24329     >>> warning: Program_Error will be raised at run time
24331  5.
24332  6.    function One return Float is
24333  7.    begin
24334  8.         return 1.0;
24335  9.    end One;
24337 11. begin
24338 12.    null;
24339 13. end;
24340 @end cartouche
24341 @end group
24342 @end smallexample
24344 @noindent
24345 Note that in this particular case, it is likely that the call is safe, because
24346 the function @code{One} does not access any global variables.
24347 Nevertheless in Ada, we do not want the validity of the check to depend on
24348 the contents of the body (think about the separate compilation case), so this
24349 is still wrong, as we discussed in the previous sections.
24351 The error is easily corrected by rearranging the declarations so that the
24352 body of @code{One} appears before the declaration containing the call
24353 (note that in Ada 95 and Ada 2005,
24354 declarations can appear in any order, so there is no restriction that
24355 would prevent this reordering, and if we write:
24357 @smallexample @c ada
24358 @group
24359 @cartouche
24360 function One return Float;
24362 function One return Float is
24363 begin
24364      return 1.0;
24365 end One;
24367 Q : Float := One;
24368 @end cartouche
24369 @end group
24370 @end smallexample
24372 @noindent
24373 then all is well, no warning is generated, and no
24374 @code{Program_Error} exception
24375 will be raised.
24376 Things are more complicated when a chain of subprograms is executed:
24378 @smallexample @c ada
24379 @group
24380 @cartouche
24381 function A return Integer;
24382 function B return Integer;
24383 function C return Integer;
24385 function B return Integer is begin return A; end;
24386 function C return Integer is begin return B; end;
24388 X : Integer := C;
24390 function A return Integer is begin return 1; end;
24391 @end cartouche
24392 @end group
24393 @end smallexample
24395 @noindent
24396 Now the call to @code{C}
24397 at elaboration time in the declaration of @code{X} is correct, because
24398 the body of @code{C} is already elaborated,
24399 and the call to @code{B} within the body of
24400 @code{C} is correct, but the call
24401 to @code{A} within the body of @code{B} is incorrect, because the body
24402 of @code{A} has not been elaborated, so @code{Program_Error}
24403 will be raised on the call to @code{A}.
24404 In this case GNAT will generate a
24405 warning that @code{Program_Error} may be
24406 raised at the point of the call. Let's look at the warning:
24408 @smallexample
24409 @group
24410 @cartouche
24411  1. procedure x is
24412  2.    function A return Integer;
24413  3.    function B return Integer;
24414  4.    function C return Integer;
24415  5.
24416  6.    function B return Integer is begin return A; end;
24417                                                     |
24418     >>> warning: call to "A" before body is elaborated may
24419                  raise Program_Error
24420     >>> warning: "B" called at line 7
24421     >>> warning: "C" called at line 9
24423  7.    function C return Integer is begin return B; end;
24424  8.
24425  9.    X : Integer := C;
24427 11.    function A return Integer is begin return 1; end;
24429 13. begin
24430 14.    null;
24431 15. end;
24432 @end cartouche
24433 @end group
24434 @end smallexample
24436 @noindent
24437 Note that the message here says ``may raise'', instead of the direct case,
24438 where the message says ``will be raised''. That's because whether
24439 @code{A} is
24440 actually called depends in general on run-time flow of control.
24441 For example, if the body of @code{B} said
24443 @smallexample @c ada
24444 @group
24445 @cartouche
24446 function B return Integer is
24447 begin
24448    if some-condition-depending-on-input-data then
24449       return A;
24450    else
24451       return 1;
24452    end if;
24453 end B;
24454 @end cartouche
24455 @end group
24456 @end smallexample
24458 @noindent
24459 then we could not know until run time whether the incorrect call to A would
24460 actually occur, so @code{Program_Error} might
24461 or might not be raised. It is possible for a compiler to
24462 do a better job of analyzing bodies, to
24463 determine whether or not @code{Program_Error}
24464 might be raised, but it certainly
24465 couldn't do a perfect job (that would require solving the halting problem
24466 and is provably impossible), and because this is a warning anyway, it does
24467 not seem worth the effort to do the analysis. Cases in which it
24468 would be relevant are rare.
24470 In practice, warnings of either of the forms given
24471 above will usually correspond to
24472 real errors, and should be examined carefully and eliminated.
24473 In the rare case where a warning is bogus, it can be suppressed by any of
24474 the following methods:
24476 @itemize @bullet
24477 @item
24478 Compile with the @option{-gnatws} switch set
24480 @item
24481 Suppress @code{Elaboration_Check} for the called subprogram
24483 @item
24484 Use pragma @code{Warnings_Off} to turn warnings off for the call
24485 @end itemize
24487 @noindent
24488 For the internal elaboration check case,
24489 GNAT by default generates the
24490 necessary run-time checks to ensure
24491 that @code{Program_Error} is raised if any
24492 call fails an elaboration check. Of course this can only happen if a
24493 warning has been issued as described above. The use of pragma
24494 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24495 some of these checks, meaning that it may be possible (but is not
24496 guaranteed) for a program to be able to call a subprogram whose body
24497 is not yet elaborated, without raising a @code{Program_Error} exception.
24499 @node Controlling Elaboration in GNAT - External Calls
24500 @section Controlling Elaboration in GNAT - External Calls
24502 @noindent
24503 The previous section discussed the case in which the execution of a
24504 particular thread of elaboration code occurred entirely within a
24505 single unit. This is the easy case to handle, because a programmer
24506 has direct and total control over the order of elaboration, and
24507 furthermore, checks need only be generated in cases which are rare
24508 and which the compiler can easily detect.
24509 The situation is more complex when separate compilation is taken into account.
24510 Consider the following:
24512 @smallexample @c ada
24513 @cartouche
24514 @group
24515 package Math is
24516    function Sqrt (Arg : Float) return Float;
24517 end Math;
24519 package body Math is
24520    function Sqrt (Arg : Float) return Float is
24521    begin
24522          @dots{}
24523    end Sqrt;
24524 end Math;
24525 @end group
24526 @group
24527 with Math;
24528 package Stuff is
24529    X : Float := Math.Sqrt (0.5);
24530 end Stuff;
24532 with Stuff;
24533 procedure Main is
24534 begin
24535    @dots{}
24536 end Main;
24537 @end group
24538 @end cartouche
24539 @end smallexample
24541 @noindent
24542 where @code{Main} is the main program. When this program is executed, the
24543 elaboration code must first be executed, and one of the jobs of the
24544 binder is to determine the order in which the units of a program are
24545 to be elaborated. In this case we have four units: the spec and body
24546 of @code{Math},
24547 the spec of @code{Stuff} and the body of @code{Main}).
24548 In what order should the four separate sections of elaboration code
24549 be executed?
24551 There are some restrictions in the order of elaboration that the binder
24552 can choose. In particular, if unit U has a @code{with}
24553 for a package @code{X}, then you
24554 are assured that the spec of @code{X}
24555 is elaborated before U , but you are
24556 not assured that the body of @code{X}
24557 is elaborated before U.
24558 This means that in the above case, the binder is allowed to choose the
24559 order:
24561 @smallexample
24562 spec of Math
24563 spec of Stuff
24564 body of Math
24565 body of Main
24566 @end smallexample
24568 @noindent
24569 but that's not good, because now the call to @code{Math.Sqrt}
24570 that happens during
24571 the elaboration of the @code{Stuff}
24572 spec happens before the body of @code{Math.Sqrt} is
24573 elaborated, and hence causes @code{Program_Error} exception to be raised.
24574 At first glance, one might say that the binder is misbehaving, because
24575 obviously you want to elaborate the body of something you @code{with}
24576 first, but
24577 that is not a general rule that can be followed in all cases. Consider
24579 @smallexample @c ada
24580 @group
24581 @cartouche
24582 package X is @dots{}
24584 package Y is @dots{}
24586 with X;
24587 package body Y is @dots{}
24589 with Y;
24590 package body X is @dots{}
24591 @end cartouche
24592 @end group
24593 @end smallexample
24595 @noindent
24596 This is a common arrangement, and, apart from the order of elaboration
24597 problems that might arise in connection with elaboration code, this works fine.
24598 A rule that says that you must first elaborate the body of anything you
24599 @code{with} cannot work in this case:
24600 the body of @code{X} @code{with}'s @code{Y},
24601 which means you would have to
24602 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24603 which means
24604 you have to elaborate the body of @code{X} first, but @dots{} and we have a
24605 loop that cannot be broken.
24607 It is true that the binder can in many cases guess an order of elaboration
24608 that is unlikely to cause a @code{Program_Error}
24609 exception to be raised, and it tries to do so (in the
24610 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24611 by default
24612 elaborate the body of @code{Math} right after its spec, so all will be well).
24614 However, a program that blindly relies on the binder to be helpful can
24615 get into trouble, as we discussed in the previous sections, so
24616 GNAT
24617 provides a number of facilities for assisting the programmer in
24618 developing programs that are robust with respect to elaboration order.
24620 @node Default Behavior in GNAT - Ensuring Safety
24621 @section Default Behavior in GNAT - Ensuring Safety
24623 @noindent
24624 The default behavior in GNAT ensures elaboration safety. In its
24625 default mode GNAT implements the
24626 rule we previously described as the right approach. Let's restate it:
24628 @itemize
24629 @item
24630 @emph{If a unit has elaboration code that can directly or indirectly make a
24631 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24632 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24633 does not have pragma @code{Pure} or
24634 @code{Preelaborate}, then the client should have an
24635 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24637 @emph{In the case of instantiating a generic subprogram, it is always
24638 sufficient to have only an @code{Elaborate} pragma for the
24639 @code{with}'ed unit.}
24640 @end itemize
24642 @noindent
24643 By following this rule a client is assured that calls and instantiations
24644 can be made without risk of an exception.
24646 In this mode GNAT traces all calls that are potentially made from
24647 elaboration code, and puts in any missing implicit @code{Elaborate}
24648 and @code{Elaborate_All} pragmas.
24649 The advantage of this approach is that no elaboration problems
24650 are possible if the binder can find an elaboration order that is
24651 consistent with these implicit @code{Elaborate} and
24652 @code{Elaborate_All} pragmas. The
24653 disadvantage of this approach is that no such order may exist.
24655 If the binder does not generate any diagnostics, then it means that it has
24656 found an elaboration order that is guaranteed to be safe. However, the binder
24657 may still be relying on implicitly generated @code{Elaborate} and
24658 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24659 guaranteed.
24661 If it is important to guarantee portability, then the compilations should
24662 use the
24663 @option{-gnatwl}
24664 (warn on elaboration problems) switch. This will cause warning messages
24665 to be generated indicating the missing @code{Elaborate} and
24666 @code{Elaborate_All} pragmas.
24667 Consider the following source program:
24669 @smallexample @c ada
24670 @group
24671 @cartouche
24672 with k;
24673 package j is
24674   m : integer := k.r;
24675 end;
24676 @end cartouche
24677 @end group
24678 @end smallexample
24680 @noindent
24681 where it is clear that there
24682 should be a pragma @code{Elaborate_All}
24683 for unit @code{k}. An implicit pragma will be generated, and it is
24684 likely that the binder will be able to honor it. However, if you want
24685 to port this program to some other Ada compiler than GNAT.
24686 it is safer to include the pragma explicitly in the source. If this
24687 unit is compiled with the
24688 @option{-gnatwl}
24689 switch, then the compiler outputs a warning:
24691 @smallexample
24692 @group
24693 @cartouche
24694 1. with k;
24695 2. package j is
24696 3.   m : integer := k.r;
24697                      |
24698    >>> warning: call to "r" may raise Program_Error
24699    >>> warning: missing pragma Elaborate_All for "k"
24701 4. end;
24702 @end cartouche
24703 @end group
24704 @end smallexample
24706 @noindent
24707 and these warnings can be used as a guide for supplying manually
24708 the missing pragmas. It is usually a bad idea to use this warning
24709 option during development. That's because it will warn you when
24710 you need to put in a pragma, but cannot warn you when it is time
24711 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24712 unnecessary dependencies and even false circularities.
24714 This default mode is more restrictive than the Ada Reference
24715 Manual, and it is possible to construct programs which will compile
24716 using the dynamic model described there, but will run into a
24717 circularity using the safer static model we have described.
24719 Of course any Ada compiler must be able to operate in a mode
24720 consistent with the requirements of the Ada Reference Manual,
24721 and in particular must have the capability of implementing the
24722 standard dynamic model of elaboration with run-time checks.
24724 In GNAT, this standard mode can be achieved either by the use of
24725 the @option{-gnatE} switch on the compiler (@command{gcc} or
24726 @command{gnatmake}) command, or by the use of the configuration pragma:
24728 @smallexample @c ada
24729 pragma Elaboration_Checks (DYNAMIC);
24730 @end smallexample
24732 @noindent
24733 Either approach will cause the unit affected to be compiled using the
24734 standard dynamic run-time elaboration checks described in the Ada
24735 Reference Manual. The static model is generally preferable, since it
24736 is clearly safer to rely on compile and link time checks rather than
24737 run-time checks. However, in the case of legacy code, it may be
24738 difficult to meet the requirements of the static model. This
24739 issue is further discussed in
24740 @ref{What to Do If the Default Elaboration Behavior Fails}.
24742 Note that the static model provides a strict subset of the allowed
24743 behavior and programs of the Ada Reference Manual, so if you do
24744 adhere to the static model and no circularities exist,
24745 then you are assured that your program will
24746 work using the dynamic model, providing that you remove any
24747 pragma Elaborate statements from the source.
24749 @node Treatment of Pragma Elaborate
24750 @section Treatment of Pragma Elaborate
24751 @cindex Pragma Elaborate
24753 @noindent
24754 The use of @code{pragma Elaborate}
24755 should generally be avoided in Ada 95 and Ada 2005 programs,
24756 since there is no guarantee that transitive calls
24757 will be properly handled. Indeed at one point, this pragma was placed
24758 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24760 Now that's a bit restrictive. In practice, the case in which
24761 @code{pragma Elaborate} is useful is when the caller knows that there
24762 are no transitive calls, or that the called unit contains all necessary
24763 transitive @code{pragma Elaborate} statements, and legacy code often
24764 contains such uses.
24766 Strictly speaking the static mode in GNAT should ignore such pragmas,
24767 since there is no assurance at compile time that the necessary safety
24768 conditions are met. In practice, this would cause GNAT to be incompatible
24769 with correctly written Ada 83 code that had all necessary
24770 @code{pragma Elaborate} statements in place. Consequently, we made the
24771 decision that GNAT in its default mode will believe that if it encounters
24772 a @code{pragma Elaborate} then the programmer knows what they are doing,
24773 and it will trust that no elaboration errors can occur.
24775 The result of this decision is two-fold. First to be safe using the
24776 static mode, you should remove all @code{pragma Elaborate} statements.
24777 Second, when fixing circularities in existing code, you can selectively
24778 use @code{pragma Elaborate} statements to convince the static mode of
24779 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24780 statement.
24782 When using the static mode with @option{-gnatwl}, any use of
24783 @code{pragma Elaborate} will generate a warning about possible
24784 problems.
24786 @node Elaboration Issues for Library Tasks
24787 @section Elaboration Issues for Library Tasks
24788 @cindex Library tasks, elaboration issues
24789 @cindex Elaboration of library tasks
24791 @noindent
24792 In this section we examine special elaboration issues that arise for
24793 programs that declare library level tasks.
24795 Generally the model of execution of an Ada program is that all units are
24796 elaborated, and then execution of the program starts. However, the
24797 declaration of library tasks definitely does not fit this model. The
24798 reason for this is that library tasks start as soon as they are declared
24799 (more precisely, as soon as the statement part of the enclosing package
24800 body is reached), that is to say before elaboration
24801 of the program is complete. This means that if such a task calls a
24802 subprogram, or an entry in another task, the callee may or may not be
24803 elaborated yet, and in the standard
24804 Reference Manual model of dynamic elaboration checks, you can even
24805 get timing dependent Program_Error exceptions, since there can be
24806 a race between the elaboration code and the task code.
24808 The static model of elaboration in GNAT seeks to avoid all such
24809 dynamic behavior, by being conservative, and the conservative
24810 approach in this particular case is to assume that all the code
24811 in a task body is potentially executed at elaboration time if
24812 a task is declared at the library level.
24814 This can definitely result in unexpected circularities. Consider
24815 the following example
24817 @smallexample @c ada
24818 package Decls is
24819   task Lib_Task is
24820      entry Start;
24821   end Lib_Task;
24823   type My_Int is new Integer;
24825   function Ident (M : My_Int) return My_Int;
24826 end Decls;
24828 with Utils;
24829 package body Decls is
24830   task body Lib_Task is
24831   begin
24832      accept Start;
24833      Utils.Put_Val (2);
24834   end Lib_Task;
24836   function Ident (M : My_Int) return My_Int is
24837   begin
24838      return M;
24839   end Ident;
24840 end Decls;
24842 with Decls;
24843 package Utils is
24844   procedure Put_Val (Arg : Decls.My_Int);
24845 end Utils;
24847 with Text_IO;
24848 package body Utils is
24849   procedure Put_Val (Arg : Decls.My_Int) is
24850   begin
24851      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24852   end Put_Val;
24853 end Utils;
24855 with Decls;
24856 procedure Main is
24857 begin
24858    Decls.Lib_Task.Start;
24859 end;
24860 @end smallexample
24862 @noindent
24863 If the above example is compiled in the default static elaboration
24864 mode, then a circularity occurs. The circularity comes from the call
24865 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24866 this call occurs in elaboration code, we need an implicit pragma
24867 @code{Elaborate_All} for @code{Utils}. This means that not only must
24868 the spec and body of @code{Utils} be elaborated before the body
24869 of @code{Decls}, but also the spec and body of any unit that is
24870 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24871 the body of @code{Decls}. This is the transitive implication of
24872 pragma @code{Elaborate_All} and it makes sense, because in general
24873 the body of @code{Put_Val} might have a call to something in a
24874 @code{with'ed} unit.
24876 In this case, the body of Utils (actually its spec) @code{with's}
24877 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24878 must be elaborated before itself, in case there is a call from the
24879 body of @code{Utils}.
24881 Here is the exact chain of events we are worrying about:
24883 @enumerate
24884 @item
24885 In the body of @code{Decls} a call is made from within the body of a library
24886 task to a subprogram in the package @code{Utils}. Since this call may
24887 occur at elaboration time (given that the task is activated at elaboration
24888 time), we have to assume the worst, i.e., that the
24889 call does happen at elaboration time.
24891 @item
24892 This means that the body and spec of @code{Util} must be elaborated before
24893 the body of @code{Decls} so that this call does not cause an access before
24894 elaboration.
24896 @item
24897 Within the body of @code{Util}, specifically within the body of
24898 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24899 by this package.
24901 @item
24902 One such @code{with}'ed package is package @code{Decls}, so there
24903 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24904 In fact there is such a call in this example, but we would have to
24905 assume that there was such a call even if it were not there, since
24906 we are not supposed to write the body of @code{Decls} knowing what
24907 is in the body of @code{Utils}; certainly in the case of the
24908 static elaboration model, the compiler does not know what is in
24909 other bodies and must assume the worst.
24911 @item
24912 This means that the spec and body of @code{Decls} must also be
24913 elaborated before we elaborate the unit containing the call, but
24914 that unit is @code{Decls}! This means that the body of @code{Decls}
24915 must be elaborated before itself, and that's a circularity.
24916 @end enumerate
24918 @noindent
24919 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24920 the body of @code{Decls} you will get a true Ada Reference Manual
24921 circularity that makes the program illegal.
24923 In practice, we have found that problems with the static model of
24924 elaboration in existing code often arise from library tasks, so
24925 we must address this particular situation.
24927 Note that if we compile and run the program above, using the dynamic model of
24928 elaboration (that is to say use the @option{-gnatE} switch),
24929 then it compiles, binds,
24930 links, and runs, printing the expected result of 2. Therefore in some sense
24931 the circularity here is only apparent, and we need to capture
24932 the properties of this program that  distinguish it from other library-level
24933 tasks that have real elaboration problems.
24935 We have four possible answers to this question:
24937 @itemize @bullet
24939 @item
24940 Use the dynamic model of elaboration.
24942 If we use the @option{-gnatE} switch, then as noted above, the program works.
24943 Why is this? If we examine the task body, it is apparent that the task cannot
24944 proceed past the
24945 @code{accept} statement until after elaboration has been completed, because
24946 the corresponding entry call comes from the main program, not earlier.
24947 This is why the dynamic model works here. But that's really giving
24948 up on a precise analysis, and we prefer to take this approach only if we cannot
24949 solve the
24950 problem in any other manner. So let us examine two ways to reorganize
24951 the program to avoid the potential elaboration problem.
24953 @item
24954 Split library tasks into separate packages.
24956 Write separate packages, so that library tasks are isolated from
24957 other declarations as much as possible. Let us look at a variation on
24958 the above program.
24960 @smallexample @c ada
24961 package Decls1 is
24962   task Lib_Task is
24963      entry Start;
24964   end Lib_Task;
24965 end Decls1;
24967 with Utils;
24968 package body Decls1 is
24969   task body Lib_Task is
24970   begin
24971      accept Start;
24972      Utils.Put_Val (2);
24973   end Lib_Task;
24974 end Decls1;
24976 package Decls2 is
24977   type My_Int is new Integer;
24978   function Ident (M : My_Int) return My_Int;
24979 end Decls2;
24981 with Utils;
24982 package body Decls2 is
24983   function Ident (M : My_Int) return My_Int is
24984   begin
24985      return M;
24986   end Ident;
24987 end Decls2;
24989 with Decls2;
24990 package Utils is
24991   procedure Put_Val (Arg : Decls2.My_Int);
24992 end Utils;
24994 with Text_IO;
24995 package body Utils is
24996   procedure Put_Val (Arg : Decls2.My_Int) is
24997   begin
24998      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24999   end Put_Val;
25000 end Utils;
25002 with Decls1;
25003 procedure Main is
25004 begin
25005    Decls1.Lib_Task.Start;
25006 end;
25007 @end smallexample
25009 @noindent
25010 All we have done is to split @code{Decls} into two packages, one
25011 containing the library task, and one containing everything else. Now
25012 there is no cycle, and the program compiles, binds, links and executes
25013 using the default static model of elaboration.
25015 @item
25016 Declare separate task types.
25018 A significant part of the problem arises because of the use of the
25019 single task declaration form. This means that the elaboration of
25020 the task type, and the elaboration of the task itself (i.e.@: the
25021 creation of the task) happen at the same time. A good rule
25022 of style in Ada is to always create explicit task types. By
25023 following the additional step of placing task objects in separate
25024 packages from the task type declaration, many elaboration problems
25025 are avoided. Here is another modified example of the example program:
25027 @smallexample @c ada
25028 package Decls is
25029   task type Lib_Task_Type is
25030      entry Start;
25031   end Lib_Task_Type;
25033   type My_Int is new Integer;
25035   function Ident (M : My_Int) return My_Int;
25036 end Decls;
25038 with Utils;
25039 package body Decls is
25040   task body Lib_Task_Type is
25041   begin
25042      accept Start;
25043      Utils.Put_Val (2);
25044   end Lib_Task_Type;
25046   function Ident (M : My_Int) return My_Int is
25047   begin
25048      return M;
25049   end Ident;
25050 end Decls;
25052 with Decls;
25053 package Utils is
25054   procedure Put_Val (Arg : Decls.My_Int);
25055 end Utils;
25057 with Text_IO;
25058 package body Utils is
25059   procedure Put_Val (Arg : Decls.My_Int) is
25060   begin
25061      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25062   end Put_Val;
25063 end Utils;
25065 with Decls;
25066 package Declst is
25067    Lib_Task : Decls.Lib_Task_Type;
25068 end Declst;
25070 with Declst;
25071 procedure Main is
25072 begin
25073    Declst.Lib_Task.Start;
25074 end;
25075 @end smallexample
25077 @noindent
25078 What we have done here is to replace the @code{task} declaration in
25079 package @code{Decls} with a @code{task type} declaration. Then we
25080 introduce a separate package @code{Declst} to contain the actual
25081 task object. This separates the elaboration issues for
25082 the @code{task type}
25083 declaration, which causes no trouble, from the elaboration issues
25084 of the task object, which is also unproblematic, since it is now independent
25085 of the elaboration of  @code{Utils}.
25086 This separation of concerns also corresponds to
25087 a generally sound engineering principle of separating declarations
25088 from instances. This version of the program also compiles, binds, links,
25089 and executes, generating the expected output.
25091 @item
25092 Use No_Entry_Calls_In_Elaboration_Code restriction.
25093 @cindex No_Entry_Calls_In_Elaboration_Code
25095 The previous two approaches described how a program can be restructured
25096 to avoid the special problems caused by library task bodies. in practice,
25097 however, such restructuring may be difficult to apply to existing legacy code,
25098 so we must consider solutions that do not require massive rewriting.
25100 Let us consider more carefully why our original sample program works
25101 under the dynamic model of elaboration. The reason is that the code
25102 in the task body blocks immediately on the @code{accept}
25103 statement. Now of course there is nothing to prohibit elaboration
25104 code from making entry calls (for example from another library level task),
25105 so we cannot tell in isolation that
25106 the task will not execute the accept statement  during elaboration.
25108 However, in practice it is very unusual to see elaboration code
25109 make any entry calls, and the pattern of tasks starting
25110 at elaboration time and then immediately blocking on @code{accept} or
25111 @code{select} statements is very common. What this means is that
25112 the compiler is being too pessimistic when it analyzes the
25113 whole package body as though it might be executed at elaboration
25114 time.
25116 If we know that the elaboration code contains no entry calls, (a very safe
25117 assumption most of the time, that could almost be made the default
25118 behavior), then we can compile all units of the program under control
25119 of the following configuration pragma:
25121 @smallexample
25122 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
25123 @end smallexample
25125 @noindent
25126 This pragma can be placed in the @file{gnat.adc} file in the usual
25127 manner. If we take our original unmodified program and compile it
25128 in the presence of a @file{gnat.adc} containing the above pragma,
25129 then once again, we can compile, bind, link, and execute, obtaining
25130 the expected result. In the presence of this pragma, the compiler does
25131 not trace calls in a task body, that appear after the first @code{accept}
25132 or @code{select} statement, and therefore does not report a potential
25133 circularity in the original program.
25135 The compiler will check to the extent it can that the above
25136 restriction is not violated, but it is not always possible to do a
25137 complete check at compile time, so it is important to use this
25138 pragma only if the stated restriction is in fact met, that is to say
25139 no task receives an entry call before elaboration of all units is completed.
25141 @end itemize
25143 @node Mixing Elaboration Models
25144 @section Mixing Elaboration Models
25145 @noindent
25146 So far, we have assumed that the entire program is either compiled
25147 using the dynamic model or static model, ensuring consistency. It
25148 is possible to mix the two models, but rules have to be followed
25149 if this mixing is done to ensure that elaboration checks are not
25150 omitted.
25152 The basic rule is that @emph{a unit compiled with the static model cannot
25153 be @code{with'ed} by a unit compiled with the dynamic model}. The
25154 reason for this is that in the static model, a unit assumes that
25155 its clients guarantee to use (the equivalent of) pragma
25156 @code{Elaborate_All} so that no elaboration checks are required
25157 in inner subprograms, and this assumption is violated if the
25158 client is compiled with dynamic checks.
25160 The precise rule is as follows. A unit that is compiled with dynamic
25161 checks can only @code{with} a unit that meets at least one of the
25162 following criteria:
25164 @itemize @bullet
25166 @item
25167 The @code{with'ed} unit is itself compiled with dynamic elaboration
25168 checks (that is with the @option{-gnatE} switch.
25170 @item
25171 The @code{with'ed} unit is an internal GNAT implementation unit from
25172 the System, Interfaces, Ada, or GNAT hierarchies.
25174 @item
25175 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25177 @item
25178 The @code{with'ing} unit (that is the client) has an explicit pragma
25179 @code{Elaborate_All} for the @code{with'ed} unit.
25181 @end itemize
25183 @noindent
25184 If this rule is violated, that is if a unit with dynamic elaboration
25185 checks @code{with's} a unit that does not meet one of the above four
25186 criteria, then the binder (@code{gnatbind}) will issue a warning
25187 similar to that in the following example:
25189 @smallexample
25190 warning: "x.ads" has dynamic elaboration checks and with's
25191 warning:   "y.ads" which has static elaboration checks
25192 @end smallexample
25194 @noindent
25195 These warnings indicate that the rule has been violated, and that as a result
25196 elaboration checks may be missed in the resulting executable file.
25197 This warning may be suppressed using the @option{-ws} binder switch
25198 in the usual manner.
25200 One useful application of this mixing rule is in the case of a subsystem
25201 which does not itself @code{with} units from the remainder of the
25202 application. In this case, the entire subsystem can be compiled with
25203 dynamic checks to resolve a circularity in the subsystem, while
25204 allowing the main application that uses this subsystem to be compiled
25205 using the more reliable default static model.
25207 @node What to Do If the Default Elaboration Behavior Fails
25208 @section What to Do If the Default Elaboration Behavior Fails
25210 @noindent
25211 If the binder cannot find an acceptable order, it outputs detailed
25212 diagnostics. For example:
25213 @smallexample
25214 @group
25215 @iftex
25216 @leftskip=0cm
25217 @end iftex
25218 error: elaboration circularity detected
25219 info:   "proc (body)" must be elaborated before "pack (body)"
25220 info:     reason: Elaborate_All probably needed in unit "pack (body)"
25221 info:     recompile "pack (body)" with -gnatwl
25222 info:                             for full details
25223 info:       "proc (body)"
25224 info:         is needed by its spec:
25225 info:       "proc (spec)"
25226 info:         which is withed by:
25227 info:       "pack (body)"
25228 info:  "pack (body)" must be elaborated before "proc (body)"
25229 info:     reason: pragma Elaborate in unit "proc (body)"
25230 @end group
25232 @end smallexample
25234 @noindent
25235 In this case we have a cycle that the binder cannot break. On the one
25236 hand, there is an explicit pragma Elaborate in @code{proc} for
25237 @code{pack}. This means that the body of @code{pack} must be elaborated
25238 before the body of @code{proc}. On the other hand, there is elaboration
25239 code in @code{pack} that calls a subprogram in @code{proc}. This means
25240 that for maximum safety, there should really be a pragma
25241 Elaborate_All in @code{pack} for @code{proc} which would require that
25242 the body of @code{proc} be elaborated before the body of
25243 @code{pack}. Clearly both requirements cannot be satisfied.
25244 Faced with a circularity of this kind, you have three different options.
25246 @table @asis
25247 @item Fix the program
25248 The most desirable option from the point of view of long-term maintenance
25249 is to rearrange the program so that the elaboration problems are avoided.
25250 One useful technique is to place the elaboration code into separate
25251 child packages. Another is to move some of the initialization code to
25252 explicitly called subprograms, where the program controls the order
25253 of initialization explicitly. Although this is the most desirable option,
25254 it may be impractical and involve too much modification, especially in
25255 the case of complex legacy code.
25257 @item Perform dynamic checks
25258 If the compilations are done using the
25259 @option{-gnatE}
25260 (dynamic elaboration check) switch, then GNAT behaves in a quite different
25261 manner. Dynamic checks are generated for all calls that could possibly result
25262 in raising an exception. With this switch, the compiler does not generate
25263 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
25264 exactly as specified in the @cite{Ada Reference Manual}.
25265 The binder will generate
25266 an executable program that may or may not raise @code{Program_Error}, and then
25267 it is the programmer's job to ensure that it does not raise an exception. Note
25268 that it is important to compile all units with the switch, it cannot be used
25269 selectively.
25271 @item Suppress checks
25272 The drawback of dynamic checks is that they generate a
25273 significant overhead at run time, both in space and time. If you
25274 are absolutely sure that your program cannot raise any elaboration
25275 exceptions, and you still want to use the dynamic elaboration model,
25276 then you can use the configuration pragma
25277 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
25278 example this pragma could be placed in the @file{gnat.adc} file.
25280 @item Suppress checks selectively
25281 When you know that certain calls or instantiations in elaboration code cannot
25282 possibly lead to an elaboration error, and the binder nevertheless complains
25283 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
25284 elaboration circularities, it is possible to remove those warnings locally and
25285 obtain a program that will bind. Clearly this can be unsafe, and it is the
25286 responsibility of the programmer to make sure that the resulting program has no
25287 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
25288 used with different granularity to suppress warnings and break elaboration
25289 circularities:
25291 @itemize @bullet
25292 @item
25293 Place the pragma that names the called subprogram in the declarative part
25294 that contains the call.
25296 @item
25297 Place the pragma in the declarative part, without naming an entity. This
25298 disables warnings on all calls in the corresponding  declarative region.
25300 @item
25301 Place the pragma in the package spec that declares the called subprogram,
25302 and name the subprogram. This disables warnings on all elaboration calls to
25303 that subprogram.
25305 @item
25306 Place the pragma in the package spec that declares the called subprogram,
25307 without naming any entity. This disables warnings on all elaboration calls to
25308 all subprograms declared in this spec.
25310 @item Use Pragma Elaborate
25311 As previously described in section @xref{Treatment of Pragma Elaborate},
25312 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
25313 that no elaboration checks are required on calls to the designated unit.
25314 There may be cases in which the caller knows that no transitive calls
25315 can occur, so that a @code{pragma Elaborate} will be sufficient in a
25316 case where @code{pragma Elaborate_All} would cause a circularity.
25317 @end itemize
25319 @noindent
25320 These five cases are listed in order of decreasing safety, and therefore
25321 require increasing programmer care in their application. Consider the
25322 following program:
25324 @smallexample @c adanocomment
25325 package Pack1 is
25326   function F1 return Integer;
25327   X1 : Integer;
25328 end Pack1;
25330 package Pack2 is
25331   function F2 return Integer;
25332   function Pure (x : integer) return integer;
25333   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
25334   --  pragma Suppress (Elaboration_Check);              -- (4)
25335 end Pack2;
25337 with Pack2;
25338 package body Pack1 is
25339   function F1 return Integer is
25340   begin
25341     return 100;
25342   end F1;
25343   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
25344 begin
25345   declare
25346     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
25347     --  pragma Suppress(Elaboration_Check);             -- (2)
25348   begin
25349     X1 := Pack2.F2 + 1;                --  Elab. call (2)
25350   end;
25351 end Pack1;
25353 with Pack1;
25354 package body Pack2 is
25355   function F2 return Integer is
25356   begin
25357      return Pack1.F1;
25358   end F2;
25359   function Pure (x : integer) return integer is
25360   begin
25361      return x ** 3 - 3 * x;
25362   end;
25363 end Pack2;
25365 with Pack1, Ada.Text_IO;
25366 procedure Proc3 is
25367 begin
25368   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25369 end Proc3;
25370 @end smallexample
25371 In the absence of any pragmas, an attempt to bind this program produces
25372 the following diagnostics:
25373 @smallexample
25374 @group
25375 @iftex
25376 @leftskip=.5cm
25377 @end iftex
25378 error: elaboration circularity detected
25379 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
25380 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
25381 info:       recompile "pack1 (body)" with -gnatwl for full details
25382 info:          "pack1 (body)"
25383 info:             must be elaborated along with its spec:
25384 info:          "pack1 (spec)"
25385 info:             which is withed by:
25386 info:          "pack2 (body)"
25387 info:             which must be elaborated along with its spec:
25388 info:          "pack2 (spec)"
25389 info:             which is withed by:
25390 info:          "pack1 (body)"
25391 @end group
25392 @end smallexample
25393 The sources of the circularity are the two calls to @code{Pack2.Pure} and
25394 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
25395 F2 is safe, even though F2 calls F1, because the call appears after the
25396 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
25397 remove the warning on the call. It is also possible to use pragma (2)
25398 because there are no other potentially unsafe calls in the block.
25400 @noindent
25401 The call to @code{Pure} is safe because this function does not depend on the
25402 state of @code{Pack2}. Therefore any call to this function is safe, and it
25403 is correct to place pragma (3) in the corresponding package spec.
25405 @noindent
25406 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
25407 warnings on all calls to functions declared therein. Note that this is not
25408 necessarily safe, and requires more detailed examination of the subprogram
25409 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
25410 be already elaborated.
25411 @end table
25413 @noindent
25414 It is hard to generalize on which of these four approaches should be
25415 taken. Obviously if it is possible to fix the program so that the default
25416 treatment works, this is preferable, but this may not always be practical.
25417 It is certainly simple enough to use
25418 @option{-gnatE}
25419 but the danger in this case is that, even if the GNAT binder
25420 finds a correct elaboration order, it may not always do so,
25421 and certainly a binder from another Ada compiler might not. A
25422 combination of testing and analysis (for which the warnings generated
25423 with the
25424 @option{-gnatwl}
25425 switch can be useful) must be used to ensure that the program is free
25426 of errors. One switch that is useful in this testing is the
25427 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
25428 switch for
25429 @code{gnatbind}.
25430 Normally the binder tries to find an order that has the best chance
25431 of avoiding elaboration problems. However, if this switch is used, the binder
25432 plays a devil's advocate role, and tries to choose the order that
25433 has the best chance of failing. If your program works even with this
25434 switch, then it has a better chance of being error free, but this is still
25435 not a guarantee.
25437 For an example of this approach in action, consider the C-tests (executable
25438 tests) from the ACVC suite. If these are compiled and run with the default
25439 treatment, then all but one of them succeed without generating any error
25440 diagnostics from the binder. However, there is one test that fails, and
25441 this is not surprising, because the whole point of this test is to ensure
25442 that the compiler can handle cases where it is impossible to determine
25443 a correct order statically, and it checks that an exception is indeed
25444 raised at run time.
25446 This one test must be compiled and run using the
25447 @option{-gnatE}
25448 switch, and then it passes. Alternatively, the entire suite can
25449 be run using this switch. It is never wrong to run with the dynamic
25450 elaboration switch if your code is correct, and we assume that the
25451 C-tests are indeed correct (it is less efficient, but efficiency is
25452 not a factor in running the ACVC tests.)
25454 @node Elaboration for Dispatching Calls
25455 @section Elaboration for Dispatching Calls
25456 @cindex Dispatching calls
25458 @noindent
25459 In rare cases, the static elaboration model fails to prevent
25460 dispatching calls to not-yet-elaborated subprograms. In such cases, we
25461 fall back to run-time checks; premature calls to any primitive
25462 operation of a tagged type before the body of the operation has been
25463 elaborated will raise @code{Program_Error}.
25465 Access-to-subprogram types, however, are handled conservatively, and
25466 do not require run-time checks. This was not true in earlier versions
25467 of the compiler; you can use the @option{-gnatd.U} debug switch to
25468 revert to the old behavior if the new conservative behavior causes
25469 elaboration cycles.
25471 @node Summary of Procedures for Elaboration Control
25472 @section Summary of Procedures for Elaboration Control
25473 @cindex Elaboration control
25475 @noindent
25476 First, compile your program with the default options, using none of
25477 the special elaboration control switches. If the binder successfully
25478 binds your program, then you can be confident that, apart from issues
25479 raised by the use of access-to-subprogram types and dynamic dispatching,
25480 the program is free of elaboration errors. If it is important that the
25481 program be portable, then use the
25482 @option{-gnatwl}
25483 switch to generate warnings about missing @code{Elaborate} or
25484 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25486 If the program fails to bind using the default static elaboration
25487 handling, then you can fix the program to eliminate the binder
25488 message, or recompile the entire program with the
25489 @option{-gnatE} switch to generate dynamic elaboration checks,
25490 and, if you are sure there really are no elaboration problems,
25491 use a global pragma @code{Suppress (Elaboration_Check)}.
25493 @node Other Elaboration Order Considerations
25494 @section Other Elaboration Order Considerations
25495 @noindent
25496 This section has been entirely concerned with the issue of finding a valid
25497 elaboration order, as defined by the Ada Reference Manual. In a case
25498 where several elaboration orders are valid, the task is to find one
25499 of the possible valid elaboration orders (and the static model in GNAT
25500 will ensure that this is achieved).
25502 The purpose of the elaboration rules in the Ada Reference Manual is to
25503 make sure that no entity is accessed before it has been elaborated. For
25504 a subprogram, this means that the spec and body must have been elaborated
25505 before the subprogram is called. For an object, this means that the object
25506 must have been elaborated before its value is read or written. A violation
25507 of either of these two requirements is an access before elaboration order,
25508 and this section has been all about avoiding such errors.
25510 In the case where more than one order of elaboration is possible, in the
25511 sense that access before elaboration errors are avoided, then any one of
25512 the orders is ``correct'' in the sense that it meets the requirements of
25513 the Ada Reference Manual, and no such error occurs.
25515 However, it may be the case for a given program, that there are
25516 constraints on the order of elaboration that come not from consideration
25517 of avoiding elaboration errors, but rather from extra-lingual logic
25518 requirements. Consider this example:
25520 @smallexample @c ada
25521 with Init_Constants;
25522 package Constants is
25523    X : Integer := 0;
25524    Y : Integer := 0;
25525 end Constants;
25527 package Init_Constants is
25528    procedure P; -- require a body
25529 end Init_Constants;
25531 with Constants;
25532 package body Init_Constants is
25533    procedure P is begin null; end;
25534 begin
25535    Constants.X := 3;
25536    Constants.Y := 4;
25537 end Init_Constants;
25539 with Constants;
25540 package Calc is
25541    Z : Integer := Constants.X + Constants.Y;
25542 end Calc;
25544 with Calc;
25545 with Text_IO; use Text_IO;
25546 procedure Main is
25547 begin
25548    Put_Line (Calc.Z'Img);
25549 end Main;
25550 @end smallexample
25552 @noindent
25553 In this example, there is more than one valid order of elaboration. For
25554 example both the following are correct orders:
25556 @smallexample
25557 Init_Constants spec
25558 Constants spec
25559 Calc spec
25560 Init_Constants body
25561 Main body
25563   and
25565 Init_Constants spec
25566 Init_Constants body
25567 Constants spec
25568 Calc spec
25569 Main body
25570 @end smallexample
25572 @noindent
25573 There is no language rule to prefer one or the other, both are correct
25574 from an order of elaboration point of view. But the programmatic effects
25575 of the two orders are very different. In the first, the elaboration routine
25576 of @code{Calc} initializes @code{Z} to zero, and then the main program
25577 runs with this value of zero. But in the second order, the elaboration
25578 routine of @code{Calc} runs after the body of Init_Constants has set
25579 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25580 runs.
25582 One could perhaps by applying pretty clever non-artificial intelligence
25583 to the situation guess that it is more likely that the second order of
25584 elaboration is the one desired, but there is no formal linguistic reason
25585 to prefer one over the other. In fact in this particular case, GNAT will
25586 prefer the second order, because of the rule that bodies are elaborated
25587 as soon as possible, but it's just luck that this is what was wanted
25588 (if indeed the second order was preferred).
25590 If the program cares about the order of elaboration routines in a case like
25591 this, it is important to specify the order required. In this particular
25592 case, that could have been achieved by adding to the spec of Calc:
25594 @smallexample @c ada
25595 pragma Elaborate_All (Constants);
25596 @end smallexample
25598 @noindent
25599 which requires that the body (if any) and spec of @code{Constants},
25600 as well as the body and spec of any unit @code{with}'ed by
25601 @code{Constants} be elaborated before @code{Calc} is elaborated.
25603 Clearly no automatic method can always guess which alternative you require,
25604 and if you are working with legacy code that had constraints of this kind
25605 which were not properly specified by adding @code{Elaborate} or
25606 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25607 compilers can choose different orders.
25609 However, GNAT does attempt to diagnose the common situation where there
25610 are uninitialized variables in the visible part of a package spec, and the
25611 corresponding package body has an elaboration block that directly or
25612 indirectly initialized one or more of these variables. This is the situation
25613 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25614 a warning that suggests this addition if it detects this situation.
25616 The @code{gnatbind}
25617 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25618 out problems. This switch causes bodies to be elaborated as late as possible
25619 instead of as early as possible. In the example above, it would have forced
25620 the choice of the first elaboration order. If you get different results
25621 when using this switch, and particularly if one set of results is right,
25622 and one is wrong as far as you are concerned, it shows that you have some
25623 missing @code{Elaborate} pragmas. For the example above, we have the
25624 following output:
25626 @smallexample
25627 gnatmake -f -q main
25628 main
25630 gnatmake -f -q main -bargs -p
25631 main
25633 @end smallexample
25635 @noindent
25636 It is of course quite unlikely that both these results are correct, so
25637 it is up to you in a case like this to investigate the source of the
25638 difference, by looking at the two elaboration orders that are chosen,
25639 and figuring out which is correct, and then adding the necessary
25640 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25643 @c **********************************
25644 @node Overflow Check Handling in GNAT
25645 @appendix Overflow Check Handling in GNAT
25646 @cindex Overflow checks
25647 @cindex Checks (overflow)
25648 @c **********************************
25650 @menu
25651 * Background::
25652 * Overflow Checking Modes in GNAT::
25653 * Specifying the Desired Mode::
25654 * Default Settings::
25655 * Implementation Notes::
25656 @end menu
25659 @node Background
25660 @section Background
25662 @noindent
25663 Overflow checks are checks that the compiler may make to ensure
25664 that intermediate results are not out of range. For example:
25666 @smallexample @c ada
25667    A : Integer;
25668    ...
25669    A := A + 1;
25670 @end smallexample
25672 @noindent
25673 if @code{A} has the value @code{Integer'Last}, then the addition may cause
25674 overflow since the result is out of range of the type @code{Integer}.
25675 In this case @code{Constraint_Error} will be raised if checks are
25676 enabled.
25678 A trickier situation arises in examples like the following:
25680 @smallexample @c ada
25681   A, C : Integer;
25682   ...
25683   A := (A + 1) + C;
25684 @end smallexample
25686 @noindent
25687 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
25688 Now the final result of the expression on the right hand side is
25689 @code{Integer'Last} which is in range, but the question arises whether the
25690 intermediate addition of @code{(A + 1)} raises an overflow error.
25692 The (perhaps surprising) answer is that the Ada language
25693 definition does not answer this question. Instead it leaves
25694 it up to the implementation to do one of two things if overflow
25695 checks are enabled.
25697 @itemize @bullet
25698 @item
25699 raise an exception (@code{Constraint_Error}), or
25701 @item
25702 yield the correct mathematical result which is then used in
25703 subsequent operations.
25704 @end itemize
25706 @noindent
25707 If the compiler chooses the first approach, then the assignment of this
25708 example will indeed raise @code{Constraint_Error} if overflow checking is
25709 enabled, or result in erroneous execution if overflow checks are suppressed.
25711 But if the compiler
25712 chooses the second approach, then it can perform both additions yielding
25713 the correct mathematical result, which is in range, so no exception
25714 will be raised, and the right result is obtained, regardless of whether
25715 overflow checks are suppressed.
25717 Note that in the first example an
25718 exception will be raised in either case, since if the compiler
25719 gives the correct mathematical result for the addition, it will
25720 be out of range of the target type of the assignment, and thus
25721 fails the range check.
25723 This lack of specified behavior in the handling of overflow for
25724 intermediate results is a source of non-portability, and can thus
25725 be problematic when programs are ported. Most typically this arises
25726 in a situation where the original compiler did not raise an exception,
25727 and then the application is moved to a compiler where the check is
25728 performed on the intermediate result and an unexpected exception is
25729 raised.
25731 Furthermore, when using Ada 2012's preconditions and other
25732 assertion forms, another issue arises. Consider:
25734 @smallexample @c ada
25735      procedure P (A, B : Integer) with
25736        Pre => A + B <= Integer'Last;
25737 @end smallexample
25739 @noindent
25740 One often wants to regard arithmetic in a context like this from
25741 a mathematical point of view. So for example, if the two actual parameters
25742 for a call to @code{P} are both @code{Integer'Last}, then
25743 the precondition should be regarded as False. If we are executing
25744 in a mode with run-time checks enabled for preconditions, then we would
25745 like this precondition to fail, rather than raising an exception
25746 because of the intermediate overflow.
25748 However, the language definition leaves the specification of
25749 whether the above condition fails (raising @code{Assert_Error}) or
25750 causes an intermediate overflow (raising @code{Constraint_Error})
25751 up to the implementation.
25753 The situation is worse in a case such as the following:
25755 @smallexample @c ada
25756      procedure Q (A, B, C : Integer) with
25757        Pre => A + B + C <= Integer'Last;
25758 @end smallexample
25760 @noindent
25761 Consider the call
25763 @smallexample @c ada
25764      Q (A => Integer'Last, B => 1, C => -1);
25765 @end smallexample
25767 @noindent
25768 From a mathematical point of view the precondition
25769 is True, but at run time we may (but are not guaranteed to) get an
25770 exception raised because of the intermediate overflow (and we really
25771 would prefer this precondition to be considered True at run time).
25773 @node Overflow Checking Modes in GNAT
25774 @section Overflow Checking Modes in GNAT
25776 @noindent
25777 To deal with the portability issue, and with the problem of
25778 mathematical versus run-time intepretation of the expressions in
25779 assertions, GNAT provides comprehensive control over the handling
25780 of intermediate overflow. GNAT can operate in three modes, and
25781 furthemore, permits separate selection of operating modes for
25782 the expressions within assertions (here the term ``assertions''
25783 is used in the technical sense, which includes preconditions and so forth)
25784 and for expressions appearing outside assertions.
25786 The three modes are:
25788 @itemize @bullet
25789 @item   @i{Use base type for intermediate operations} (@code{STRICT})
25791      In this mode, all intermediate results for predefined arithmetic
25792      operators are computed using the base type, and the result must
25793      be in range of the base type. If this is not the
25794      case then either an exception is raised (if overflow checks are
25795      enabled) or the execution is erroneous (if overflow checks are suppressed).
25796      This is the normal default mode.
25798 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
25800      In this mode, the compiler attempts to avoid intermediate overflows by
25801      using a larger integer type, typically @code{Long_Long_Integer},
25802      as the type in which arithmetic is
25803      performed for predefined arithmetic operators. This may be slightly more
25804      expensive at
25805      run time (compared to suppressing intermediate overflow checks), though
25806      the cost is negligible on modern 64-bit machines. For the examples given
25807      earlier, no intermediate overflows would have resulted in exceptions,
25808      since the intermediate results are all in the range of
25809      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
25810      of GNAT). In addition, if checks are enabled, this reduces the number of
25811      checks that must be made, so this choice may actually result in an
25812      improvement in space and time behavior.
25814      However, there are cases where @code{Long_Long_Integer} is not large
25815      enough, consider the following example:
25817 @smallexample @c ada
25818        procedure R (A, B, C, D : Integer) with
25819          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
25820 @end smallexample
25822      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25823      Now the intermediate results are
25824      out of the range of @code{Long_Long_Integer} even though the final result
25825      is in range and the precondition is True (from a mathematical point
25826      of view). In such a case, operating in this mode, an overflow occurs
25827      for the intermediate computation (which is why this mode
25828      says @i{most} intermediate overflows are avoided). In this case,
25829      an exception is raised if overflow checks are enabled, and the
25830      execution is erroneous if overflow checks are suppressed.
25832 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
25834      In this mode, the compiler  avoids all intermediate overflows
25835      by using arbitrary precision arithmetic as required. In this
25836      mode, the above example with @code{A**2 * B**2} would
25837      not cause intermediate overflow, because the intermediate result
25838      would be evaluated using sufficient precision, and the result
25839      of evaluating the precondition would be True.
25841      This mode has the advantage of avoiding any intermediate
25842      overflows, but at the expense of significant run-time overhead,
25843      including the use of a library (included automatically in this
25844      mode) for multiple-precision arithmetic.
25846      This mode provides cleaner semantics for assertions, since now
25847      the run-time behavior emulates true arithmetic behavior for the
25848      predefined arithmetic operators, meaning that there is never a
25849      conflict between the mathematical view of the assertion, and its
25850      run-time behavior.
25852      Note that in this mode, the behavior is unaffected by whether or
25853      not overflow checks are suppressed, since overflow does not occur.
25854      It is possible for gigantic intermediate expressions to raise
25855      @code{Storage_Error} as a result of attempting to compute the
25856      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
25857      but overflow is impossible.
25860 @end itemize
25862 @noindent
25863   Note that these modes apply only to the evaluation of predefined
25864   arithmetic, membership, and comparison operators for signed integer
25865   aritmetic.
25867   For fixed-point arithmetic, checks can be suppressed. But if checks
25868   are enabled
25869   then fixed-point values are always checked for overflow against the
25870   base type for intermediate expressions (that is such checks always
25871   operate in the equivalent of @code{STRICT} mode).
25873   For floating-point, on nearly all architectures, @code{Machine_Overflows}
25874   is False, and IEEE infinities are generated, so overflow exceptions
25875   are never raised. If you want to avoid infinities, and check that
25876   final results of expressions are in range, then you can declare a
25877   constrained floating-point type, and range checks will be carried
25878   out in the normal manner (with infinite values always failing all
25879   range checks).
25882 @c -------------------------
25883 @node Specifying the Desired Mode
25884 @section Specifying the Desired Mode
25886 @noindent
25887 The desired mode of for handling intermediate overflow can be specified using
25888 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
25889 The pragma has the form
25890 @cindex pragma @code{Overflow_Mode}
25892 @smallexample @c ada
25893     pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
25894 @end smallexample
25896 @noindent
25897 where @code{MODE} is one of
25899 @itemize @bullet
25900 @item   @code{STRICT}:  intermediate overflows checked (using base type)
25901 @item   @code{MINIMIZED}: minimize intermediate overflows
25902 @item   @code{ELIMINATED}: eliminate intermediate overflows
25903 @end itemize
25905 @noindent
25906 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25907 @code{minimized} all have the same effect.
25909 If only the @code{General} parameter is present, then the given @code{MODE}
25910 applies
25911 to expressions both within and outside assertions. If both arguments
25912 are present, then @code{General} applies to expressions outside assertions,
25913 and @code{Assertions} applies to expressions within assertions. For example:
25915 @smallexample @c ada
25916    pragma Overflow_Mode
25917      (General => Minimized, Assertions => Eliminated);
25918 @end smallexample
25920 @noindent
25921 specifies that general expressions outside assertions be evaluated
25922 in ``minimize intermediate overflows'' mode, and expressions within
25923 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25924 This is often a reasonable choice, avoiding excessive overhead
25925 outside assertions, but assuring a high degree of portability
25926 when importing code from another compiler, while incurring
25927 the extra overhead for assertion expressions to ensure that
25928 the behavior at run time matches the expected mathematical
25929 behavior.
25931 The @code{Overflow_Mode} pragma has the same scoping and placement
25932 rules as pragma @code{Suppress}, so it can occur either as a
25933 configuration pragma, specifying a default for the whole
25934 program, or in a declarative scope, where it applies to the
25935 remaining declarations and statements in that scope.
25937 Note that pragma @code{Overflow_Mode} does not affect whether
25938 overflow checks are enabled or suppressed. It only controls the
25939 method used to compute intermediate values. To control whether
25940 overflow checking is enabled or suppressed, use pragma @code{Suppress}
25941 or @code{Unsuppress} in the usual manner
25943 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25944 can be used to control the checking mode default (which can be subsequently
25945 overridden using pragmas).
25946 @cindex @option{-gnato?} (gcc)
25947 @cindex @option{-gnato??} (gcc)
25949 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
25951 @itemize @bullet
25952 @item   @code{1}:
25953 use base type for intermediate operations (@code{STRICT})
25954 @item   @code{2}:
25955 minimize intermediate overflows (@code{MINIMIZED})
25956 @item   @code{3}:
25957 eliminate intermediate overflows (@code{ELIMINATED})
25958 @end itemize
25960 @noindent
25961 As with the pragma, if only one digit appears then it applies to all
25962 cases; if two digits are given, then the first applies outside
25963 assertions, and the second within assertions. Thus the equivalent
25964 of the example pragma above would be
25965 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
25967 If no digits follow the @option{-gnato}, then it is equivalent to
25968 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
25969 causing all intermediate operations to be computed using the base
25970 type (@code{STRICT} mode).
25972 In addition to setting the mode used for computation of intermediate
25973 results, the @code{-gnato} switch also enables overflow checking (which
25974 is suppressed by default). It thus combines the effect of using
25975 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
25978 @c -------------------------
25979 @node Default Settings
25980 @section Default Settings
25982 The default mode for overflow checks is
25984 @smallexample
25985    General => Strict
25986 @end smallexample
25988 @noindent
25989 which causes all computations both inside and outside assertions to use
25990 the base type. In addition overflow checks are suppressed.
25992 This retains compatibility with previous versions of
25993 GNAT which suppressed overflow checks by default and always
25994 used the base type for computation of intermediate results.
25996 The switch @option{-gnato} (with no digits following) is equivalent to
25997 @cindex @option{-gnato} (gcc)
25999 @smallexample
26000    General => Strict
26001 @end smallexample
26003 @noindent
26004 which causes overflow checking of all intermediate overflows
26005 both inside and outside assertions against the base type.
26006 This provides compatibility
26007 with this switch as implemented in previous versions of GNAT.
26009 The pragma @code{Suppress (Overflow_Check)} disables overflow
26010 checking, but it has no effect on the method used for computing
26011 intermediate results.
26013 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
26014 checking, but it has no effect on the method used for computing
26015 intermediate results.
26017 @c -------------------------
26018 @node Implementation Notes
26019 @section Implementation Notes
26021 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
26022 reasonably efficient, and can be generally used. It also helps
26023 to ensure compatibility with code imported from some other
26024 compiler to GNAT.
26026 Setting all intermediate overflows checking (@code{CHECKED} mode)
26027 makes sense if you want to
26028 make sure that your code is compatible with any other possible
26029 Ada implementation. This may be useful in ensuring portability
26030 for code that is to be exported to some other compiler than GNAT.
26033 The Ada standard allows the reassociation of expressions at
26034 the same precedence level if no parentheses are present. For
26035 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
26036 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
26037 introducing or eliminating an overflow exception. The GNAT
26038 compiler never takes advantage of this freedom, and the
26039 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
26040 If you need the other order, you can write the parentheses
26041 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
26043 The use of @code{ELIMINATED} mode will cause the compiler to
26044 automatically include an appropriate arbitrary precision
26045 integer arithmetic package. The compiler will make calls
26046 to this package, though only in cases where it cannot be
26047 sure that @code{Long_Long_Integer} is sufficient to guard against
26048 intermediate overflows. This package does not use dynamic
26049 alllocation, but it does use the secondary stack, so an
26050 appropriate secondary stack package must be present (this
26051 is always true for standard full Ada, but may require
26052 specific steps for restricted run times such as ZFP).
26054 Although @code{ELIMINATED} mode causes expressions to use arbitrary
26055 precision arithmetic, avoiding overflow, the final result
26056 must be in an appropriate range. This is true even if the
26057 final result is of type @code{[Long_[Long_]]Integer'Base}, which
26058 still has the same bounds as its associated constrained
26059 type at run-time.
26061 Currently, the @code{ELIMINATED} mode is only available on target
26062 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
26063 platforms).
26065 @c *******************************
26066 @node Conditional Compilation
26067 @appendix Conditional Compilation
26068 @c *******************************
26069 @cindex Conditional compilation
26071 @noindent
26072 It is often necessary to arrange for a single source program
26073 to serve multiple purposes, where it is compiled in different
26074 ways to achieve these different goals. Some examples of the
26075 need for this feature are
26077 @itemize @bullet
26078 @item  Adapting a program to a different hardware environment
26079 @item  Adapting a program to a different target architecture
26080 @item  Turning debugging features on and off
26081 @item  Arranging for a program to compile with different compilers
26082 @end itemize
26084 @noindent
26085 In C, or C++, the typical approach would be to use the preprocessor
26086 that is defined as part of the language. The Ada language does not
26087 contain such a feature. This is not an oversight, but rather a very
26088 deliberate design decision, based on the experience that overuse of
26089 the preprocessing features in C and C++ can result in programs that
26090 are extremely difficult to maintain. For example, if we have ten
26091 switches that can be on or off, this means that there are a thousand
26092 separate programs, any one of which might not even be syntactically
26093 correct, and even if syntactically correct, the resulting program
26094 might not work correctly. Testing all combinations can quickly become
26095 impossible.
26097 Nevertheless, the need to tailor programs certainly exists, and in
26098 this Appendix we will discuss how this can
26099 be achieved using Ada in general, and GNAT in particular.
26101 @menu
26102 * Use of Boolean Constants::
26103 * Debugging - A Special Case::
26104 * Conditionalizing Declarations::
26105 * Use of Alternative Implementations::
26106 * Preprocessing::
26107 @end menu
26109 @node Use of Boolean Constants
26110 @section Use of Boolean Constants
26112 @noindent
26113 In the case where the difference is simply which code
26114 sequence is executed, the cleanest solution is to use Boolean
26115 constants to control which code is executed.
26117 @smallexample @c ada
26118 @group
26119 FP_Initialize_Required : constant Boolean := True;
26120 @dots{}
26121 if FP_Initialize_Required then
26122 @dots{}
26123 end if;
26124 @end group
26125 @end smallexample
26127 @noindent
26128 Not only will the code inside the @code{if} statement not be executed if
26129 the constant Boolean is @code{False}, but it will also be completely
26130 deleted from the program.
26131 However, the code is only deleted after the @code{if} statement
26132 has been checked for syntactic and semantic correctness.
26133 (In contrast, with preprocessors the code is deleted before the
26134 compiler ever gets to see it, so it is not checked until the switch
26135 is turned on.)
26136 @cindex Preprocessors (contrasted with conditional compilation)
26138 Typically the Boolean constants will be in a separate package,
26139 something like:
26141 @smallexample @c ada
26142 @group
26143 package Config is
26144    FP_Initialize_Required : constant Boolean := True;
26145    Reset_Available        : constant Boolean := False;
26146    @dots{}
26147 end Config;
26148 @end group
26149 @end smallexample
26151 @noindent
26152 The @code{Config} package exists in multiple forms for the various targets,
26153 with an appropriate script selecting the version of @code{Config} needed.
26154 Then any other unit requiring conditional compilation can do a @code{with}
26155 of @code{Config} to make the constants visible.
26158 @node Debugging - A Special Case
26159 @section Debugging - A Special Case
26161 @noindent
26162 A common use of conditional code is to execute statements (for example
26163 dynamic checks, or output of intermediate results) under control of a
26164 debug switch, so that the debugging behavior can be turned on and off.
26165 This can be done using a Boolean constant to control whether the code
26166 is active:
26168 @smallexample @c ada
26169 @group
26170 if Debugging then
26171    Put_Line ("got to the first stage!");
26172 end if;
26173 @end group
26174 @end smallexample
26176 @noindent
26179 @smallexample @c ada
26180 @group
26181 if Debugging and then Temperature > 999.0 then
26182    raise Temperature_Crazy;
26183 end if;
26184 @end group
26185 @end smallexample
26187 @noindent
26188 Since this is a common case, there are special features to deal with
26189 this in a convenient manner. For the case of tests, Ada 2005 has added
26190 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
26191 @cindex pragma @code{Assert}
26192 on the @code{Assert} pragma that has always been available in GNAT, so this
26193 feature may be used with GNAT even if you are not using Ada 2005 features.
26194 The use of pragma @code{Assert} is described in
26195 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
26196 example, the last test could be written:
26198 @smallexample @c ada
26199 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
26200 @end smallexample
26202 @noindent
26203 or simply
26205 @smallexample @c ada
26206 pragma Assert (Temperature <= 999.0);
26207 @end smallexample
26209 @noindent
26210 In both cases, if assertions are active and the temperature is excessive,
26211 the exception @code{Assert_Failure} will be raised, with the given string in
26212 the first case or a string indicating the location of the pragma in the second
26213 case used as the exception message.
26215 You can turn assertions on and off by using the @code{Assertion_Policy}
26216 pragma.
26217 @cindex pragma @code{Assertion_Policy}
26218 This is an Ada 2005 pragma which is implemented in all modes by
26219 GNAT, but only in the latest versions of GNAT which include Ada 2005
26220 capability. Alternatively, you can use the @option{-gnata} switch
26221 @cindex @option{-gnata} switch
26222 to enable assertions from the command line (this is recognized by all versions
26223 of GNAT).
26225 For the example above with the @code{Put_Line}, the GNAT-specific pragma
26226 @code{Debug} can be used:
26227 @cindex pragma @code{Debug}
26229 @smallexample @c ada
26230 pragma Debug (Put_Line ("got to the first stage!"));
26231 @end smallexample
26233 @noindent
26234 If debug pragmas are enabled, the argument, which must be of the form of
26235 a procedure call, is executed (in this case, @code{Put_Line} will be called).
26236 Only one call can be present, but of course a special debugging procedure
26237 containing any code you like can be included in the program and then
26238 called in a pragma @code{Debug} argument as needed.
26240 One advantage of pragma @code{Debug} over the @code{if Debugging then}
26241 construct is that pragma @code{Debug} can appear in declarative contexts,
26242 such as at the very beginning of a procedure, before local declarations have
26243 been elaborated.
26245 Debug pragmas are enabled using either the @option{-gnata} switch that also
26246 controls assertions, or with a separate Debug_Policy pragma.
26247 @cindex pragma @code{Debug_Policy}
26248 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
26249 in Ada 95 and Ada 83 programs as well), and is analogous to
26250 pragma @code{Assertion_Policy} to control assertions.
26252 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
26253 and thus they can appear in @file{gnat.adc} if you are not using a
26254 project file, or in the file designated to contain configuration pragmas
26255 in a project file.
26256 They then apply to all subsequent compilations. In practice the use of
26257 the @option{-gnata} switch is often the most convenient method of controlling
26258 the status of these pragmas.
26260 Note that a pragma is not a statement, so in contexts where a statement
26261 sequence is required, you can't just write a pragma on its own. You have
26262 to add a @code{null} statement.
26264 @smallexample @c ada
26265 @group
26266 if @dots{} then
26267    @dots{} -- some statements
26268 else
26269    pragma Assert (Num_Cases < 10);
26270    null;
26271 end if;
26272 @end group
26273 @end smallexample
26276 @node Conditionalizing Declarations
26277 @section Conditionalizing Declarations
26279 @noindent
26280 In some cases, it may be necessary to conditionalize declarations to meet
26281 different requirements. For example we might want a bit string whose length
26282 is set to meet some hardware message requirement.
26284 In some cases, it may be possible to do this using declare blocks controlled
26285 by conditional constants:
26287 @smallexample @c ada
26288 @group
26289 if Small_Machine then
26290    declare
26291       X : Bit_String (1 .. 10);
26292    begin
26293       @dots{}
26294    end;
26295 else
26296    declare
26297       X : Large_Bit_String (1 .. 1000);
26298    begin
26299       @dots{}
26300    end;
26301 end if;
26302 @end group
26303 @end smallexample
26305 @noindent
26306 Note that in this approach, both declarations are analyzed by the
26307 compiler so this can only be used where both declarations are legal,
26308 even though one of them will not be used.
26310 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
26311 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
26312 that are parameterized by these constants. For example
26314 @smallexample @c ada
26315 @group
26316 for Rec use
26317   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
26318 end record;
26319 @end group
26320 @end smallexample
26322 @noindent
26323 If @code{Bits_Per_Word} is set to 32, this generates either
26325 @smallexample @c ada
26326 @group
26327 for Rec use
26328   Field1 at 0 range 0 .. 32;
26329 end record;
26330 @end group
26331 @end smallexample
26333 @noindent
26334 for the big endian case, or
26336 @smallexample @c ada
26337 @group
26338 for Rec use record
26339   Field1 at 0 range 10 .. 32;
26340 end record;
26341 @end group
26342 @end smallexample
26344 @noindent
26345 for the little endian case. Since a powerful subset of Ada expression
26346 notation is usable for creating static constants, clever use of this
26347 feature can often solve quite difficult problems in conditionalizing
26348 compilation (note incidentally that in Ada 95, the little endian
26349 constant was introduced as @code{System.Default_Bit_Order}, so you do not
26350 need to define this one yourself).
26353 @node Use of Alternative Implementations
26354 @section Use of Alternative Implementations
26356 @noindent
26357 In some cases, none of the approaches described above are adequate. This
26358 can occur for example if the set of declarations required is radically
26359 different for two different configurations.
26361 In this situation, the official Ada way of dealing with conditionalizing
26362 such code is to write separate units for the different cases. As long as
26363 this does not result in excessive duplication of code, this can be done
26364 without creating maintenance problems. The approach is to share common
26365 code as far as possible, and then isolate the code and declarations
26366 that are different. Subunits are often a convenient method for breaking
26367 out a piece of a unit that is to be conditionalized, with separate files
26368 for different versions of the subunit for different targets, where the
26369 build script selects the right one to give to the compiler.
26370 @cindex Subunits (and conditional compilation)
26372 As an example, consider a situation where a new feature in Ada 2005
26373 allows something to be done in a really nice way. But your code must be able
26374 to compile with an Ada 95 compiler. Conceptually you want to say:
26376 @smallexample @c ada
26377 @group
26378 if Ada_2005 then
26379    @dots{} neat Ada 2005 code
26380 else
26381    @dots{} not quite as neat Ada 95 code
26382 end if;
26383 @end group
26384 @end smallexample
26386 @noindent
26387 where @code{Ada_2005} is a Boolean constant.
26389 But this won't work when @code{Ada_2005} is set to @code{False},
26390 since the @code{then} clause will be illegal for an Ada 95 compiler.
26391 (Recall that although such unreachable code would eventually be deleted
26392 by the compiler, it still needs to be legal.  If it uses features
26393 introduced in Ada 2005, it will be illegal in Ada 95.)
26395 So instead we write
26397 @smallexample @c ada
26398 procedure Insert is separate;
26399 @end smallexample
26401 @noindent
26402 Then we have two files for the subunit @code{Insert}, with the two sets of
26403 code.
26404 If the package containing this is called @code{File_Queries}, then we might
26405 have two files
26407 @itemize @bullet
26408 @item    @file{file_queries-insert-2005.adb}
26409 @item    @file{file_queries-insert-95.adb}
26410 @end itemize
26412 @noindent
26413 and the build script renames the appropriate file to
26415 @smallexample
26416 file_queries-insert.adb
26417 @end smallexample
26419 @noindent
26420 and then carries out the compilation.
26422 This can also be done with project files' naming schemes. For example:
26424 @smallexample @c project
26425 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
26426 @end smallexample
26428 @noindent
26429 Note also that with project files it is desirable to use a different extension
26430 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
26431 conflict may arise through another commonly used feature: to declare as part
26432 of the project a set of directories containing all the sources obeying the
26433 default naming scheme.
26435 The use of alternative units is certainly feasible in all situations,
26436 and for example the Ada part of the GNAT run-time is conditionalized
26437 based on the target architecture using this approach. As a specific example,
26438 consider the implementation of the AST feature in VMS. There is one
26439 spec:
26441 @smallexample
26442 s-asthan.ads
26443 @end smallexample
26445 @noindent
26446 which is the same for all architectures, and three bodies:
26448 @table @file
26449 @item    s-asthan.adb
26450 used for all non-VMS operating systems
26451 @item    s-asthan-vms-alpha.adb
26452 used for VMS on the Alpha
26453 @item    s-asthan-vms-ia64.adb
26454 used for VMS on the ia64
26455 @end table
26457 @noindent
26458 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
26459 this operating system feature is not available, and the two remaining
26460 versions interface with the corresponding versions of VMS to provide
26461 VMS-compatible AST handling. The GNAT build script knows the architecture
26462 and operating system, and automatically selects the right version,
26463 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
26465 Another style for arranging alternative implementations is through Ada's
26466 access-to-subprogram facility.
26467 In case some functionality is to be conditionally included,
26468 you can declare an access-to-procedure variable @code{Ref} that is initialized
26469 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
26470 when appropriate.
26471 In some library package, set @code{Ref} to @code{Proc'Access} for some
26472 procedure @code{Proc} that performs the relevant processing.
26473 The initialization only occurs if the library package is included in the
26474 program.
26475 The same idea can also be implemented using tagged types and dispatching
26476 calls.
26479 @node Preprocessing
26480 @section Preprocessing
26481 @cindex Preprocessing
26483 @noindent
26484 Although it is quite possible to conditionalize code without the use of
26485 C-style preprocessing, as described earlier in this section, it is
26486 nevertheless convenient in some cases to use the C approach. Moreover,
26487 older Ada compilers have often provided some preprocessing capability,
26488 so legacy code may depend on this approach, even though it is not
26489 standard.
26491 To accommodate such use, GNAT provides a preprocessor (modeled to a large
26492 extent on the various preprocessors that have been used
26493 with legacy code on other compilers, to enable easier transition).
26495 The preprocessor may be used in two separate modes. It can be used quite
26496 separately from the compiler, to generate a separate output source file
26497 that is then fed to the compiler as a separate step. This is the
26498 @code{gnatprep} utility, whose use is fully described in
26499 @ref{Preprocessing Using gnatprep}.
26500 @cindex @code{gnatprep}
26502 The preprocessing language allows such constructs as
26504 @smallexample
26505 @group
26506 #if DEBUG or PRIORITY > 4 then
26507    bunch of declarations
26508 #else
26509    completely different bunch of declarations
26510 #end if;
26511 @end group
26512 @end smallexample
26514 @noindent
26515 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
26516 defined either on the command line or in a separate file.
26518 The other way of running the preprocessor is even closer to the C style and
26519 often more convenient. In this approach the preprocessing is integrated into
26520 the compilation process. The compiler is fed the preprocessor input which
26521 includes @code{#if} lines etc, and then the compiler carries out the
26522 preprocessing internally and processes the resulting output.
26523 For more details on this approach, see @ref{Integrated Preprocessing}.
26526 @c *******************************
26527 @node Inline Assembler
26528 @appendix Inline Assembler
26529 @c *******************************
26531 @noindent
26532 If you need to write low-level software that interacts directly
26533 with the hardware, Ada provides two ways to incorporate assembly
26534 language code into your program.  First, you can import and invoke
26535 external routines written in assembly language, an Ada feature fully
26536 supported by GNAT@.  However, for small sections of code it may be simpler
26537 or more efficient to include assembly language statements directly
26538 in your Ada source program, using the facilities of the implementation-defined
26539 package @code{System.Machine_Code}, which incorporates the gcc
26540 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
26541 including the following:
26543 @itemize @bullet
26544 @item No need to use non-Ada tools
26545 @item Consistent interface over different targets
26546 @item Automatic usage of the proper calling conventions
26547 @item Access to Ada constants and variables
26548 @item Definition of intrinsic routines
26549 @item Possibility of inlining a subprogram comprising assembler code
26550 @item Code optimizer can take Inline Assembler code into account
26551 @end itemize
26553 This chapter presents a series of examples to show you how to use
26554 the Inline Assembler.  Although it focuses on the Intel x86,
26555 the general approach applies also to other processors.
26556 It is assumed that you are familiar with Ada
26557 and with assembly language programming.
26559 @menu
26560 * Basic Assembler Syntax::
26561 * A Simple Example of Inline Assembler::
26562 * Output Variables in Inline Assembler::
26563 * Input Variables in Inline Assembler::
26564 * Inlining Inline Assembler Code::
26565 * Other Asm Functionality::
26566 @end menu
26568 @c ---------------------------------------------------------------------------
26569 @node Basic Assembler Syntax
26570 @section Basic Assembler Syntax
26572 @noindent
26573 The assembler used by GNAT and gcc is based not on the Intel assembly
26574 language, but rather on a language that descends from the AT&T Unix
26575 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
26576 The following table summarizes the main features of @emph{as} syntax
26577 and points out the differences from the Intel conventions.
26578 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
26579 pre-processor) documentation for further information.
26581 @table @asis
26582 @item Register names
26583 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
26585 Intel: No extra punctuation; for example @code{eax}
26587 @item Immediate operand
26588 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
26590 Intel: No extra punctuation; for example @code{4}
26592 @item Address
26593 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
26595 Intel: No extra punctuation; for example @code{loc}
26597 @item Memory contents
26598 gcc / @emph{as}: No extra punctuation; for example @code{loc}
26600 Intel: Square brackets; for example @code{[loc]}
26602 @item Register contents
26603 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
26605 Intel: Square brackets; for example @code{[eax]}
26607 @item Hexadecimal numbers
26608 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
26610 Intel: Trailing ``h''; for example @code{A0h}
26612 @item Operand size
26613 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
26614 a 16-bit word
26616 Intel: Implicit, deduced by assembler; for example @code{mov}
26618 @item Instruction repetition
26619 gcc / @emph{as}: Split into two lines; for example
26621 @code{rep}
26623 @code{stosl}
26625 Intel: Keep on one line; for example @code{rep stosl}
26627 @item Order of operands
26628 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
26630 Intel: Destination first; for example @code{mov eax, 4}
26631 @end table
26633 @c ---------------------------------------------------------------------------
26634 @node A Simple Example of Inline Assembler
26635 @section A Simple Example of Inline Assembler
26637 @noindent
26638 The following example will generate a single assembly language statement,
26639 @code{nop}, which does nothing.  Despite its lack of run-time effect,
26640 the example will be useful in illustrating the basics of
26641 the Inline Assembler facility.
26643 @smallexample @c ada
26644 @group
26645 with System.Machine_Code; use System.Machine_Code;
26646 procedure Nothing is
26647 begin
26648    Asm ("nop");
26649 end Nothing;
26650 @end group
26651 @end smallexample
26653 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
26654 here it takes one parameter, a @emph{template string} that must be a static
26655 expression and that will form the generated instruction.
26656 @code{Asm} may be regarded as a compile-time procedure that parses
26657 the template string and additional parameters (none here),
26658 from which it generates a sequence of assembly language instructions.
26660 The examples in this chapter will illustrate several of the forms
26661 for invoking @code{Asm}; a complete specification of the syntax
26662 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
26663 Manual}.
26665 Under the standard GNAT conventions, the @code{Nothing} procedure
26666 should be in a file named @file{nothing.adb}.
26667 You can build the executable in the usual way:
26668 @smallexample
26669 gnatmake nothing
26670 @end smallexample
26671 However, the interesting aspect of this example is not its run-time behavior
26672 but rather the generated assembly code.
26673 To see this output, invoke the compiler as follows:
26674 @smallexample
26675    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
26676 @end smallexample
26677 where the options are:
26679 @table @code
26680 @item -c
26681 compile only (no bind or link)
26682 @item -S
26683 generate assembler listing
26684 @item -fomit-frame-pointer
26685 do not set up separate stack frames
26686 @item -gnatp
26687 do not add runtime checks
26688 @end table
26690 This gives a human-readable assembler version of the code. The resulting
26691 file will have the same name as the Ada source file, but with a @code{.s}
26692 extension. In our example, the file @file{nothing.s} has the following
26693 contents:
26695 @smallexample
26696 @group
26697 .file "nothing.adb"
26698 gcc2_compiled.:
26699 ___gnu_compiled_ada:
26700 .text
26701    .align 4
26702 .globl __ada_nothing
26703 __ada_nothing:
26704 #APP
26705    nop
26706 #NO_APP
26707    jmp L1
26708    .align 2,0x90
26710    ret
26711 @end group
26712 @end smallexample
26714 The assembly code you included is clearly indicated by
26715 the compiler, between the @code{#APP} and @code{#NO_APP}
26716 delimiters. The character before the 'APP' and 'NOAPP'
26717 can differ on different targets. For example, GNU/Linux uses '#APP' while
26718 on NT you will see '/APP'.
26720 If you make a mistake in your assembler code (such as using the
26721 wrong size modifier, or using a wrong operand for the instruction) GNAT
26722 will report this error in a temporary file, which will be deleted when
26723 the compilation is finished.  Generating an assembler file will help
26724 in such cases, since you can assemble this file separately using the
26725 @emph{as} assembler that comes with gcc.
26727 Assembling the file using the command
26729 @smallexample
26730 as @file{nothing.s}
26731 @end smallexample
26732 @noindent
26733 will give you error messages whose lines correspond to the assembler
26734 input file, so you can easily find and correct any mistakes you made.
26735 If there are no errors, @emph{as} will generate an object file
26736 @file{nothing.out}.
26738 @c ---------------------------------------------------------------------------
26739 @node Output Variables in Inline Assembler
26740 @section Output Variables in Inline Assembler
26742 @noindent
26743 The examples in this section, showing how to access the processor flags,
26744 illustrate how to specify the destination operands for assembly language
26745 statements.
26747 @smallexample @c ada
26748 @group
26749 with Interfaces; use Interfaces;
26750 with Ada.Text_IO; use Ada.Text_IO;
26751 with System.Machine_Code; use System.Machine_Code;
26752 procedure Get_Flags is
26753    Flags : Unsigned_32;
26754    use ASCII;
26755 begin
26756    Asm ("pushfl"          & LF & HT & -- push flags on stack
26757         "popl %%eax"      & LF & HT & -- load eax with flags
26758         "movl %%eax, %0",             -- store flags in variable
26759         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26760    Put_Line ("Flags register:" & Flags'Img);
26761 end Get_Flags;
26762 @end group
26763 @end smallexample
26765 In order to have a nicely aligned assembly listing, we have separated
26766 multiple assembler statements in the Asm template string with linefeed
26767 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
26768 The resulting section of the assembly output file is:
26770 @smallexample
26771 @group
26772 #APP
26773    pushfl
26774    popl %eax
26775    movl %eax, -40(%ebp)
26776 #NO_APP
26777 @end group
26778 @end smallexample
26780 It would have been legal to write the Asm invocation as:
26782 @smallexample
26783 Asm ("pushfl popl %%eax movl %%eax, %0")
26784 @end smallexample
26786 but in the generated assembler file, this would come out as:
26788 @smallexample
26789 #APP
26790    pushfl popl %eax movl %eax, -40(%ebp)
26791 #NO_APP
26792 @end smallexample
26794 which is not so convenient for the human reader.
26796 We use Ada comments
26797 at the end of each line to explain what the assembler instructions
26798 actually do.  This is a useful convention.
26800 When writing Inline Assembler instructions, you need to precede each register
26801 and variable name with a percent sign.  Since the assembler already requires
26802 a percent sign at the beginning of a register name, you need two consecutive
26803 percent signs for such names in the Asm template string, thus @code{%%eax}.
26804 In the generated assembly code, one of the percent signs will be stripped off.
26806 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
26807 variables: operands you later define using @code{Input} or @code{Output}
26808 parameters to @code{Asm}.
26809 An output variable is illustrated in
26810 the third statement in the Asm template string:
26811 @smallexample
26812 movl %%eax, %0
26813 @end smallexample
26814 The intent is to store the contents of the eax register in a variable that can
26815 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
26816 necessarily work, since the compiler might optimize by using a register
26817 to hold Flags, and the expansion of the @code{movl} instruction would not be
26818 aware of this optimization.  The solution is not to store the result directly
26819 but rather to advise the compiler to choose the correct operand form;
26820 that is the purpose of the @code{%0} output variable.
26822 Information about the output variable is supplied in the @code{Outputs}
26823 parameter to @code{Asm}:
26824 @smallexample
26825 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26826 @end smallexample
26828 The output is defined by the @code{Asm_Output} attribute of the target type;
26829 the general format is
26830 @smallexample
26831 Type'Asm_Output (constraint_string, variable_name)
26832 @end smallexample
26834 The constraint string directs the compiler how
26835 to store/access the associated variable.  In the example
26836 @smallexample
26837 Unsigned_32'Asm_Output ("=m", Flags);
26838 @end smallexample
26839 the @code{"m"} (memory) constraint tells the compiler that the variable
26840 @code{Flags} should be stored in a memory variable, thus preventing
26841 the optimizer from keeping it in a register.  In contrast,
26842 @smallexample
26843 Unsigned_32'Asm_Output ("=r", Flags);
26844 @end smallexample
26845 uses the @code{"r"} (register) constraint, telling the compiler to
26846 store the variable in a register.
26848 If the constraint is preceded by the equal character (@strong{=}), it tells
26849 the compiler that the variable will be used to store data into it.
26851 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26852 allowing the optimizer to choose whatever it deems best.
26854 There are a fairly large number of constraints, but the ones that are
26855 most useful (for the Intel x86 processor) are the following:
26857 @table @code
26858 @item =
26859 output constraint
26860 @item g
26861 global (i.e.@: can be stored anywhere)
26862 @item m
26863 in memory
26864 @item I
26865 a constant
26866 @item a
26867 use eax
26868 @item b
26869 use ebx
26870 @item c
26871 use ecx
26872 @item d
26873 use edx
26874 @item S
26875 use esi
26876 @item D
26877 use edi
26878 @item r
26879 use one of eax, ebx, ecx or edx
26880 @item q
26881 use one of eax, ebx, ecx, edx, esi or edi
26882 @end table
26884 The full set of constraints is described in the gcc and @emph{as}
26885 documentation; note that it is possible to combine certain constraints
26886 in one constraint string.
26888 You specify the association of an output variable with an assembler operand
26889 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26890 integer.  Thus in
26891 @smallexample @c ada
26892 @group
26893 Asm ("pushfl"          & LF & HT & -- push flags on stack
26894      "popl %%eax"      & LF & HT & -- load eax with flags
26895      "movl %%eax, %0",             -- store flags in variable
26896      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26897 @end group
26898 @end smallexample
26899 @noindent
26900 @code{%0} will be replaced in the expanded code by the appropriate operand,
26901 whatever
26902 the compiler decided for the @code{Flags} variable.
26904 In general, you may have any number of output variables:
26905 @itemize @bullet
26906 @item
26907 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26908 @item
26909 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26910 of @code{Asm_Output} attributes
26911 @end itemize
26913 For example:
26914 @smallexample @c ada
26915 @group
26916 Asm ("movl %%eax, %0" & LF & HT &
26917      "movl %%ebx, %1" & LF & HT &
26918      "movl %%ecx, %2",
26919      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
26920                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
26921                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
26922 @end group
26923 @end smallexample
26924 @noindent
26925 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26926 in the Ada program.
26928 As a variation on the @code{Get_Flags} example, we can use the constraints
26929 string to direct the compiler to store the eax register into the @code{Flags}
26930 variable, instead of including the store instruction explicitly in the
26931 @code{Asm} template string:
26933 @smallexample @c ada
26934 @group
26935 with Interfaces; use Interfaces;
26936 with Ada.Text_IO; use Ada.Text_IO;
26937 with System.Machine_Code; use System.Machine_Code;
26938 procedure Get_Flags_2 is
26939    Flags : Unsigned_32;
26940    use ASCII;
26941 begin
26942    Asm ("pushfl"      & LF & HT & -- push flags on stack
26943         "popl %%eax",             -- save flags in eax
26944         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26945    Put_Line ("Flags register:" & Flags'Img);
26946 end Get_Flags_2;
26947 @end group
26948 @end smallexample
26950 @noindent
26951 The @code{"a"} constraint tells the compiler that the @code{Flags}
26952 variable will come from the eax register. Here is the resulting code:
26954 @smallexample
26955 @group
26956 #APP
26957    pushfl
26958    popl %eax
26959 #NO_APP
26960    movl %eax,-40(%ebp)
26961 @end group
26962 @end smallexample
26964 @noindent
26965 The compiler generated the store of eax into Flags after
26966 expanding the assembler code.
26968 Actually, there was no need to pop the flags into the eax register;
26969 more simply, we could just pop the flags directly into the program variable:
26971 @smallexample @c ada
26972 @group
26973 with Interfaces; use Interfaces;
26974 with Ada.Text_IO; use Ada.Text_IO;
26975 with System.Machine_Code; use System.Machine_Code;
26976 procedure Get_Flags_3 is
26977    Flags : Unsigned_32;
26978    use ASCII;
26979 begin
26980    Asm ("pushfl"  & LF & HT & -- push flags on stack
26981         "pop %0",             -- save flags in Flags
26982         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26983    Put_Line ("Flags register:" & Flags'Img);
26984 end Get_Flags_3;
26985 @end group
26986 @end smallexample
26988 @c ---------------------------------------------------------------------------
26989 @node Input Variables in Inline Assembler
26990 @section Input Variables in Inline Assembler
26992 @noindent
26993 The example in this section illustrates how to specify the source operands
26994 for assembly language statements.
26995 The program simply increments its input value by 1:
26997 @smallexample @c ada
26998 @group
26999 with Interfaces; use Interfaces;
27000 with Ada.Text_IO; use Ada.Text_IO;
27001 with System.Machine_Code; use System.Machine_Code;
27002 procedure Increment is
27004    function Incr (Value : Unsigned_32) return Unsigned_32 is
27005       Result : Unsigned_32;
27006    begin
27007       Asm ("incl %0",
27008            Outputs => Unsigned_32'Asm_Output ("=a", Result),
27009            Inputs  => Unsigned_32'Asm_Input ("a", Value));
27010       return Result;
27011    end Incr;
27013    Value : Unsigned_32;
27015 begin
27016    Value := 5;
27017    Put_Line ("Value before is" & Value'Img);
27018    Value := Incr (Value);
27019    Put_Line ("Value after is" & Value'Img);
27020 end Increment;
27021 @end group
27022 @end smallexample
27024 The @code{Outputs} parameter to @code{Asm} specifies
27025 that the result will be in the eax register and that it is to be stored
27026 in the @code{Result} variable.
27028 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
27029 but with an @code{Asm_Input} attribute.
27030 The @code{"="} constraint, indicating an output value, is not present.
27032 You can have multiple input variables, in the same way that you can have more
27033 than one output variable.
27035 The parameter count (%0, %1) etc, still starts at the first output statement,
27036 and continues with the input statements.
27038 Just as the @code{Outputs} parameter causes the register to be stored into the
27039 target variable after execution of the assembler statements, so does the
27040 @code{Inputs} parameter cause its variable to be loaded into the register
27041 before execution of the assembler statements.
27043 Thus the effect of the @code{Asm} invocation is:
27044 @enumerate
27045 @item load the 32-bit value of @code{Value} into eax
27046 @item execute the @code{incl %eax} instruction
27047 @item store the contents of eax into the @code{Result} variable
27048 @end enumerate
27050 The resulting assembler file (with @option{-O2} optimization) contains:
27051 @smallexample
27052 @group
27053 _increment__incr.1:
27054    subl $4,%esp
27055    movl 8(%esp),%eax
27056 #APP
27057    incl %eax
27058 #NO_APP
27059    movl %eax,%edx
27060    movl %ecx,(%esp)
27061    addl $4,%esp
27062    ret
27063 @end group
27064 @end smallexample
27066 @c ---------------------------------------------------------------------------
27067 @node Inlining Inline Assembler Code
27068 @section Inlining Inline Assembler Code
27070 @noindent
27071 For a short subprogram such as the @code{Incr} function in the previous
27072 section, the overhead of the call and return (creating / deleting the stack
27073 frame) can be significant, compared to the amount of code in the subprogram
27074 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
27075 which directs the compiler to expand invocations of the subprogram at the
27076 point(s) of call, instead of setting up a stack frame for out-of-line calls.
27077 Here is the resulting program:
27079 @smallexample @c ada
27080 @group
27081 with Interfaces; use Interfaces;
27082 with Ada.Text_IO; use Ada.Text_IO;
27083 with System.Machine_Code; use System.Machine_Code;
27084 procedure Increment_2 is
27086    function Incr (Value : Unsigned_32) return Unsigned_32 is
27087       Result : Unsigned_32;
27088    begin
27089       Asm ("incl %0",
27090            Outputs => Unsigned_32'Asm_Output ("=a", Result),
27091            Inputs  => Unsigned_32'Asm_Input ("a", Value));
27092       return Result;
27093    end Incr;
27094    pragma Inline (Increment);
27096    Value : Unsigned_32;
27098 begin
27099    Value := 5;
27100    Put_Line ("Value before is" & Value'Img);
27101    Value := Increment (Value);
27102    Put_Line ("Value after is" & Value'Img);
27103 end Increment_2;
27104 @end group
27105 @end smallexample
27107 Compile the program with both optimization (@option{-O2}) and inlining
27108 (@option{-gnatn}) enabled.
27110 The @code{Incr} function is still compiled as usual, but at the
27111 point in @code{Increment} where our function used to be called:
27113 @smallexample
27114 @group
27115 pushl %edi
27116 call _increment__incr.1
27117 @end group
27118 @end smallexample
27120 @noindent
27121 the code for the function body directly appears:
27123 @smallexample
27124 @group
27125 movl %esi,%eax
27126 #APP
27127    incl %eax
27128 #NO_APP
27129    movl %eax,%edx
27130 @end group
27131 @end smallexample
27133 @noindent
27134 thus saving the overhead of stack frame setup and an out-of-line call.
27136 @c ---------------------------------------------------------------------------
27137 @node Other Asm Functionality
27138 @section Other @code{Asm} Functionality
27140 @noindent
27141 This section describes two important parameters to the @code{Asm}
27142 procedure: @code{Clobber}, which identifies register usage;
27143 and @code{Volatile}, which inhibits unwanted optimizations.
27145 @menu
27146 * The Clobber Parameter::
27147 * The Volatile Parameter::
27148 @end menu
27150 @c ---------------------------------------------------------------------------
27151 @node The Clobber Parameter
27152 @subsection The @code{Clobber} Parameter
27154 @noindent
27155 One of the dangers of intermixing assembly language and a compiled language
27156 such as Ada is that the compiler needs to be aware of which registers are
27157 being used by the assembly code.  In some cases, such as the earlier examples,
27158 the constraint string is sufficient to indicate register usage (e.g.,
27159 @code{"a"} for
27160 the eax register).  But more generally, the compiler needs an explicit
27161 identification of the registers that are used by the Inline Assembly
27162 statements.
27164 Using a register that the compiler doesn't know about
27165 could be a side effect of an instruction (like @code{mull}
27166 storing its result in both eax and edx).
27167 It can also arise from explicit register usage in your
27168 assembly code; for example:
27169 @smallexample
27170 @group
27171 Asm ("movl %0, %%ebx" & LF & HT &
27172      "movl %%ebx, %1",
27173      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27174      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
27175 @end group
27176 @end smallexample
27177 @noindent
27178 where the compiler (since it does not analyze the @code{Asm} template string)
27179 does not know you are using the ebx register.
27181 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
27182 to identify the registers that will be used by your assembly code:
27184 @smallexample
27185 @group
27186 Asm ("movl %0, %%ebx" & LF & HT &
27187      "movl %%ebx, %1",
27188      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27189      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
27190      Clobber => "ebx");
27191 @end group
27192 @end smallexample
27194 The Clobber parameter is a static string expression specifying the
27195 register(s) you are using.  Note that register names are @emph{not} prefixed
27196 by a percent sign. Also, if more than one register is used then their names
27197 are separated by commas; e.g., @code{"eax, ebx"}
27199 The @code{Clobber} parameter has several additional uses:
27200 @enumerate
27201 @item Use ``register'' name @code{cc} to indicate that flags might have changed
27202 @item Use ``register'' name @code{memory} if you changed a memory location
27203 @end enumerate
27205 @c ---------------------------------------------------------------------------
27206 @node The Volatile Parameter
27207 @subsection The @code{Volatile} Parameter
27208 @cindex Volatile parameter
27210 @noindent
27211 Compiler optimizations in the presence of Inline Assembler may sometimes have
27212 unwanted effects.  For example, when an @code{Asm} invocation with an input
27213 variable is inside a loop, the compiler might move the loading of the input
27214 variable outside the loop, regarding it as a one-time initialization.
27216 If this effect is not desired, you can disable such optimizations by setting
27217 the @code{Volatile} parameter to @code{True}; for example:
27219 @smallexample @c ada
27220 @group
27221 Asm ("movl %0, %%ebx" & LF & HT &
27222      "movl %%ebx, %1",
27223      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
27224      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
27225      Clobber  => "ebx",
27226      Volatile => True);
27227 @end group
27228 @end smallexample
27230 By default, @code{Volatile} is set to @code{False} unless there is no
27231 @code{Outputs} parameter.
27233 Although setting @code{Volatile} to @code{True} prevents unwanted
27234 optimizations, it will also disable other optimizations that might be
27235 important for efficiency. In general, you should set @code{Volatile}
27236 to @code{True} only if the compiler's optimizations have created
27237 problems.
27238 @c END OF INLINE ASSEMBLER CHAPTER
27239 @c ===============================
27241 @c ***********************************
27242 @c * Compatibility and Porting Guide *
27243 @c ***********************************
27244 @node Compatibility and Porting Guide
27245 @appendix Compatibility and Porting Guide
27247 @noindent
27248 This chapter describes the compatibility issues that may arise between
27249 GNAT and other Ada compilation systems (including those for Ada 83),
27250 and shows how GNAT can expedite porting
27251 applications developed in other Ada environments.
27253 @menu
27254 * Compatibility with Ada 83::
27255 * Compatibility between Ada 95 and Ada 2005::
27256 * Implementation-dependent characteristics::
27257 * Compatibility with Other Ada Systems::
27258 * Representation Clauses::
27259 @ifclear vms
27260 @c Brief section is only in non-VMS version
27261 @c Full chapter is in VMS version
27262 * Compatibility with HP Ada 83::
27263 @end ifclear
27264 @ifset vms
27265 * Transitioning to 64-Bit GNAT for OpenVMS::
27266 @end ifset
27267 @end menu
27269 @node Compatibility with Ada 83
27270 @section Compatibility with Ada 83
27271 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
27273 @noindent
27274 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
27275 particular, the design intention was that the difficulties associated
27276 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
27277 that occur when moving from one Ada 83 system to another.
27279 However, there are a number of points at which there are minor
27280 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
27281 full details of these issues,
27282 and should be consulted for a complete treatment.
27283 In practice the
27284 following subsections treat the most likely issues to be encountered.
27286 @menu
27287 * Legal Ada 83 programs that are illegal in Ada 95::
27288 * More deterministic semantics::
27289 * Changed semantics::
27290 * Other language compatibility issues::
27291 @end menu
27293 @node Legal Ada 83 programs that are illegal in Ada 95
27294 @subsection Legal Ada 83 programs that are illegal in Ada 95
27296 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
27297 Ada 95 and thus also in Ada 2005:
27299 @table @emph
27300 @item Character literals
27301 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
27302 @code{Wide_Character} as a new predefined character type, some uses of
27303 character literals that were legal in Ada 83 are illegal in Ada 95.
27304 For example:
27305 @smallexample @c ada
27306    for Char in 'A' .. 'Z' loop @dots{} end loop;
27307 @end smallexample
27309 @noindent
27310 The problem is that @code{'A'} and @code{'Z'} could be from either
27311 @code{Character} or @code{Wide_Character}.  The simplest correction
27312 is to make the type explicit; e.g.:
27313 @smallexample @c ada
27314    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
27315 @end smallexample
27317 @item New reserved words
27318 The identifiers @code{abstract}, @code{aliased}, @code{protected},
27319 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
27320 Existing Ada 83 code using any of these identifiers must be edited to
27321 use some alternative name.
27323 @item Freezing rules
27324 The rules in Ada 95 are slightly different with regard to the point at
27325 which entities are frozen, and representation pragmas and clauses are
27326 not permitted past the freeze point.  This shows up most typically in
27327 the form of an error message complaining that a representation item
27328 appears too late, and the appropriate corrective action is to move
27329 the item nearer to the declaration of the entity to which it refers.
27331 A particular case is that representation pragmas
27332 @ifset vms
27333 (including the
27334 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
27335 @end ifset
27336 cannot be applied to a subprogram body.  If necessary, a separate subprogram
27337 declaration must be introduced to which the pragma can be applied.
27339 @item Optional bodies for library packages
27340 In Ada 83, a package that did not require a package body was nevertheless
27341 allowed to have one.  This lead to certain surprises in compiling large
27342 systems (situations in which the body could be unexpectedly ignored by the
27343 binder).  In Ada 95, if a package does not require a body then it is not
27344 permitted to have a body.  To fix this problem, simply remove a redundant
27345 body if it is empty, or, if it is non-empty, introduce a dummy declaration
27346 into the spec that makes the body required.  One approach is to add a private
27347 part to the package declaration (if necessary), and define a parameterless
27348 procedure called @code{Requires_Body}, which must then be given a dummy
27349 procedure body in the package body, which then becomes required.
27350 Another approach (assuming that this does not introduce elaboration
27351 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
27352 since one effect of this pragma is to require the presence of a package body.
27354 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
27355 In Ada 95, the exception @code{Numeric_Error} is a renaming of
27356 @code{Constraint_Error}.
27357 This means that it is illegal to have separate exception handlers for
27358 the two exceptions.  The fix is simply to remove the handler for the
27359 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
27360 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
27362 @item Indefinite subtypes in generics
27363 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
27364 as the actual for a generic formal private type, but then the instantiation
27365 would be illegal if there were any instances of declarations of variables
27366 of this type in the generic body.  In Ada 95, to avoid this clear violation
27367 of the methodological principle known as the ``contract model'',
27368 the generic declaration explicitly indicates whether
27369 or not such instantiations are permitted.  If a generic formal parameter
27370 has explicit unknown discriminants, indicated by using @code{(<>)} after the
27371 subtype name, then it can be instantiated with indefinite types, but no
27372 stand-alone variables can be declared of this type.  Any attempt to declare
27373 such a variable will result in an illegality at the time the generic is
27374 declared.  If the @code{(<>)} notation is not used, then it is illegal
27375 to instantiate the generic with an indefinite type.
27376 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
27377 It will show up as a compile time error, and
27378 the fix is usually simply to add the @code{(<>)} to the generic declaration.
27379 @end table
27381 @node More deterministic semantics
27382 @subsection More deterministic semantics
27384 @table @emph
27385 @item Conversions
27386 Conversions from real types to integer types round away from 0.  In Ada 83
27387 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
27388 implementation freedom was intended to support unbiased rounding in
27389 statistical applications, but in practice it interfered with portability.
27390 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
27391 is required.  Numeric code may be affected by this change in semantics.
27392 Note, though, that this issue is no worse than already existed in Ada 83
27393 when porting code from one vendor to another.
27395 @item Tasking
27396 The Real-Time Annex introduces a set of policies that define the behavior of
27397 features that were implementation dependent in Ada 83, such as the order in
27398 which open select branches are executed.
27399 @end table
27401 @node Changed semantics
27402 @subsection Changed semantics
27404 @noindent
27405 The worst kind of incompatibility is one where a program that is legal in
27406 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
27407 possible in Ada 83.  Fortunately this is extremely rare, but the one
27408 situation that you should be alert to is the change in the predefined type
27409 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
27411 @table @emph
27412 @item Range of type @code{Character}
27413 The range of @code{Standard.Character} is now the full 256 characters
27414 of Latin-1, whereas in most Ada 83 implementations it was restricted
27415 to 128 characters. Although some of the effects of
27416 this change will be manifest in compile-time rejection of legal
27417 Ada 83 programs it is possible for a working Ada 83 program to have
27418 a different effect in Ada 95, one that was not permitted in Ada 83.
27419 As an example, the expression
27420 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
27421 delivers @code{255} as its value.
27422 In general, you should look at the logic of any
27423 character-processing Ada 83 program and see whether it needs to be adapted
27424 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
27425 character handling package that may be relevant if code needs to be adapted
27426 to account for the additional Latin-1 elements.
27427 The desirable fix is to
27428 modify the program to accommodate the full character set, but in some cases
27429 it may be convenient to define a subtype or derived type of Character that
27430 covers only the restricted range.
27431 @cindex Latin-1
27432 @end table
27434 @node Other language compatibility issues
27435 @subsection Other language compatibility issues
27437 @table @emph
27438 @item @option{-gnat83} switch
27439 All implementations of GNAT provide a switch that causes GNAT to operate
27440 in Ada 83 mode.  In this mode, some but not all compatibility problems
27441 of the type described above are handled automatically.  For example, the
27442 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
27443 as identifiers as in Ada 83.
27444 However,
27445 in practice, it is usually advisable to make the necessary modifications
27446 to the program to remove the need for using this switch.
27447 See @ref{Compiling Different Versions of Ada}.
27449 @item Support for removed Ada 83 pragmas and attributes
27450 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
27451 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
27452 compilers are allowed, but not required, to implement these missing
27453 elements.  In contrast with some other compilers, GNAT implements all
27454 such pragmas and attributes, eliminating this compatibility concern.  These
27455 include @code{pragma Interface} and the floating point type attributes
27456 (@code{Emax}, @code{Mantissa}, etc.), among other items.
27457 @end table
27460 @node Compatibility between Ada 95 and Ada 2005
27461 @section Compatibility between Ada 95 and Ada 2005
27462 @cindex Compatibility between Ada 95 and Ada 2005
27464 @noindent
27465 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
27466 a number of incompatibilities. Several are enumerated below;
27467 for a complete description please see the
27468 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
27469 @cite{Rationale for Ada 2005}.
27471 @table @emph
27472 @item New reserved words.
27473 The words @code{interface}, @code{overriding} and @code{synchronized} are
27474 reserved in Ada 2005.
27475 A pre-Ada 2005 program that uses any of these as an identifier will be
27476 illegal.
27478 @item New declarations in predefined packages.
27479 A number of packages in the predefined environment contain new declarations:
27480 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
27481 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
27482 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
27483 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
27484 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
27485 If an Ada 95 program does a @code{with} and @code{use} of any of these
27486 packages, the new declarations may cause name clashes.
27488 @item Access parameters.
27489 A nondispatching subprogram with an access parameter cannot be renamed
27490 as a dispatching operation.  This was permitted in Ada 95.
27492 @item Access types, discriminants, and constraints.
27493 Rule changes in this area have led to some incompatibilities; for example,
27494 constrained subtypes of some access types are not permitted in Ada 2005.
27496 @item Aggregates for limited types.
27497 The allowance of aggregates for limited types in Ada 2005 raises the
27498 possibility of ambiguities in legal Ada 95 programs, since additional types
27499 now need to be considered in expression resolution.
27501 @item Fixed-point multiplication and division.
27502 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
27503 were legal in Ada 95 and invoked the predefined versions of these operations,
27504 are now ambiguous.
27505 The ambiguity may be resolved either by applying a type conversion to the
27506 expression, or by explicitly invoking the operation from package
27507 @code{Standard}.
27509 @item Return-by-reference types.
27510 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
27511 can declare a function returning a value from an anonymous access type.
27512 @end table
27515 @node Implementation-dependent characteristics
27516 @section Implementation-dependent characteristics
27517 @noindent
27518 Although the Ada language defines the semantics of each construct as
27519 precisely as practical, in some situations (for example for reasons of
27520 efficiency, or where the effect is heavily dependent on the host or target
27521 platform) the implementation is allowed some freedom.  In porting Ada 83
27522 code to GNAT, you need to be aware of whether / how the existing code
27523 exercised such implementation dependencies.  Such characteristics fall into
27524 several categories, and GNAT offers specific support in assisting the
27525 transition from certain Ada 83 compilers.
27527 @menu
27528 * Implementation-defined pragmas::
27529 * Implementation-defined attributes::
27530 * Libraries::
27531 * Elaboration order::
27532 * Target-specific aspects::
27533 @end menu
27535 @node Implementation-defined pragmas
27536 @subsection Implementation-defined pragmas
27538 @noindent
27539 Ada compilers are allowed to supplement the language-defined pragmas, and
27540 these are a potential source of non-portability.  All GNAT-defined pragmas
27541 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
27542 Reference Manual}, and these include several that are specifically
27543 intended to correspond to other vendors' Ada 83 pragmas.
27544 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
27545 For compatibility with HP Ada 83, GNAT supplies the pragmas
27546 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
27547 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
27548 and @code{Volatile}.
27549 Other relevant pragmas include @code{External} and @code{Link_With}.
27550 Some vendor-specific
27551 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
27552 recognized, thus
27553 avoiding compiler rejection of units that contain such pragmas; they are not
27554 relevant in a GNAT context and hence are not otherwise implemented.
27556 @node Implementation-defined attributes
27557 @subsection Implementation-defined attributes
27559 Analogous to pragmas, the set of attributes may be extended by an
27560 implementation.  All GNAT-defined attributes are described in
27561 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
27562 Manual}, and these include several that are specifically intended
27563 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
27564 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
27565 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
27566 @code{Type_Class}.
27568 @node Libraries
27569 @subsection Libraries
27570 @noindent
27571 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
27572 code uses vendor-specific libraries then there are several ways to manage
27573 this in Ada 95 or Ada 2005:
27574 @enumerate
27575 @item
27576 If the source code for the libraries (specs and bodies) are
27577 available, then the libraries can be migrated in the same way as the
27578 application.
27579 @item
27580 If the source code for the specs but not the bodies are
27581 available, then you can reimplement the bodies.
27582 @item
27583 Some features introduced by Ada 95 obviate the need for library support.  For
27584 example most Ada 83 vendors supplied a package for unsigned integers.  The
27585 Ada 95 modular type feature is the preferred way to handle this need, so
27586 instead of migrating or reimplementing the unsigned integer package it may
27587 be preferable to retrofit the application using modular types.
27588 @end enumerate
27590 @node Elaboration order
27591 @subsection Elaboration order
27592 @noindent
27593 The implementation can choose any elaboration order consistent with the unit
27594 dependency relationship.  This freedom means that some orders can result in
27595 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
27596 to invoke a subprogram its body has been elaborated, or to instantiate a
27597 generic before the generic body has been elaborated.  By default GNAT
27598 attempts to choose a safe order (one that will not encounter access before
27599 elaboration problems) by implicitly inserting @code{Elaborate} or
27600 @code{Elaborate_All} pragmas where
27601 needed.  However, this can lead to the creation of elaboration circularities
27602 and a resulting rejection of the program by gnatbind.  This issue is
27603 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
27604 In brief, there are several
27605 ways to deal with this situation:
27607 @itemize @bullet
27608 @item
27609 Modify the program to eliminate the circularities, e.g.@: by moving
27610 elaboration-time code into explicitly-invoked procedures
27611 @item
27612 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
27613 @code{Elaborate} pragmas, and then inhibit the generation of implicit
27614 @code{Elaborate_All}
27615 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
27616 (by selectively suppressing elaboration checks via pragma
27617 @code{Suppress(Elaboration_Check)} when it is safe to do so).
27618 @end itemize
27620 @node Target-specific aspects
27621 @subsection Target-specific aspects
27622 @noindent
27623 Low-level applications need to deal with machine addresses, data
27624 representations, interfacing with assembler code, and similar issues.  If
27625 such an Ada 83 application is being ported to different target hardware (for
27626 example where the byte endianness has changed) then you will need to
27627 carefully examine the program logic; the porting effort will heavily depend
27628 on the robustness of the original design.  Moreover, Ada 95 (and thus
27629 Ada 2005) are sometimes
27630 incompatible with typical Ada 83 compiler practices regarding implicit
27631 packing, the meaning of the Size attribute, and the size of access values.
27632 GNAT's approach to these issues is described in @ref{Representation Clauses}.
27634 @node Compatibility with Other Ada Systems
27635 @section Compatibility with Other Ada Systems
27637 @noindent
27638 If programs avoid the use of implementation dependent and
27639 implementation defined features, as documented in the @cite{Ada
27640 Reference Manual}, there should be a high degree of portability between
27641 GNAT and other Ada systems.  The following are specific items which
27642 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
27643 compilers, but do not affect porting code to GNAT@.
27644 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
27645 the following issues may or may not arise for Ada 2005 programs
27646 when other compilers appear.)
27648 @table @emph
27649 @item Ada 83 Pragmas and Attributes
27650 Ada 95 compilers are allowed, but not required, to implement the missing
27651 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
27652 GNAT implements all such pragmas and attributes, eliminating this as
27653 a compatibility concern, but some other Ada 95 compilers reject these
27654 pragmas and attributes.
27656 @item Specialized Needs Annexes
27657 GNAT implements the full set of special needs annexes.  At the
27658 current time, it is the only Ada 95 compiler to do so.  This means that
27659 programs making use of these features may not be portable to other Ada
27660 95 compilation systems.
27662 @item Representation Clauses
27663 Some other Ada 95 compilers implement only the minimal set of
27664 representation clauses required by the Ada 95 reference manual.  GNAT goes
27665 far beyond this minimal set, as described in the next section.
27666 @end table
27668 @node Representation Clauses
27669 @section Representation Clauses
27671 @noindent
27672 The Ada 83 reference manual was quite vague in describing both the minimal
27673 required implementation of representation clauses, and also their precise
27674 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
27675 minimal set of capabilities required is still quite limited.
27677 GNAT implements the full required set of capabilities in
27678 Ada 95 and Ada 2005, but also goes much further, and in particular
27679 an effort has been made to be compatible with existing Ada 83 usage to the
27680 greatest extent possible.
27682 A few cases exist in which Ada 83 compiler behavior is incompatible with
27683 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
27684 intentional or accidental dependence on specific implementation dependent
27685 characteristics of these Ada 83 compilers.  The following is a list of
27686 the cases most likely to arise in existing Ada 83 code.
27688 @table @emph
27689 @item Implicit Packing
27690 Some Ada 83 compilers allowed a Size specification to cause implicit
27691 packing of an array or record.  This could cause expensive implicit
27692 conversions for change of representation in the presence of derived
27693 types, and the Ada design intends to avoid this possibility.
27694 Subsequent AI's were issued to make it clear that such implicit
27695 change of representation in response to a Size clause is inadvisable,
27696 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27697 Reference Manuals as implementation advice that is followed by GNAT@.
27698 The problem will show up as an error
27699 message rejecting the size clause.  The fix is simply to provide
27700 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27701 a Component_Size clause.
27703 @item Meaning of Size Attribute
27704 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27705 the minimal number of bits required to hold values of the type.  For example,
27706 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27707 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
27708 some 32 in this situation.  This problem will usually show up as a compile
27709 time error, but not always.  It is a good idea to check all uses of the
27710 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
27711 Object_Size can provide a useful way of duplicating the behavior of
27712 some Ada 83 compiler systems.
27714 @item Size of Access Types
27715 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27716 and that therefore it will be the same size as a System.Address value.  This
27717 assumption is true for GNAT in most cases with one exception.  For the case of
27718 a pointer to an unconstrained array type (where the bounds may vary from one
27719 value of the access type to another), the default is to use a ``fat pointer'',
27720 which is represented as two separate pointers, one to the bounds, and one to
27721 the array.  This representation has a number of advantages, including improved
27722 efficiency.  However, it may cause some difficulties in porting existing Ada 83
27723 code which makes the assumption that, for example, pointers fit in 32 bits on
27724 a machine with 32-bit addressing.
27726 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27727 access types in this case (where the designated type is an unconstrained array
27728 type).  These thin pointers are indeed the same size as a System.Address value.
27729 To specify a thin pointer, use a size clause for the type, for example:
27731 @smallexample @c ada
27732 type X is access all String;
27733 for X'Size use Standard'Address_Size;
27734 @end smallexample
27736 @noindent
27737 which will cause the type X to be represented using a single pointer.
27738 When using this representation, the bounds are right behind the array.
27739 This representation is slightly less efficient, and does not allow quite
27740 such flexibility in the use of foreign pointers or in using the
27741 Unrestricted_Access attribute to create pointers to non-aliased objects.
27742 But for any standard portable use of the access type it will work in
27743 a functionally correct manner and allow porting of existing code.
27744 Note that another way of forcing a thin pointer representation
27745 is to use a component size clause for the element size in an array,
27746 or a record representation clause for an access field in a record.
27747 @end table
27749 @ifclear vms
27750 @c This brief section is only in the non-VMS version
27751 @c The complete chapter on HP Ada is in the VMS version
27752 @node Compatibility with HP Ada 83
27753 @section Compatibility with HP Ada 83
27755 @noindent
27756 The VMS version of GNAT fully implements all the pragmas and attributes
27757 provided by HP Ada 83, as well as providing the standard HP Ada 83
27758 libraries, including Starlet.  In addition, data layouts and parameter
27759 passing conventions are highly compatible.  This means that porting
27760 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27761 most other porting efforts.  The following are some of the most
27762 significant differences between GNAT and HP Ada 83.
27764 @table @emph
27765 @item Default floating-point representation
27766 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27767 it is VMS format.  GNAT does implement the necessary pragmas
27768 (Long_Float, Float_Representation) for changing this default.
27770 @item System
27771 The package System in GNAT exactly corresponds to the definition in the
27772 Ada 95 reference manual, which means that it excludes many of the
27773 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
27774 that contains the additional definitions, and a special pragma,
27775 Extend_System allows this package to be treated transparently as an
27776 extension of package System.
27778 @item To_Address
27779 The definitions provided by Aux_DEC are exactly compatible with those
27780 in the HP Ada 83 version of System, with one exception.
27781 HP Ada provides the following declarations:
27783 @smallexample @c ada
27784 TO_ADDRESS (INTEGER)
27785 TO_ADDRESS (UNSIGNED_LONGWORD)
27786 TO_ADDRESS (@i{universal_integer})
27787 @end smallexample
27789 @noindent
27790 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27791 an extension to Ada 83 not strictly compatible with the reference manual.
27792 In GNAT, we are constrained to be exactly compatible with the standard,
27793 and this means we cannot provide this capability.  In HP Ada 83, the
27794 point of this definition is to deal with a call like:
27796 @smallexample @c ada
27797 TO_ADDRESS (16#12777#);
27798 @end smallexample
27800 @noindent
27801 Normally, according to the Ada 83 standard, one would expect this to be
27802 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27803 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
27804 definition using @i{universal_integer} takes precedence.
27806 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27807 is not possible to be 100% compatible.  Since there are many programs using
27808 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27809 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27810 declarations provided in the GNAT version of AUX_Dec are:
27812 @smallexample @c ada
27813 function To_Address (X : Integer) return Address;
27814 pragma Pure_Function (To_Address);
27816 function To_Address_Long (X : Unsigned_Longword)
27817  return Address;
27818 pragma Pure_Function (To_Address_Long);
27819 @end smallexample
27821 @noindent
27822 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27823 change the name to TO_ADDRESS_LONG@.
27825 @item Task_Id values
27826 The Task_Id values assigned will be different in the two systems, and GNAT
27827 does not provide a specified value for the Task_Id of the environment task,
27828 which in GNAT is treated like any other declared task.
27829 @end table
27831 @noindent
27832 For full details on these and other less significant compatibility issues,
27833 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27834 Overview and Comparison on HP Platforms}.
27836 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27837 attributes are recognized, although only a subset of them can sensibly
27838 be implemented.  The description of pragmas in @ref{Implementation
27839 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27840 indicates whether or not they are applicable to non-VMS systems.
27841 @end ifclear
27843 @ifset vms
27844 @node Transitioning to 64-Bit GNAT for OpenVMS
27845 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
27847 @noindent
27848 This section is meant to assist users of pre-2006 @value{EDITION}
27849 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
27850 the version of the GNAT technology supplied in 2006 and later for
27851 OpenVMS on both Alpha and I64.
27853 @menu
27854 * Introduction to transitioning::
27855 * Migration of 32 bit code::
27856 * Taking advantage of 64 bit addressing::
27857 * Technical details::
27858 @end menu
27860 @node Introduction to transitioning
27861 @subsection Introduction
27863 @noindent
27864 64-bit @value{EDITION} for Open VMS has been designed to meet
27865 three main goals:
27867 @enumerate
27868 @item
27869 Providing a full conforming implementation of Ada 95 and Ada 2005
27871 @item
27872 Allowing maximum backward compatibility, thus easing migration of existing
27873 Ada source code
27875 @item
27876 Supplying a path for exploiting the full 64-bit address range
27877 @end enumerate
27879 @noindent
27880 Ada's strong typing semantics has made it
27881 impractical to have different 32-bit and 64-bit modes. As soon as
27882 one object could possibly be outside the 32-bit address space, this
27883 would make it necessary for the @code{System.Address} type to be 64 bits.
27884 In particular, this would cause inconsistencies if 32-bit code is
27885 called from 64-bit code that raises an exception.
27887 This issue has been resolved by always using 64-bit addressing
27888 at the system level, but allowing for automatic conversions between
27889 32-bit and 64-bit addresses where required. Thus users who
27890 do not currently require 64-bit addressing capabilities, can
27891 recompile their code with only minimal changes (and indeed
27892 if the code is written in portable Ada, with no assumptions about
27893 the size of the @code{Address} type, then no changes at all are necessary).
27894 At the same time,
27895 this approach provides a simple, gradual upgrade path to future
27896 use of larger memories than available for 32-bit systems.
27897 Also, newly written applications or libraries will by default
27898 be fully compatible with future systems exploiting 64-bit
27899 addressing capabilities.
27901 @ref{Migration of 32 bit code}, will focus on porting applications
27902 that do not require more than 2 GB of
27903 addressable memory. This code will be referred to as
27904 @emph{32-bit code}.
27905 For applications intending to exploit the full 64-bit address space,
27906 @ref{Taking advantage of 64 bit addressing},
27907 will consider further changes that may be required.
27908 Such code will be referred to below as @emph{64-bit code}.
27910 @node Migration of 32 bit code
27911 @subsection Migration of 32-bit code
27913 @menu
27914 * Address types::
27915 * Access types and 32/64-bit allocation::
27916 * Unchecked conversions::
27917 * Predefined constants::
27918 * Interfacing with C::
27919 * 32/64-bit descriptors::
27920 * Experience with source compatibility::
27921 @end menu
27923 @node Address types
27924 @subsubsection Address types
27926 @noindent
27927 To solve the problem of mixing 64-bit and 32-bit addressing,
27928 while maintaining maximum backward compatibility, the following
27929 approach has been taken:
27931 @itemize @bullet
27932 @item
27933 @code{System.Address} always has a size of 64 bits
27934 @cindex @code{System.Address} size
27935 @cindex @code{Address} size
27937 @item
27938 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
27939 @cindex @code{System.Short_Address} size
27940 @cindex @code{Short_Address} size
27941 @end itemize
27943 @noindent
27944 Since @code{System.Short_Address} is a subtype of @code{System.Address},
27945 a @code{Short_Address}
27946 may be used where an @code{Address} is required, and vice versa, without
27947 needing explicit type conversions.
27948 By virtue of the Open VMS parameter passing conventions,
27949 even imported
27950 and exported subprograms that have 32-bit address parameters are
27951 compatible with those that have 64-bit address parameters.
27952 (See @ref{Making code 64 bit clean} for details.)
27954 The areas that may need attention are those where record types have
27955 been defined that contain components of the type @code{System.Address}, and
27956 where objects of this type are passed to code expecting a record layout with
27957 32-bit addresses.
27959 Different compilers on different platforms cannot be
27960 expected to represent the same type in the same way,
27961 since alignment constraints
27962 and other system-dependent properties affect the compiler's decision.
27963 For that reason, Ada code
27964 generally uses representation clauses to specify the expected
27965 layout where required.
27967 If such a representation clause uses 32 bits for a component having
27968 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
27969 will detect that error and produce a specific diagnostic message.
27970 The developer should then determine whether the representation
27971 should be 64 bits or not and make either of two changes:
27972 change the size to 64 bits and leave the type as @code{System.Address}, or
27973 leave the size as 32 bits and change the type to @code{System.Short_Address}.
27974 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
27975 required in any code setting or accessing the field; the compiler will
27976 automatically perform any needed conversions between address
27977 formats.
27979 @node Access types and 32/64-bit allocation
27980 @subsubsection Access types and 32/64-bit allocation
27981 @cindex 32-bit allocation
27982 @cindex 64-bit allocation
27984 @noindent
27985 By default, objects designated by access values are always allocated in
27986 the 64-bit address space, and access values themselves are represented
27987 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
27988 is required (for example if the address of an allocated object is assigned
27989 to a @code{Short_Address} variable), then several alternatives are available:
27991 @itemize @bullet
27992 @item
27993 A pool-specific access type (ie, an @w{Ada 83} access type, whose
27994 definition is @code{access T} versus @code{access all T} or
27995 @code{access constant T}), may be declared with a @code{'Size} representation
27996 clause that establishes the size as 32 bits.
27997 In such circumstances allocations for that type will
27998 be from the 32-bit heap.  Such a clause is not permitted
27999 for a general access type (declared with @code{access all} or
28000 @code{access constant}) as values of such types must be able to refer
28001 to any object of the designated type, including objects residing outside
28002 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
28003 type definitions, however, since general access types were introduced
28004 in @w{Ada 95}.
28006 @item
28007 Switches for @command{GNAT BIND} control whether the internal GNAT
28008 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
28009 @cindex @code{__gnat_malloc}
28010 The switches are respectively @option{-H64} (the default) and
28011 @option{-H32}.
28012 @cindex @option{-H32} (@command{gnatbind})
28013 @cindex @option{-H64} (@command{gnatbind})
28015 @item
28016 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
28017 @cindex @code{GNAT$NO_MALLOC_64} environment variable
28018 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
28019 If this variable is left
28020 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
28021 then the default (64-bit) allocation is used.
28022 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
28023 then 32-bit allocation is used.  The gnatbind qualifiers described above
28024 override this logical name.
28026 @item
28027 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
28028 @cindex @option{-mno-malloc64} (^gcc^gcc^)
28029 at a low level to convert explicit calls to @code{malloc} and related
28030 functions from the C run-time library so that they perform allocations
28031 in the 32-bit heap.
28032 Since all internal allocations from GNAT use @code{__gnat_malloc},
28033 this switch is not required unless the program makes explicit calls on
28034 @code{malloc} (or related functions) from interfaced C code.
28035 @end itemize
28038 @node Unchecked conversions
28039 @subsubsection Unchecked conversions
28041 @noindent
28042 In the case of an @code{Unchecked_Conversion} where the source type is a
28043 64-bit access type or the type @code{System.Address}, and the target
28044 type is a 32-bit type, the compiler will generate a warning.
28045 Even though the generated code will still perform the required
28046 conversions, it is highly recommended in these cases to use
28047 respectively a 32-bit access type or @code{System.Short_Address}
28048 as the source type.
28050 @node Predefined constants
28051 @subsubsection Predefined constants
28053 @noindent
28054 The following table shows the correspondence between pre-2006 versions of
28055 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
28056 (``New''):
28058 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
28059 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
28060 @item   @code{System.Word_Size}          @tab 32      @tab 64
28061 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
28062 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
28063 @item   @code{System.Address_Size}       @tab 32      @tab 64
28064 @end multitable
28066 @noindent
28067 If you need to refer to the specific
28068 memory size of a 32-bit implementation, instead of the
28069 actual memory size, use @code{System.Short_Memory_Size}
28070 rather than @code{System.Memory_Size}.
28071 Similarly, references to @code{System.Address_Size} may need
28072 to be replaced by @code{System.Short_Address'Size}.
28073 The program @command{gnatfind} may be useful for locating
28074 references to the above constants, so that you can verify that they
28075 are still correct.
28077 @node Interfacing with C
28078 @subsubsection Interfacing with C
28080 @noindent
28081 In order to minimize the impact of the transition to 64-bit addresses on
28082 legacy programs, some fundamental types in the @code{Interfaces.C}
28083 package hierarchy continue to be represented in 32 bits.
28084 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
28085 This eases integration with the default HP C layout choices, for example
28086 as found in the system routines in @code{DECC$SHR.EXE}.
28087 Because of this implementation choice, the type fully compatible with
28088 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
28089 Depending on the context the compiler will issue a
28090 warning or an error when type @code{Address} is used, alerting the user to a
28091 potential problem. Otherwise 32-bit programs that use
28092 @code{Interfaces.C} should normally not require code modifications
28094 The other issue arising with C interfacing concerns pragma @code{Convention}.
28095 For VMS 64-bit systems, there is an issue of the appropriate default size
28096 of C convention pointers in the absence of an explicit size clause. The HP
28097 C compiler can choose either 32 or 64 bits depending on compiler options.
28098 GNAT chooses 32-bits rather than 64-bits in the default case where no size
28099 clause is given. This proves a better choice for porting 32-bit legacy
28100 applications. In order to have a 64-bit representation, it is necessary to
28101 specify a size representation clause. For example:
28103 @smallexample @c ada
28104 type int_star is access Interfaces.C.int;
28105 pragma Convention(C, int_star);
28106 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
28107 @end smallexample
28109 @node 32/64-bit descriptors
28110 @subsubsection 32/64-bit descriptors
28112 @noindent
28113 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
28114 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
28115 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
28116 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
28117 @cindex @code{Short_Descriptor} mechanism for imported subprograms
28119 If the configuration pragma @code{Short_Descriptors} is supplied, then
28120 all descriptors will be 32 bits.
28121 @cindex pragma @code{Short_Descriptors}
28123 @node Experience with source compatibility
28124 @subsubsection Experience with source compatibility
28126 @noindent
28127 The Security Server and STARLET on I64 provide an interesting ``test case''
28128 for source compatibility issues, since it is in such system code
28129 where assumptions about @code{Address} size might be expected to occur.
28130 Indeed, there were a small number of occasions in the Security Server
28131 file @file{jibdef.ads}
28132 where a representation clause for a record type specified
28133 32 bits for a component of type @code{Address}.
28134 All of these errors were detected by the compiler.
28135 The repair was obvious and immediate; to simply replace @code{Address} by
28136 @code{Short_Address}.
28138 In the case of STARLET, there were several record types that should
28139 have had representation clauses but did not.  In these record types
28140 there was an implicit assumption that an @code{Address} value occupied
28141 32 bits.
28142 These compiled without error, but their usage resulted in run-time error
28143 returns from STARLET system calls.
28144 Future GNAT technology enhancements may include a tool that detects and flags
28145 these sorts of potential source code porting problems.
28147 @c ****************************************
28148 @node Taking advantage of 64 bit addressing
28149 @subsection Taking advantage of 64-bit addressing
28151 @menu
28152 * Making code 64 bit clean::
28153 * Allocating memory from the 64 bit storage pool::
28154 * Restrictions on use of 64 bit objects::
28155 * STARLET and other predefined libraries::
28156 @end menu
28158 @node Making code 64 bit clean
28159 @subsubsection Making code 64-bit clean
28161 @noindent
28162 In order to prevent problems that may occur when (parts of) a
28163 system start using memory outside the 32-bit address range,
28164 we recommend some additional guidelines:
28166 @itemize @bullet
28167 @item
28168 For imported subprograms that take parameters of the
28169 type @code{System.Address}, ensure that these subprograms can
28170 indeed handle 64-bit addresses. If not, or when in doubt,
28171 change the subprogram declaration to specify
28172 @code{System.Short_Address} instead.
28174 @item
28175 Resolve all warnings related to size mismatches in
28176 unchecked conversions. Failing to do so causes
28177 erroneous execution if the source object is outside
28178 the 32-bit address space.
28180 @item
28181 (optional) Explicitly use the 32-bit storage pool
28182 for access types used in a 32-bit context, or use
28183 generic access types where possible
28184 (@pxref{Restrictions on use of 64 bit objects}).
28185 @end itemize
28187 @noindent
28188 If these rules are followed, the compiler will automatically insert
28189 any necessary checks to ensure that no addresses or access values
28190 passed to 32-bit code ever refer to objects outside the 32-bit
28191 address range.
28192 Any attempt to do this will raise @code{Constraint_Error}.
28194 @node Allocating memory from the 64 bit storage pool
28195 @subsubsection Allocating memory from the 64-bit storage pool
28197 @noindent
28198 By default, all allocations -- for both pool-specific and general
28199 access types -- use the 64-bit storage pool.  To override
28200 this default, for an individual access type or globally, see
28201 @ref{Access types and 32/64-bit allocation}.
28203 @node Restrictions on use of 64 bit objects
28204 @subsubsection Restrictions on use of 64-bit objects
28206 @noindent
28207 Taking the address of an object allocated from a 64-bit storage pool,
28208 and then passing this address to a subprogram expecting
28209 @code{System.Short_Address},
28210 or assigning it to a variable of type @code{Short_Address}, will cause
28211 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
28212 (@pxref{Making code 64 bit clean}), or checks are suppressed,
28213 no exception is raised and execution
28214 will become erroneous.
28216 @node STARLET and other predefined libraries
28217 @subsubsection STARLET and other predefined libraries
28219 @noindent
28220 All code that comes as part of GNAT is 64-bit clean, but the
28221 restrictions given in @ref{Restrictions on use of 64 bit objects},
28222 still apply. Look at the package
28223 specs to see in which contexts objects allocated
28224 in 64-bit address space are acceptable.
28226 @node Technical details
28227 @subsection Technical details
28229 @noindent
28230 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
28231 Ada standard with respect to the type of @code{System.Address}. Previous
28232 versions of @value{EDITION} have defined this type as private and implemented it as a
28233 modular type.
28235 In order to allow defining @code{System.Short_Address} as a proper subtype,
28236 and to match the implicit sign extension in parameter passing,
28237 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
28238 visible (i.e., non-private) integer type.
28239 Standard operations on the type, such as the binary operators ``+'', ``-'',
28240 etc., that take @code{Address} operands and return an @code{Address} result,
28241 have been hidden by declaring these
28242 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
28243 ambiguities that would otherwise result from overloading.
28244 (Note that, although @code{Address} is a visible integer type,
28245 good programming practice dictates against exploiting the type's
28246 integer properties such as literals, since this will compromise
28247 code portability.)
28249 Defining @code{Address} as a visible integer type helps achieve
28250 maximum compatibility for existing Ada code,
28251 without sacrificing the capabilities of the 64-bit architecture.
28252 @end ifset
28254 @c ************************************************
28255 @ifset unw
28256 @node Microsoft Windows Topics
28257 @appendix Microsoft Windows Topics
28258 @cindex Windows NT
28259 @cindex Windows 95
28260 @cindex Windows 98
28262 @noindent
28263 This chapter describes topics that are specific to the Microsoft Windows
28264 platforms (NT, 2000, and XP Professional).
28266 @menu
28267 * Using GNAT on Windows::
28268 * Using a network installation of GNAT::
28269 * CONSOLE and WINDOWS subsystems::
28270 * Temporary Files::
28271 * Mixed-Language Programming on Windows::
28272 * Windows Calling Conventions::
28273 * Introduction to Dynamic Link Libraries (DLLs)::
28274 * Using DLLs with GNAT::
28275 * Building DLLs with GNAT Project files::
28276 * Building DLLs with GNAT::
28277 * Building DLLs with gnatdll::
28278 * GNAT and Windows Resources::
28279 * Debugging a DLL::
28280 * Setting Stack Size from gnatlink::
28281 * Setting Heap Size from gnatlink::
28282 @end menu
28284 @node Using GNAT on Windows
28285 @section Using GNAT on Windows
28287 @noindent
28288 One of the strengths of the GNAT technology is that its tool set
28289 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
28290 @code{gdb} debugger, etc.) is used in the same way regardless of the
28291 platform.
28293 On Windows this tool set is complemented by a number of Microsoft-specific
28294 tools that have been provided to facilitate interoperability with Windows
28295 when this is required. With these tools:
28297 @itemize @bullet
28299 @item
28300 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
28301 subsystems.
28303 @item
28304 You can use any Dynamically Linked Library (DLL) in your Ada code (both
28305 relocatable and non-relocatable DLLs are supported).
28307 @item
28308 You can build Ada DLLs for use in other applications. These applications
28309 can be written in a language other than Ada (e.g., C, C++, etc). Again both
28310 relocatable and non-relocatable Ada DLLs are supported.
28312 @item
28313 You can include Windows resources in your Ada application.
28315 @item
28316 You can use or create COM/DCOM objects.
28317 @end itemize
28319 @noindent
28320 Immediately below are listed all known general GNAT-for-Windows restrictions.
28321 Other restrictions about specific features like Windows Resources and DLLs
28322 are listed in separate sections below.
28324 @itemize @bullet
28326 @item
28327 It is not possible to use @code{GetLastError} and @code{SetLastError}
28328 when tasking, protected records, or exceptions are used. In these
28329 cases, in order to implement Ada semantics, the GNAT run-time system
28330 calls certain Win32 routines that set the last error variable to 0 upon
28331 success. It should be possible to use @code{GetLastError} and
28332 @code{SetLastError} when tasking, protected record, and exception
28333 features are not used, but it is not guaranteed to work.
28335 @item
28336 It is not possible to link against Microsoft C++ libraries except for
28337 import libraries. Interfacing must be done by the mean of DLLs.
28339 @item
28340 It is possible to link against Microsoft C libraries. Yet the preferred
28341 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
28342 doesn't require having two different development environments and makes the
28343 inter-language debugging experience smoother.
28345 @item
28346 When the compilation environment is located on FAT32 drives, users may
28347 experience recompilations of the source files that have not changed if
28348 Daylight Saving Time (DST) state has changed since the last time files
28349 were compiled. NTFS drives do not have this problem.
28351 @item
28352 No components of the GNAT toolset use any entries in the Windows
28353 registry. The only entries that can be created are file associations and
28354 PATH settings, provided the user has chosen to create them at installation
28355 time, as well as some minimal book-keeping information needed to correctly
28356 uninstall or integrate different GNAT products.
28357 @end itemize
28359 @node Using a network installation of GNAT
28360 @section Using a network installation of GNAT
28362 @noindent
28363 Make sure the system on which GNAT is installed is accessible from the
28364 current machine, i.e., the install location is shared over the network.
28365 Shared resources are accessed on Windows by means of UNC paths, which
28366 have the format @code{\\server\sharename\path}
28368 In order to use such a network installation, simply add the UNC path of the
28369 @file{bin} directory of your GNAT installation in front of your PATH. For
28370 example, if GNAT is installed in @file{\GNAT} directory of a share location
28371 called @file{c-drive} on a machine @file{LOKI}, the following command will
28372 make it available:
28374 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
28376 Be aware that every compilation using the network installation results in the
28377 transfer of large amounts of data across the network and will likely cause
28378 serious performance penalty.
28380 @node CONSOLE and WINDOWS subsystems
28381 @section CONSOLE and WINDOWS subsystems
28382 @cindex CONSOLE Subsystem
28383 @cindex WINDOWS Subsystem
28384 @cindex -mwindows
28386 @noindent
28387 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
28388 (which is the default subsystem) will always create a console when
28389 launching the application. This is not something desirable when the
28390 application has a Windows GUI. To get rid of this console the
28391 application must be using the @code{WINDOWS} subsystem. To do so
28392 the @option{-mwindows} linker option must be specified.
28394 @smallexample
28395 $ gnatmake winprog -largs -mwindows
28396 @end smallexample
28398 @node Temporary Files
28399 @section Temporary Files
28400 @cindex Temporary files
28402 @noindent
28403 It is possible to control where temporary files gets created by setting
28404 the @env{TMP} environment variable. The file will be created:
28406 @itemize
28407 @item Under the directory pointed to by the @env{TMP} environment variable if
28408 this directory exists.
28410 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
28411 set (or not pointing to a directory) and if this directory exists.
28413 @item Under the current working directory otherwise.
28414 @end itemize
28416 @noindent
28417 This allows you to determine exactly where the temporary
28418 file will be created. This is particularly useful in networked
28419 environments where you may not have write access to some
28420 directories.
28422 @node Mixed-Language Programming on Windows
28423 @section Mixed-Language Programming on Windows
28425 @noindent
28426 Developing pure Ada applications on Windows is no different than on
28427 other GNAT-supported platforms. However, when developing or porting an
28428 application that contains a mix of Ada and C/C++, the choice of your
28429 Windows C/C++ development environment conditions your overall
28430 interoperability strategy.
28432 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
28433 your application, there are no Windows-specific restrictions that
28434 affect the overall interoperability with your Ada code. If you do want
28435 to use the Microsoft tools for your C++ code, you have two choices:
28437 @enumerate
28438 @item
28439 Encapsulate your C++ code in a DLL to be linked with your Ada
28440 application. In this case, use the Microsoft or whatever environment to
28441 build the DLL and use GNAT to build your executable
28442 (@pxref{Using DLLs with GNAT}).
28444 @item
28445 Or you can encapsulate your Ada code in a DLL to be linked with the
28446 other part of your application. In this case, use GNAT to build the DLL
28447 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
28448 or whatever environment to build your executable.
28449 @end enumerate
28451 In addition to the description about C main in
28452 @pxref{Mixed Language Programming} section, if the C main uses a
28453 stand-alone library it is required on x86-windows to
28454 setup the SEH context. For this the C main must looks like this:
28456 @smallexample
28457 /* main.c */
28458 extern void adainit (void);
28459 extern void adafinal (void);
28460 extern void __gnat_initialize(void*);
28461 extern void call_to_ada (void);
28463 int main (int argc, char *argv[])
28465   int SEH [2];
28467   /* Initialize the SEH context */
28468   __gnat_initialize (&SEH);
28470   adainit();
28472   /* Then call Ada services in the stand-alone library */
28474   call_to_ada();
28476   adafinal();
28478 @end smallexample
28480 Note that this is not needed on x86_64-windows where the Windows
28481 native SEH support is used.
28483 @node Windows Calling Conventions
28484 @section Windows Calling Conventions
28485 @findex Stdcall
28486 @findex APIENTRY
28488 This section pertain only to Win32. On Win64 there is a single native
28489 calling convention. All convention specifiers are ignored on this
28490 platform.
28492 @menu
28493 * C Calling Convention::
28494 * Stdcall Calling Convention::
28495 * Win32 Calling Convention::
28496 * DLL Calling Convention::
28497 @end menu
28499 @noindent
28500 When a subprogram @code{F} (caller) calls a subprogram @code{G}
28501 (callee), there are several ways to push @code{G}'s parameters on the
28502 stack and there are several possible scenarios to clean up the stack
28503 upon @code{G}'s return. A calling convention is an agreed upon software
28504 protocol whereby the responsibilities between the caller (@code{F}) and
28505 the callee (@code{G}) are clearly defined. Several calling conventions
28506 are available for Windows:
28508 @itemize @bullet
28509 @item
28510 @code{C} (Microsoft defined)
28512 @item
28513 @code{Stdcall} (Microsoft defined)
28515 @item
28516 @code{Win32} (GNAT specific)
28518 @item
28519 @code{DLL} (GNAT specific)
28520 @end itemize
28522 @node C Calling Convention
28523 @subsection @code{C} Calling Convention
28525 @noindent
28526 This is the default calling convention used when interfacing to C/C++
28527 routines compiled with either @command{gcc} or Microsoft Visual C++.
28529 In the @code{C} calling convention subprogram parameters are pushed on the
28530 stack by the caller from right to left. The caller itself is in charge of
28531 cleaning up the stack after the call. In addition, the name of a routine
28532 with @code{C} calling convention is mangled by adding a leading underscore.
28534 The name to use on the Ada side when importing (or exporting) a routine
28535 with @code{C} calling convention is the name of the routine. For
28536 instance the C function:
28538 @smallexample
28539 int get_val (long);
28540 @end smallexample
28542 @noindent
28543 should be imported from Ada as follows:
28545 @smallexample @c ada
28546 @group
28547 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28548 pragma Import (C, Get_Val, External_Name => "get_val");
28549 @end group
28550 @end smallexample
28552 @noindent
28553 Note that in this particular case the @code{External_Name} parameter could
28554 have been omitted since, when missing, this parameter is taken to be the
28555 name of the Ada entity in lower case. When the @code{Link_Name} parameter
28556 is missing, as in the above example, this parameter is set to be the
28557 @code{External_Name} with a leading underscore.
28559 When importing a variable defined in C, you should always use the @code{C}
28560 calling convention unless the object containing the variable is part of a
28561 DLL (in which case you should use the @code{Stdcall} calling
28562 convention, @pxref{Stdcall Calling Convention}).
28564 @node Stdcall Calling Convention
28565 @subsection @code{Stdcall} Calling Convention
28567 @noindent
28568 This convention, which was the calling convention used for Pascal
28569 programs, is used by Microsoft for all the routines in the Win32 API for
28570 efficiency reasons. It must be used to import any routine for which this
28571 convention was specified.
28573 In the @code{Stdcall} calling convention subprogram parameters are pushed
28574 on the stack by the caller from right to left. The callee (and not the
28575 caller) is in charge of cleaning the stack on routine exit. In addition,
28576 the name of a routine with @code{Stdcall} calling convention is mangled by
28577 adding a leading underscore (as for the @code{C} calling convention) and a
28578 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
28579 bytes) of the parameters passed to the routine.
28581 The name to use on the Ada side when importing a C routine with a
28582 @code{Stdcall} calling convention is the name of the C routine. The leading
28583 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
28584 the compiler. For instance the Win32 function:
28586 @smallexample
28587 @b{APIENTRY} int get_val (long);
28588 @end smallexample
28590 @noindent
28591 should be imported from Ada as follows:
28593 @smallexample @c ada
28594 @group
28595 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28596 pragma Import (Stdcall, Get_Val);
28597 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
28598 @end group
28599 @end smallexample
28601 @noindent
28602 As for the @code{C} calling convention, when the @code{External_Name}
28603 parameter is missing, it is taken to be the name of the Ada entity in lower
28604 case. If instead of writing the above import pragma you write:
28606 @smallexample @c ada
28607 @group
28608 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28609 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
28610 @end group
28611 @end smallexample
28613 @noindent
28614 then the imported routine is @code{_retrieve_val@@4}. However, if instead
28615 of specifying the @code{External_Name} parameter you specify the
28616 @code{Link_Name} as in the following example:
28618 @smallexample @c ada
28619 @group
28620 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28621 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
28622 @end group
28623 @end smallexample
28625 @noindent
28626 then the imported routine is @code{retrieve_val}, that is, there is no
28627 decoration at all. No leading underscore and no Stdcall suffix
28628 @code{@@}@code{@var{nn}}.
28630 @noindent
28631 This is especially important as in some special cases a DLL's entry
28632 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
28633 name generated for a call has it.
28635 @noindent
28636 It is also possible to import variables defined in a DLL by using an
28637 import pragma for a variable. As an example, if a DLL contains a
28638 variable defined as:
28640 @smallexample
28641 int my_var;
28642 @end smallexample
28644 @noindent
28645 then, to access this variable from Ada you should write:
28647 @smallexample @c ada
28648 @group
28649 My_Var : Interfaces.C.int;
28650 pragma Import (Stdcall, My_Var);
28651 @end group
28652 @end smallexample
28654 @noindent
28655 Note that to ease building cross-platform bindings this convention
28656 will be handled as a @code{C} calling convention on non-Windows platforms.
28658 @node Win32 Calling Convention
28659 @subsection @code{Win32} Calling Convention
28661 @noindent
28662 This convention, which is GNAT-specific is fully equivalent to the
28663 @code{Stdcall} calling convention described above.
28665 @node DLL Calling Convention
28666 @subsection @code{DLL} Calling Convention
28668 @noindent
28669 This convention, which is GNAT-specific is fully equivalent to the
28670 @code{Stdcall} calling convention described above.
28672 @node Introduction to Dynamic Link Libraries (DLLs)
28673 @section Introduction to Dynamic Link Libraries (DLLs)
28674 @findex DLL
28676 @noindent
28677 A Dynamically Linked Library (DLL) is a library that can be shared by
28678 several applications running under Windows. A DLL can contain any number of
28679 routines and variables.
28681 One advantage of DLLs is that you can change and enhance them without
28682 forcing all the applications that depend on them to be relinked or
28683 recompiled. However, you should be aware than all calls to DLL routines are
28684 slower since, as you will understand below, such calls are indirect.
28686 To illustrate the remainder of this section, suppose that an application
28687 wants to use the services of a DLL @file{API.dll}. To use the services
28688 provided by @file{API.dll} you must statically link against the DLL or
28689 an import library which contains a jump table with an entry for each
28690 routine and variable exported by the DLL. In the Microsoft world this
28691 import library is called @file{API.lib}. When using GNAT this import
28692 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
28693 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
28695 After you have linked your application with the DLL or the import library
28696 and you run your application, here is what happens:
28698 @enumerate
28699 @item
28700 Your application is loaded into memory.
28702 @item
28703 The DLL @file{API.dll} is mapped into the address space of your
28704 application. This means that:
28706 @itemize @bullet
28707 @item
28708 The DLL will use the stack of the calling thread.
28710 @item
28711 The DLL will use the virtual address space of the calling process.
28713 @item
28714 The DLL will allocate memory from the virtual address space of the calling
28715 process.
28717 @item
28718 Handles (pointers) can be safely exchanged between routines in the DLL
28719 routines and routines in the application using the DLL.
28720 @end itemize
28722 @item
28723 The entries in the jump table (from the import library @file{libAPI.dll.a}
28724 or @file{API.lib} or automatically created when linking against a DLL)
28725 which is part of your application are initialized with the addresses
28726 of the routines and variables in @file{API.dll}.
28728 @item
28729 If present in @file{API.dll}, routines @code{DllMain} or
28730 @code{DllMainCRTStartup} are invoked. These routines typically contain
28731 the initialization code needed for the well-being of the routines and
28732 variables exported by the DLL.
28733 @end enumerate
28735 @noindent
28736 There is an additional point which is worth mentioning. In the Windows
28737 world there are two kind of DLLs: relocatable and non-relocatable
28738 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
28739 in the target application address space. If the addresses of two
28740 non-relocatable DLLs overlap and these happen to be used by the same
28741 application, a conflict will occur and the application will run
28742 incorrectly. Hence, when possible, it is always preferable to use and
28743 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
28744 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
28745 User's Guide) removes the debugging symbols from the DLL but the DLL can
28746 still be relocated.
28748 As a side note, an interesting difference between Microsoft DLLs and
28749 Unix shared libraries, is the fact that on most Unix systems all public
28750 routines are exported by default in a Unix shared library, while under
28751 Windows it is possible (but not required) to list exported routines in
28752 a definition file (@pxref{The Definition File}).
28754 @node Using DLLs with GNAT
28755 @section Using DLLs with GNAT
28757 @menu
28758 * Creating an Ada Spec for the DLL Services::
28759 * Creating an Import Library::
28760 @end menu
28762 @noindent
28763 To use the services of a DLL, say @file{API.dll}, in your Ada application
28764 you must have:
28766 @enumerate
28767 @item
28768 The Ada spec for the routines and/or variables you want to access in
28769 @file{API.dll}. If not available this Ada spec must be built from the C/C++
28770 header files provided with the DLL.
28772 @item
28773 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
28774 mentioned an import library is a statically linked library containing the
28775 import table which will be filled at load time to point to the actual
28776 @file{API.dll} routines. Sometimes you don't have an import library for the
28777 DLL you want to use. The following sections will explain how to build
28778 one. Note that this is optional.
28780 @item
28781 The actual DLL, @file{API.dll}.
28782 @end enumerate
28784 @noindent
28785 Once you have all the above, to compile an Ada application that uses the
28786 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
28787 you simply issue the command
28789 @smallexample
28790 $ gnatmake my_ada_app -largs -lAPI
28791 @end smallexample
28793 @noindent
28794 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
28795 tells the GNAT linker to look for an import library. The linker will
28796 look for a library name in this specific order:
28798 @enumerate
28799 @item @file{libAPI.dll.a}
28800 @item @file{API.dll.a}
28801 @item @file{libAPI.a}
28802 @item @file{API.lib}
28803 @item @file{libAPI.dll}
28804 @item @file{API.dll}
28805 @end enumerate
28807 The first three are the GNU style import libraries. The third is the
28808 Microsoft style import libraries. The last two are the actual DLL names.
28810 Note that if the Ada package spec for @file{API.dll} contains the
28811 following pragma
28813 @smallexample @c ada
28814 pragma Linker_Options ("-lAPI");
28815 @end smallexample
28817 @noindent
28818 you do not have to add @option{-largs -lAPI} at the end of the
28819 @command{gnatmake} command.
28821 If any one of the items above is missing you will have to create it
28822 yourself. The following sections explain how to do so using as an
28823 example a fictitious DLL called @file{API.dll}.
28825 @node Creating an Ada Spec for the DLL Services
28826 @subsection Creating an Ada Spec for the DLL Services
28828 @noindent
28829 A DLL typically comes with a C/C++ header file which provides the
28830 definitions of the routines and variables exported by the DLL. The Ada
28831 equivalent of this header file is a package spec that contains definitions
28832 for the imported entities. If the DLL you intend to use does not come with
28833 an Ada spec you have to generate one such spec yourself. For example if
28834 the header file of @file{API.dll} is a file @file{api.h} containing the
28835 following two definitions:
28837 @smallexample
28838 @group
28839 @cartouche
28840 int some_var;
28841 int get (char *);
28842 @end cartouche
28843 @end group
28844 @end smallexample
28846 @noindent
28847 then the equivalent Ada spec could be:
28849 @smallexample @c ada
28850 @group
28851 @cartouche
28852 with Interfaces.C.Strings;
28853 package API is
28854    use Interfaces;
28856    Some_Var : C.int;
28857    function Get (Str : C.Strings.Chars_Ptr) return C.int;
28859 private
28860    pragma Import (C, Get);
28861    pragma Import (DLL, Some_Var);
28862 end API;
28863 @end cartouche
28864 @end group
28865 @end smallexample
28867 @noindent
28868 Note that a variable is
28869 @strong{always imported with a DLL convention}. A function
28870 can have @code{C} or @code{Stdcall} convention.
28871 (@pxref{Windows Calling Conventions}).
28873 @node Creating an Import Library
28874 @subsection Creating an Import Library
28875 @cindex Import library
28877 @menu
28878 * The Definition File::
28879 * GNAT-Style Import Library::
28880 * Microsoft-Style Import Library::
28881 @end menu
28883 @noindent
28884 If a Microsoft-style import library @file{API.lib} or a GNAT-style
28885 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
28886 with @file{API.dll} you can skip this section. You can also skip this
28887 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
28888 as in this case it is possible to link directly against the
28889 DLL. Otherwise read on.
28891 @node The Definition File
28892 @subsubsection The Definition File
28893 @cindex Definition file
28894 @findex .def
28896 @noindent
28897 As previously mentioned, and unlike Unix systems, the list of symbols
28898 that are exported from a DLL must be provided explicitly in Windows.
28899 The main goal of a definition file is precisely that: list the symbols
28900 exported by a DLL. A definition file (usually a file with a @code{.def}
28901 suffix) has the following structure:
28903 @smallexample
28904 @group
28905 @cartouche
28906 @r{[}LIBRARY @var{name}@r{]}
28907 @r{[}DESCRIPTION @var{string}@r{]}
28908 EXPORTS
28909    @var{symbol1}
28910    @var{symbol2}
28911    @dots{}
28912 @end cartouche
28913 @end group
28914 @end smallexample
28916 @table @code
28917 @item LIBRARY @var{name}
28918 This section, which is optional, gives the name of the DLL.
28920 @item DESCRIPTION @var{string}
28921 This section, which is optional, gives a description string that will be
28922 embedded in the import library.
28924 @item EXPORTS
28925 This section gives the list of exported symbols (procedures, functions or
28926 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
28927 section of @file{API.def} looks like:
28929 @smallexample
28930 @group
28931 @cartouche
28932 EXPORTS
28933    some_var
28934    get
28935 @end cartouche
28936 @end group
28937 @end smallexample
28938 @end table
28940 @noindent
28941 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28942 (@pxref{Windows Calling Conventions}) for a Stdcall
28943 calling convention function in the exported symbols list.
28945 @noindent
28946 There can actually be other sections in a definition file, but these
28947 sections are not relevant to the discussion at hand.
28949 @node GNAT-Style Import Library
28950 @subsubsection GNAT-Style Import Library
28952 @noindent
28953 To create a static import library from @file{API.dll} with the GNAT tools
28954 you should proceed as follows:
28956 @enumerate
28957 @item
28958 Create the definition file @file{API.def} (@pxref{The Definition File}).
28959 For that use the @code{dll2def} tool as follows:
28961 @smallexample
28962 $ dll2def API.dll > API.def
28963 @end smallexample
28965 @noindent
28966 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28967 to standard output the list of entry points in the DLL. Note that if
28968 some routines in the DLL have the @code{Stdcall} convention
28969 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28970 suffix then you'll have to edit @file{api.def} to add it, and specify
28971 @option{-k} to @command{gnatdll} when creating the import library.
28973 @noindent
28974 Here are some hints to find the right @code{@@}@var{nn} suffix.
28976 @enumerate
28977 @item
28978 If you have the Microsoft import library (.lib), it is possible to get
28979 the right symbols by using Microsoft @code{dumpbin} tool (see the
28980 corresponding Microsoft documentation for further details).
28982 @smallexample
28983 $ dumpbin /exports api.lib
28984 @end smallexample
28986 @item
28987 If you have a message about a missing symbol at link time the compiler
28988 tells you what symbol is expected. You just have to go back to the
28989 definition file and add the right suffix.
28990 @end enumerate
28992 @item
28993 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28994 (@pxref{Using gnatdll}) as follows:
28996 @smallexample
28997 $ gnatdll -e API.def -d API.dll
28998 @end smallexample
29000 @noindent
29001 @code{gnatdll} takes as input a definition file @file{API.def} and the
29002 name of the DLL containing the services listed in the definition file
29003 @file{API.dll}. The name of the static import library generated is
29004 computed from the name of the definition file as follows: if the
29005 definition file name is @var{xyz}@code{.def}, the import library name will
29006 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
29007 @option{-e} could have been removed because the name of the definition
29008 file (before the ``@code{.def}'' suffix) is the same as the name of the
29009 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
29010 @end enumerate
29012 @node Microsoft-Style Import Library
29013 @subsubsection Microsoft-Style Import Library
29015 @noindent
29016 With GNAT you can either use a GNAT-style or Microsoft-style import
29017 library. A Microsoft import library is needed only if you plan to make an
29018 Ada DLL available to applications developed with Microsoft
29019 tools (@pxref{Mixed-Language Programming on Windows}).
29021 To create a Microsoft-style import library for @file{API.dll} you
29022 should proceed as follows:
29024 @enumerate
29025 @item
29026 Create the definition file @file{API.def} from the DLL. For this use either
29027 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
29028 tool (see the corresponding Microsoft documentation for further details).
29030 @item
29031 Build the actual import library using Microsoft's @code{lib} utility:
29033 @smallexample
29034 $ lib -machine:IX86 -def:API.def -out:API.lib
29035 @end smallexample
29037 @noindent
29038 If you use the above command the definition file @file{API.def} must
29039 contain a line giving the name of the DLL:
29041 @smallexample
29042 LIBRARY      "API"
29043 @end smallexample
29045 @noindent
29046 See the Microsoft documentation for further details about the usage of
29047 @code{lib}.
29048 @end enumerate
29050 @node Building DLLs with GNAT Project files
29051 @section Building DLLs with GNAT Project files
29052 @cindex DLLs, building
29054 @noindent
29055 There is nothing specific to Windows in the build process.
29056 @pxref{Library Projects}.
29058 @noindent
29059 Due to a system limitation, it is not possible under Windows to create threads
29060 when inside the @code{DllMain} routine which is used for auto-initialization
29061 of shared libraries, so it is not possible to have library level tasks in SALs.
29063 @node Building DLLs with GNAT
29064 @section Building DLLs with GNAT
29065 @cindex DLLs, building
29067 @noindent
29068 This section explain how to build DLLs using the GNAT built-in DLL
29069 support. With the following procedure it is straight forward to build
29070 and use DLLs with GNAT.
29072 @enumerate
29074 @item building object files
29076 The first step is to build all objects files that are to be included
29077 into the DLL. This is done by using the standard @command{gnatmake} tool.
29079 @item building the DLL
29081 To build the DLL you must use @command{gcc}'s @option{-shared} and
29082 @option{-shared-libgcc} options. It is quite simple to use this method:
29084 @smallexample
29085 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
29086 @end smallexample
29088 It is important to note that in this case all symbols found in the
29089 object files are automatically exported. It is possible to restrict
29090 the set of symbols to export by passing to @command{gcc} a definition
29091 file, @pxref{The Definition File}. For example:
29093 @smallexample
29094 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
29095 @end smallexample
29097 If you use a definition file you must export the elaboration procedures
29098 for every package that required one. Elaboration procedures are named
29099 using the package name followed by "_E".
29101 @item preparing DLL to be used
29103 For the DLL to be used by client programs the bodies must be hidden
29104 from it and the .ali set with read-only attribute. This is very important
29105 otherwise GNAT will recompile all packages and will not actually use
29106 the code in the DLL. For example:
29108 @smallexample
29109 $ mkdir apilib
29110 $ copy *.ads *.ali api.dll apilib
29111 $ attrib +R apilib\*.ali
29112 @end smallexample
29114 @end enumerate
29116 At this point it is possible to use the DLL by directly linking
29117 against it. Note that you must use the GNAT shared runtime when using
29118 GNAT shared libraries. This is achieved by using @option{-shared} binder's
29119 option.
29121 @smallexample
29122 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
29123 @end smallexample
29125 @node Building DLLs with gnatdll
29126 @section Building DLLs with gnatdll
29127 @cindex DLLs, building
29129 @menu
29130 * Limitations When Using Ada DLLs from Ada::
29131 * Exporting Ada Entities::
29132 * Ada DLLs and Elaboration::
29133 * Ada DLLs and Finalization::
29134 * Creating a Spec for Ada DLLs::
29135 * Creating the Definition File::
29136 * Using gnatdll::
29137 @end menu
29139 @noindent
29140 Note that it is preferred to use GNAT Project files
29141 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
29142 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
29144 This section explains how to build DLLs containing Ada code using
29145 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
29146 remainder of this section.
29148 The steps required to build an Ada DLL that is to be used by Ada as well as
29149 non-Ada applications are as follows:
29151 @enumerate
29152 @item
29153 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
29154 @code{Stdcall} calling convention to avoid any Ada name mangling for the
29155 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
29156 skip this step if you plan to use the Ada DLL only from Ada applications.
29158 @item
29159 Your Ada code must export an initialization routine which calls the routine
29160 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
29161 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
29162 routine exported by the Ada DLL must be invoked by the clients of the DLL
29163 to initialize the DLL.
29165 @item
29166 When useful, the DLL should also export a finalization routine which calls
29167 routine @code{adafinal} generated by @command{gnatbind} to perform the
29168 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
29169 The finalization routine exported by the Ada DLL must be invoked by the
29170 clients of the DLL when the DLL services are no further needed.
29172 @item
29173 You must provide a spec for the services exported by the Ada DLL in each
29174 of the programming languages to which you plan to make the DLL available.
29176 @item
29177 You must provide a definition file listing the exported entities
29178 (@pxref{The Definition File}).
29180 @item
29181 Finally you must use @code{gnatdll} to produce the DLL and the import
29182 library (@pxref{Using gnatdll}).
29183 @end enumerate
29185 @noindent
29186 Note that a relocatable DLL stripped using the @code{strip}
29187 binutils tool will not be relocatable anymore. To build a DLL without
29188 debug information pass @code{-largs -s} to @code{gnatdll}. This
29189 restriction does not apply to a DLL built using a Library Project.
29190 @pxref{Library Projects}.
29192 @node Limitations When Using Ada DLLs from Ada
29193 @subsection Limitations When Using Ada DLLs from Ada
29195 @noindent
29196 When using Ada DLLs from Ada applications there is a limitation users
29197 should be aware of. Because on Windows the GNAT run time is not in a DLL of
29198 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
29199 each Ada DLL includes the services of the GNAT run time that are necessary
29200 to the Ada code inside the DLL. As a result, when an Ada program uses an
29201 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
29202 one in the main program.
29204 It is therefore not possible to exchange GNAT run-time objects between the
29205 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
29206 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
29207 types, etc.
29209 It is completely safe to exchange plain elementary, array or record types,
29210 Windows object handles, etc.
29212 @node Exporting Ada Entities
29213 @subsection Exporting Ada Entities
29214 @cindex Export table
29216 @noindent
29217 Building a DLL is a way to encapsulate a set of services usable from any
29218 application. As a result, the Ada entities exported by a DLL should be
29219 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
29220 any Ada name mangling. As an example here is an Ada package
29221 @code{API}, spec and body, exporting two procedures, a function, and a
29222 variable:
29224 @smallexample @c ada
29225 @group
29226 @cartouche
29227 with Interfaces.C; use Interfaces;
29228 package API is
29229    Count : C.int := 0;
29230    function Factorial (Val : C.int) return C.int;
29232    procedure Initialize_API;
29233    procedure Finalize_API;
29234    --  Initialization & Finalization routines. More in the next section.
29235 private
29236    pragma Export (C, Initialize_API);
29237    pragma Export (C, Finalize_API);
29238    pragma Export (C, Count);
29239    pragma Export (C, Factorial);
29240 end API;
29241 @end cartouche
29242 @end group
29243 @end smallexample
29245 @smallexample @c ada
29246 @group
29247 @cartouche
29248 package body API is
29249    function Factorial (Val : C.int) return C.int is
29250       Fact : C.int := 1;
29251    begin
29252       Count := Count + 1;
29253       for K in 1 .. Val loop
29254          Fact := Fact * K;
29255       end loop;
29256       return Fact;
29257    end Factorial;
29259    procedure Initialize_API is
29260       procedure Adainit;
29261       pragma Import (C, Adainit);
29262    begin
29263       Adainit;
29264    end Initialize_API;
29266    procedure Finalize_API is
29267       procedure Adafinal;
29268       pragma Import (C, Adafinal);
29269    begin
29270       Adafinal;
29271    end Finalize_API;
29272 end API;
29273 @end cartouche
29274 @end group
29275 @end smallexample
29277 @noindent
29278 If the Ada DLL you are building will only be used by Ada applications
29279 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
29280 convention. As an example, the previous package could be written as
29281 follows:
29283 @smallexample @c ada
29284 @group
29285 @cartouche
29286 package API is
29287    Count : Integer := 0;
29288    function Factorial (Val : Integer) return Integer;
29290    procedure Initialize_API;
29291    procedure Finalize_API;
29292    --  Initialization and Finalization routines.
29293 end API;
29294 @end cartouche
29295 @end group
29296 @end smallexample
29298 @smallexample @c ada
29299 @group
29300 @cartouche
29301 package body API is
29302    function Factorial (Val : Integer) return Integer is
29303       Fact : Integer := 1;
29304    begin
29305       Count := Count + 1;
29306       for K in 1 .. Val loop
29307          Fact := Fact * K;
29308       end loop;
29309       return Fact;
29310    end Factorial;
29312    @dots{}
29313    --  The remainder of this package body is unchanged.
29314 end API;
29315 @end cartouche
29316 @end group
29317 @end smallexample
29319 @noindent
29320 Note that if you do not export the Ada entities with a @code{C} or
29321 @code{Stdcall} convention you will have to provide the mangled Ada names
29322 in the definition file of the Ada DLL
29323 (@pxref{Creating the Definition File}).
29325 @node Ada DLLs and Elaboration
29326 @subsection Ada DLLs and Elaboration
29327 @cindex DLLs and elaboration
29329 @noindent
29330 The DLL that you are building contains your Ada code as well as all the
29331 routines in the Ada library that are needed by it. The first thing a
29332 user of your DLL must do is elaborate the Ada code
29333 (@pxref{Elaboration Order Handling in GNAT}).
29335 To achieve this you must export an initialization routine
29336 (@code{Initialize_API} in the previous example), which must be invoked
29337 before using any of the DLL services. This elaboration routine must call
29338 the Ada elaboration routine @code{adainit} generated by the GNAT binder
29339 (@pxref{Binding with Non-Ada Main Programs}). See the body of
29340 @code{Initialize_Api} for an example. Note that the GNAT binder is
29341 automatically invoked during the DLL build process by the @code{gnatdll}
29342 tool (@pxref{Using gnatdll}).
29344 When a DLL is loaded, Windows systematically invokes a routine called
29345 @code{DllMain}. It would therefore be possible to call @code{adainit}
29346 directly from @code{DllMain} without having to provide an explicit
29347 initialization routine. Unfortunately, it is not possible to call
29348 @code{adainit} from the @code{DllMain} if your program has library level
29349 tasks because access to the @code{DllMain} entry point is serialized by
29350 the system (that is, only a single thread can execute ``through'' it at a
29351 time), which means that the GNAT run time will deadlock waiting for the
29352 newly created task to complete its initialization.
29354 @node Ada DLLs and Finalization
29355 @subsection Ada DLLs and Finalization
29356 @cindex DLLs and finalization
29358 @noindent
29359 When the services of an Ada DLL are no longer needed, the client code should
29360 invoke the DLL finalization routine, if available. The DLL finalization
29361 routine is in charge of releasing all resources acquired by the DLL. In the
29362 case of the Ada code contained in the DLL, this is achieved by calling
29363 routine @code{adafinal} generated by the GNAT binder
29364 (@pxref{Binding with Non-Ada Main Programs}).
29365 See the body of @code{Finalize_Api} for an
29366 example. As already pointed out the GNAT binder is automatically invoked
29367 during the DLL build process by the @code{gnatdll} tool
29368 (@pxref{Using gnatdll}).
29370 @node Creating a Spec for Ada DLLs
29371 @subsection Creating a Spec for Ada DLLs
29373 @noindent
29374 To use the services exported by the Ada DLL from another programming
29375 language (e.g.@: C), you have to translate the specs of the exported Ada
29376 entities in that language. For instance in the case of @code{API.dll},
29377 the corresponding C header file could look like:
29379 @smallexample
29380 @group
29381 @cartouche
29382 extern int *_imp__count;
29383 #define count (*_imp__count)
29384 int factorial (int);
29385 @end cartouche
29386 @end group
29387 @end smallexample
29389 @noindent
29390 It is important to understand that when building an Ada DLL to be used by
29391 other Ada applications, you need two different specs for the packages
29392 contained in the DLL: one for building the DLL and the other for using
29393 the DLL. This is because the @code{DLL} calling convention is needed to
29394 use a variable defined in a DLL, but when building the DLL, the variable
29395 must have either the @code{Ada} or @code{C} calling convention. As an
29396 example consider a DLL comprising the following package @code{API}:
29398 @smallexample @c ada
29399 @group
29400 @cartouche
29401 package API is
29402    Count : Integer := 0;
29403    @dots{}
29404    --  Remainder of the package omitted.
29405 end API;
29406 @end cartouche
29407 @end group
29408 @end smallexample
29410 @noindent
29411 After producing a DLL containing package @code{API}, the spec that
29412 must be used to import @code{API.Count} from Ada code outside of the
29413 DLL is:
29415 @smallexample @c ada
29416 @group
29417 @cartouche
29418 package API is
29419    Count : Integer;
29420    pragma Import (DLL, Count);
29421 end API;
29422 @end cartouche
29423 @end group
29424 @end smallexample
29426 @node Creating the Definition File
29427 @subsection Creating the Definition File
29429 @noindent
29430 The definition file is the last file needed to build the DLL. It lists
29431 the exported symbols. As an example, the definition file for a DLL
29432 containing only package @code{API} (where all the entities are exported
29433 with a @code{C} calling convention) is:
29435 @smallexample
29436 @group
29437 @cartouche
29438 EXPORTS
29439     count
29440     factorial
29441     finalize_api
29442     initialize_api
29443 @end cartouche
29444 @end group
29445 @end smallexample
29447 @noindent
29448 If the @code{C} calling convention is missing from package @code{API},
29449 then the definition file contains the mangled Ada names of the above
29450 entities, which in this case are:
29452 @smallexample
29453 @group
29454 @cartouche
29455 EXPORTS
29456     api__count
29457     api__factorial
29458     api__finalize_api
29459     api__initialize_api
29460 @end cartouche
29461 @end group
29462 @end smallexample
29464 @node Using gnatdll
29465 @subsection Using @code{gnatdll}
29466 @findex gnatdll
29468 @menu
29469 * gnatdll Example::
29470 * gnatdll behind the Scenes::
29471 * Using dlltool::
29472 @end menu
29474 @noindent
29475 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
29476 and non-Ada sources that make up your DLL have been compiled.
29477 @code{gnatdll} is actually in charge of two distinct tasks: build the
29478 static import library for the DLL and the actual DLL. The form of the
29479 @code{gnatdll} command is
29481 @smallexample
29482 @cartouche
29483 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29484 @c Expanding @ovar macro inline (explanation in macro def comments)
29485 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29486 @end cartouche
29487 @end smallexample
29489 @noindent
29490 where @var{list-of-files} is a list of ALI and object files. The object
29491 file list must be the exact list of objects corresponding to the non-Ada
29492 sources whose services are to be included in the DLL. The ALI file list
29493 must be the exact list of ALI files for the corresponding Ada sources
29494 whose services are to be included in the DLL. If @var{list-of-files} is
29495 missing, only the static import library is generated.
29497 @noindent
29498 You may specify any of the following switches to @code{gnatdll}:
29500 @table @code
29501 @c @item -a@ovar{address}
29502 @c Expanding @ovar macro inline (explanation in macro def comments)
29503 @item -a@r{[}@var{address}@r{]}
29504 @cindex @option{-a} (@code{gnatdll})
29505 Build a non-relocatable DLL at @var{address}. If @var{address} is not
29506 specified the default address @var{0x11000000} will be used. By default,
29507 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
29508 advise the reader to build relocatable DLL.
29510 @item -b @var{address}
29511 @cindex @option{-b} (@code{gnatdll})
29512 Set the relocatable DLL base address. By default the address is
29513 @code{0x11000000}.
29515 @item -bargs @var{opts}
29516 @cindex @option{-bargs} (@code{gnatdll})
29517 Binder options. Pass @var{opts} to the binder.
29519 @item -d @var{dllfile}
29520 @cindex @option{-d} (@code{gnatdll})
29521 @var{dllfile} is the name of the DLL. This switch must be present for
29522 @code{gnatdll} to do anything. The name of the generated import library is
29523 obtained algorithmically from @var{dllfile} as shown in the following
29524 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
29525 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
29526 by option @option{-e}) is obtained algorithmically from @var{dllfile}
29527 as shown in the following example:
29528 if @var{dllfile} is @code{xyz.dll}, the definition
29529 file used is @code{xyz.def}.
29531 @item -e @var{deffile}
29532 @cindex @option{-e} (@code{gnatdll})
29533 @var{deffile} is the name of the definition file.
29535 @item -g
29536 @cindex @option{-g} (@code{gnatdll})
29537 Generate debugging information. This information is stored in the object
29538 file and copied from there to the final DLL file by the linker,
29539 where it can be read by the debugger. You must use the
29540 @option{-g} switch if you plan on using the debugger or the symbolic
29541 stack traceback.
29543 @item -h
29544 @cindex @option{-h} (@code{gnatdll})
29545 Help mode. Displays @code{gnatdll} switch usage information.
29547 @item -Idir
29548 @cindex @option{-I} (@code{gnatdll})
29549 Direct @code{gnatdll} to search the @var{dir} directory for source and
29550 object files needed to build the DLL.
29551 (@pxref{Search Paths and the Run-Time Library (RTL)}).
29553 @item -k
29554 @cindex @option{-k} (@code{gnatdll})
29555 Removes the @code{@@}@var{nn} suffix from the import library's exported
29556 names, but keeps them for the link names. You must specify this
29557 option if you want to use a @code{Stdcall} function in a DLL for which
29558 the @code{@@}@var{nn} suffix has been removed. This is the case for most
29559 of the Windows NT DLL for example. This option has no effect when
29560 @option{-n} option is specified.
29562 @item -l @var{file}
29563 @cindex @option{-l} (@code{gnatdll})
29564 The list of ALI and object files used to build the DLL are listed in
29565 @var{file}, instead of being given in the command line. Each line in
29566 @var{file} contains the name of an ALI or object file.
29568 @item -n
29569 @cindex @option{-n} (@code{gnatdll})
29570 No Import. Do not create the import library.
29572 @item -q
29573 @cindex @option{-q} (@code{gnatdll})
29574 Quiet mode. Do not display unnecessary messages.
29576 @item -v
29577 @cindex @option{-v} (@code{gnatdll})
29578 Verbose mode. Display extra information.
29580 @item -largs @var{opts}
29581 @cindex @option{-largs} (@code{gnatdll})
29582 Linker options. Pass @var{opts} to the linker.
29583 @end table
29585 @node gnatdll Example
29586 @subsubsection @code{gnatdll} Example
29588 @noindent
29589 As an example the command to build a relocatable DLL from @file{api.adb}
29590 once @file{api.adb} has been compiled and @file{api.def} created is
29592 @smallexample
29593 $ gnatdll -d api.dll api.ali
29594 @end smallexample
29596 @noindent
29597 The above command creates two files: @file{libapi.dll.a} (the import
29598 library) and @file{api.dll} (the actual DLL). If you want to create
29599 only the DLL, just type:
29601 @smallexample
29602 $ gnatdll -d api.dll -n api.ali
29603 @end smallexample
29605 @noindent
29606 Alternatively if you want to create just the import library, type:
29608 @smallexample
29609 $ gnatdll -d api.dll
29610 @end smallexample
29612 @node gnatdll behind the Scenes
29613 @subsubsection @code{gnatdll} behind the Scenes
29615 @noindent
29616 This section details the steps involved in creating a DLL. @code{gnatdll}
29617 does these steps for you. Unless you are interested in understanding what
29618 goes on behind the scenes, you should skip this section.
29620 We use the previous example of a DLL containing the Ada package @code{API},
29621 to illustrate the steps necessary to build a DLL. The starting point is a
29622 set of objects that will make up the DLL and the corresponding ALI
29623 files. In the case of this example this means that @file{api.o} and
29624 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
29625 the following:
29627 @enumerate
29628 @item
29629 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
29630 the information necessary to generate relocation information for the
29631 DLL.
29633 @smallexample
29634 @group
29635 $ gnatbind -n api
29636 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
29637 @end group
29638 @end smallexample
29640 @noindent
29641 In addition to the base file, the @command{gnatlink} command generates an
29642 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
29643 asks @command{gnatlink} to generate the routines @code{DllMain} and
29644 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
29645 is loaded into memory.
29647 @item
29648 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
29649 export table (@file{api.exp}). The export table contains the relocation
29650 information in a form which can be used during the final link to ensure
29651 that the Windows loader is able to place the DLL anywhere in memory.
29653 @smallexample
29654 @group
29655 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29656           --output-exp api.exp
29657 @end group
29658 @end smallexample
29660 @item
29661 @code{gnatdll} builds the base file using the new export table. Note that
29662 @command{gnatbind} must be called once again since the binder generated file
29663 has been deleted during the previous call to @command{gnatlink}.
29665 @smallexample
29666 @group
29667 $ gnatbind -n api
29668 $ gnatlink api -o api.jnk api.exp -mdll
29669       -Wl,--base-file,api.base
29670 @end group
29671 @end smallexample
29673 @item
29674 @code{gnatdll} builds the new export table using the new base file and
29675 generates the DLL import library @file{libAPI.dll.a}.
29677 @smallexample
29678 @group
29679 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29680           --output-exp api.exp --output-lib libAPI.a
29681 @end group
29682 @end smallexample
29684 @item
29685 Finally @code{gnatdll} builds the relocatable DLL using the final export
29686 table.
29688 @smallexample
29689 @group
29690 $ gnatbind -n api
29691 $ gnatlink api api.exp -o api.dll -mdll
29692 @end group
29693 @end smallexample
29694 @end enumerate
29696 @node Using dlltool
29697 @subsubsection Using @code{dlltool}
29699 @noindent
29700 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
29701 DLLs and static import libraries. This section summarizes the most
29702 common @code{dlltool} switches. The form of the @code{dlltool} command
29705 @smallexample
29706 @c $ dlltool @ovar{switches}
29707 @c Expanding @ovar macro inline (explanation in macro def comments)
29708 $ dlltool @r{[}@var{switches}@r{]}
29709 @end smallexample
29711 @noindent
29712 @code{dlltool} switches include:
29714 @table @option
29715 @item --base-file @var{basefile}
29716 @cindex @option{--base-file} (@command{dlltool})
29717 Read the base file @var{basefile} generated by the linker. This switch
29718 is used to create a relocatable DLL.
29720 @item --def @var{deffile}
29721 @cindex @option{--def} (@command{dlltool})
29722 Read the definition file.
29724 @item --dllname @var{name}
29725 @cindex @option{--dllname} (@command{dlltool})
29726 Gives the name of the DLL. This switch is used to embed the name of the
29727 DLL in the static import library generated by @code{dlltool} with switch
29728 @option{--output-lib}.
29730 @item -k
29731 @cindex @option{-k} (@command{dlltool})
29732 Kill @code{@@}@var{nn} from exported names
29733 (@pxref{Windows Calling Conventions}
29734 for a discussion about @code{Stdcall}-style symbols.
29736 @item --help
29737 @cindex @option{--help} (@command{dlltool})
29738 Prints the @code{dlltool} switches with a concise description.
29740 @item --output-exp @var{exportfile}
29741 @cindex @option{--output-exp} (@command{dlltool})
29742 Generate an export file @var{exportfile}. The export file contains the
29743 export table (list of symbols in the DLL) and is used to create the DLL.
29745 @item --output-lib @var{libfile}
29746 @cindex @option{--output-lib} (@command{dlltool})
29747 Generate a static import library @var{libfile}.
29749 @item -v
29750 @cindex @option{-v} (@command{dlltool})
29751 Verbose mode.
29753 @item --as @var{assembler-name}
29754 @cindex @option{--as} (@command{dlltool})
29755 Use @var{assembler-name} as the assembler. The default is @code{as}.
29756 @end table
29758 @node GNAT and Windows Resources
29759 @section GNAT and Windows Resources
29760 @cindex Resources, windows
29762 @menu
29763 * Building Resources::
29764 * Compiling Resources::
29765 * Using Resources::
29766 @end menu
29768 @noindent
29769 Resources are an easy way to add Windows specific objects to your
29770 application. The objects that can be added as resources include:
29772 @itemize @bullet
29773 @item menus
29775 @item accelerators
29777 @item dialog boxes
29779 @item string tables
29781 @item bitmaps
29783 @item cursors
29785 @item icons
29787 @item fonts
29789 @item version information
29790 @end itemize
29792 For example, a version information resource can be defined as follow and
29793 embedded into an executable or DLL:
29795 A version information resource can be used to embed information into an
29796 executable or a DLL. These information can be viewed using the file properties
29797 from the Windows Explorer. Here is an example of a version information
29798 resource:
29800 @smallexample
29801 @group
29802 1 VERSIONINFO
29803 FILEVERSION     1,0,0,0
29804 PRODUCTVERSION  1,0,0,0
29805 BEGIN
29806   BLOCK "StringFileInfo"
29807   BEGIN
29808     BLOCK "080904E4"
29809     BEGIN
29810       VALUE "CompanyName", "My Company Name"
29811       VALUE "FileDescription", "My application"
29812       VALUE "FileVersion", "1.0"
29813       VALUE "InternalName", "my_app"
29814       VALUE "LegalCopyright", "My Name"
29815       VALUE "OriginalFilename", "my_app.exe"
29816       VALUE "ProductName", "My App"
29817       VALUE "ProductVersion", "1.0"
29818     END
29819   END
29821   BLOCK "VarFileInfo"
29822   BEGIN
29823     VALUE "Translation", 0x809, 1252
29824   END
29826 @end group
29827 @end smallexample
29829 The value @code{0809} (langID) is for the U.K English language and
29830 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
29831 multilingual.
29833 @noindent
29834 This section explains how to build, compile and use resources. Note that this
29835 section does not cover all resource objects, for a complete description see
29836 the corresponding Microsoft documentation.
29838 @node Building Resources
29839 @subsection Building Resources
29840 @cindex Resources, building
29842 @noindent
29843 A resource file is an ASCII file. By convention resource files have an
29844 @file{.rc} extension.
29845 The easiest way to build a resource file is to use Microsoft tools
29846 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
29847 @code{dlgedit.exe} to build dialogs.
29848 It is always possible to build an @file{.rc} file yourself by writing a
29849 resource script.
29851 It is not our objective to explain how to write a resource file. A
29852 complete description of the resource script language can be found in the
29853 Microsoft documentation.
29855 @node Compiling Resources
29856 @subsection Compiling Resources
29857 @findex rc
29858 @findex windres
29859 @cindex Resources, compiling
29861 @noindent
29862 This section describes how to build a GNAT-compatible (COFF) object file
29863 containing the resources. This is done using the Resource Compiler
29864 @code{windres} as follows:
29866 @smallexample
29867 $ windres -i myres.rc -o myres.o
29868 @end smallexample
29870 @noindent
29871 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
29872 file. You can specify an alternate preprocessor (usually named
29873 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
29874 parameter. A list of all possible options may be obtained by entering
29875 the command @code{windres} @option{--help}.
29877 It is also possible to use the Microsoft resource compiler @code{rc.exe}
29878 to produce a @file{.res} file (binary resource file). See the
29879 corresponding Microsoft documentation for further details. In this case
29880 you need to use @code{windres} to translate the @file{.res} file to a
29881 GNAT-compatible object file as follows:
29883 @smallexample
29884 $ windres -i myres.res -o myres.o
29885 @end smallexample
29887 @node Using Resources
29888 @subsection Using Resources
29889 @cindex Resources, using
29891 @noindent
29892 To include the resource file in your program just add the
29893 GNAT-compatible object file for the resource(s) to the linker
29894 arguments. With @command{gnatmake} this is done by using the @option{-largs}
29895 option:
29897 @smallexample
29898 $ gnatmake myprog -largs myres.o
29899 @end smallexample
29901 @node Debugging a DLL
29902 @section Debugging a DLL
29903 @cindex DLL debugging
29905 @menu
29906 * Program and DLL Both Built with GCC/GNAT::
29907 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
29908 @end menu
29910 @noindent
29911 Debugging a DLL is similar to debugging a standard program. But
29912 we have to deal with two different executable parts: the DLL and the
29913 program that uses it. We have the following four possibilities:
29915 @enumerate 1
29916 @item
29917 The program and the DLL are built with @code{GCC/GNAT}.
29918 @item
29919 The program is built with foreign tools and the DLL is built with
29920 @code{GCC/GNAT}.
29921 @item
29922 The program is built with @code{GCC/GNAT} and the DLL is built with
29923 foreign tools.
29924 @end enumerate
29926 @noindent
29927 In this section we address only cases one and two above.
29928 There is no point in trying to debug
29929 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
29930 information in it. To do so you must use a debugger compatible with the
29931 tools suite used to build the DLL.
29933 @node Program and DLL Both Built with GCC/GNAT
29934 @subsection Program and DLL Both Built with GCC/GNAT
29936 @noindent
29937 This is the simplest case. Both the DLL and the program have @code{GDB}
29938 compatible debugging information. It is then possible to break anywhere in
29939 the process. Let's suppose here that the main procedure is named
29940 @code{ada_main} and that in the DLL there is an entry point named
29941 @code{ada_dll}.
29943 @noindent
29944 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29945 program must have been built with the debugging information (see GNAT -g
29946 switch). Here are the step-by-step instructions for debugging it:
29948 @enumerate 1
29949 @item Launch @code{GDB} on the main program.
29951 @smallexample
29952 $ gdb -nw ada_main
29953 @end smallexample
29955 @item Start the program and stop at the beginning of the main procedure
29957 @smallexample
29958 (gdb) start
29959 @end smallexample
29961 @noindent
29962 This step is required to be able to set a breakpoint inside the DLL. As long
29963 as the program is not run, the DLL is not loaded. This has the
29964 consequence that the DLL debugging information is also not loaded, so it is not
29965 possible to set a breakpoint in the DLL.
29967 @item Set a breakpoint inside the DLL
29969 @smallexample
29970 (gdb) break ada_dll
29971 (gdb) cont
29972 @end smallexample
29974 @end enumerate
29976 @noindent
29977 At this stage a breakpoint is set inside the DLL. From there on
29978 you can use the standard approach to debug the whole program
29979 (@pxref{Running and Debugging Ada Programs}).
29981 @ignore
29982 @c This used to work, probably because the DLLs were non-relocatable
29983 @c keep this section around until the problem is sorted out.
29985 To break on the @code{DllMain} routine it is not possible to follow
29986 the procedure above. At the time the program stop on @code{ada_main}
29987 the @code{DllMain} routine as already been called. Either you can use
29988 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29990 @enumerate 1
29991 @item Launch @code{GDB} on the main program.
29993 @smallexample
29994 $ gdb ada_main
29995 @end smallexample
29997 @item Load DLL symbols
29999 @smallexample
30000 (gdb) add-sym api.dll
30001 @end smallexample
30003 @item Set a breakpoint inside the DLL
30005 @smallexample
30006 (gdb) break ada_dll.adb:45
30007 @end smallexample
30009 Note that at this point it is not possible to break using the routine symbol
30010 directly as the program is not yet running. The solution is to break
30011 on the proper line (break in @file{ada_dll.adb} line 45).
30013 @item Start the program
30015 @smallexample
30016 (gdb) run
30017 @end smallexample
30019 @end enumerate
30020 @end ignore
30022 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
30023 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
30025 @menu
30026 * Debugging the DLL Directly::
30027 * Attaching to a Running Process::
30028 @end menu
30030 @noindent
30031 In this case things are slightly more complex because it is not possible to
30032 start the main program and then break at the beginning to load the DLL and the
30033 associated DLL debugging information. It is not possible to break at the
30034 beginning of the program because there is no @code{GDB} debugging information,
30035 and therefore there is no direct way of getting initial control. This
30036 section addresses this issue by describing some methods that can be used
30037 to break somewhere in the DLL to debug it.
30039 @noindent
30040 First suppose that the main procedure is named @code{main} (this is for
30041 example some C code built with Microsoft Visual C) and that there is a
30042 DLL named @code{test.dll} containing an Ada entry point named
30043 @code{ada_dll}.
30045 @noindent
30046 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
30047 been built with debugging information (see GNAT -g option).
30049 @node Debugging the DLL Directly
30050 @subsubsection Debugging the DLL Directly
30052 @enumerate 1
30053 @item
30054 Find out the executable starting address
30056 @smallexample
30057 $ objdump --file-header main.exe
30058 @end smallexample
30060 The starting address is reported on the last line. For example:
30062 @smallexample
30063 main.exe:     file format pei-i386
30064 architecture: i386, flags 0x0000010a:
30065 EXEC_P, HAS_DEBUG, D_PAGED
30066 start address 0x00401010
30067 @end smallexample
30069 @item
30070 Launch the debugger on the executable.
30072 @smallexample
30073 $ gdb main.exe
30074 @end smallexample
30076 @item
30077 Set a breakpoint at the starting address, and launch the program.
30079 @smallexample
30080 $ (gdb) break *0x00401010
30081 $ (gdb) run
30082 @end smallexample
30084 The program will stop at the given address.
30086 @item
30087 Set a breakpoint on a DLL subroutine.
30089 @smallexample
30090 (gdb) break ada_dll.adb:45
30091 @end smallexample
30093 Or if you want to break using a symbol on the DLL, you need first to
30094 select the Ada language (language used by the DLL).
30096 @smallexample
30097 (gdb) set language ada
30098 (gdb) break ada_dll
30099 @end smallexample
30101 @item
30102 Continue the program.
30104 @smallexample
30105 (gdb) cont
30106 @end smallexample
30108 @noindent
30109 This will run the program until it reaches the breakpoint that has been
30110 set. From that point you can use the standard way to debug a program
30111 as described in (@pxref{Running and Debugging Ada Programs}).
30113 @end enumerate
30115 @noindent
30116 It is also possible to debug the DLL by attaching to a running process.
30118 @node Attaching to a Running Process
30119 @subsubsection Attaching to a Running Process
30120 @cindex DLL debugging, attach to process
30122 @noindent
30123 With @code{GDB} it is always possible to debug a running process by
30124 attaching to it. It is possible to debug a DLL this way. The limitation
30125 of this approach is that the DLL must run long enough to perform the
30126 attach operation. It may be useful for instance to insert a time wasting
30127 loop in the code of the DLL to meet this criterion.
30129 @enumerate 1
30131 @item Launch the main program @file{main.exe}.
30133 @smallexample
30134 $ main
30135 @end smallexample
30137 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
30138 that the process PID for @file{main.exe} is 208.
30140 @item Launch gdb.
30142 @smallexample
30143 $ gdb
30144 @end smallexample
30146 @item Attach to the running process to be debugged.
30148 @smallexample
30149 (gdb) attach 208
30150 @end smallexample
30152 @item Load the process debugging information.
30154 @smallexample
30155 (gdb) symbol-file main.exe
30156 @end smallexample
30158 @item Break somewhere in the DLL.
30160 @smallexample
30161 (gdb) break ada_dll
30162 @end smallexample
30164 @item Continue process execution.
30166 @smallexample
30167 (gdb) cont
30168 @end smallexample
30170 @end enumerate
30172 @noindent
30173 This last step will resume the process execution, and stop at
30174 the breakpoint we have set. From there you can use the standard
30175 approach to debug a program as described in
30176 (@pxref{Running and Debugging Ada Programs}).
30178 @node Setting Stack Size from gnatlink
30179 @section Setting Stack Size from @command{gnatlink}
30181 @noindent
30182 It is possible to specify the program stack size at link time. On modern
30183 versions of Windows, starting with XP, this is mostly useful to set the size of
30184 the main stack (environment task). The other task stacks are set with pragma
30185 Storage_Size or with the @command{gnatbind -d} command.
30187 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
30188 reserve size of individual tasks, the link-time stack size applies to all
30189 tasks, and pragma Storage_Size has no effect.
30190 In particular, Stack Overflow checks are made against this
30191 link-time specified size.
30193 This setting can be done with
30194 @command{gnatlink} using either:
30196 @itemize @bullet
30198 @item using @option{-Xlinker} linker option
30200 @smallexample
30201 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
30202 @end smallexample
30204 This sets the stack reserve size to 0x10000 bytes and the stack commit
30205 size to 0x1000 bytes.
30207 @item using @option{-Wl} linker option
30209 @smallexample
30210 $ gnatlink hello -Wl,--stack=0x1000000
30211 @end smallexample
30213 This sets the stack reserve size to 0x1000000 bytes. Note that with
30214 @option{-Wl} option it is not possible to set the stack commit size
30215 because the coma is a separator for this option.
30217 @end itemize
30219 @node Setting Heap Size from gnatlink
30220 @section Setting Heap Size from @command{gnatlink}
30222 @noindent
30223 Under Windows systems, it is possible to specify the program heap size from
30224 @command{gnatlink} using either:
30226 @itemize @bullet
30228 @item using @option{-Xlinker} linker option
30230 @smallexample
30231 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
30232 @end smallexample
30234 This sets the heap reserve size to 0x10000 bytes and the heap commit
30235 size to 0x1000 bytes.
30237 @item using @option{-Wl} linker option
30239 @smallexample
30240 $ gnatlink hello -Wl,--heap=0x1000000
30241 @end smallexample
30243 This sets the heap reserve size to 0x1000000 bytes. Note that with
30244 @option{-Wl} option it is not possible to set the heap commit size
30245 because the coma is a separator for this option.
30247 @end itemize
30249 @node Mac OS Topics
30250 @appendix Mac OS Topics
30251 @cindex OS X
30253 @noindent
30254 This chapter describes topics that are specific to Apple's OS X
30255 platform.
30257 @menu
30258 * Codesigning the Debugger::
30259 @end menu
30261 @node Codesigning the Debugger
30262 @section Codesigning the Debugger
30264 @noindent
30265 The Darwin Kernel requires the debugger to have special permissions
30266 before it is allowed to control other processes. These permissions
30267 are granted by codesigning the GDB executable. Without these
30268 permissions, the debugger will report error messages such as:
30270 @smallexample
30271 Starting program: /x/y/foo
30272 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
30273  (please check gdb is codesigned - see taskgated(8))
30274 @end smallexample
30276 Codesigning requires a certificate.  The following procedure explains
30277 how to create one:
30279 @itemize @bullet
30280 @item Start the Keychain Access application (in
30281 /Applications/Utilities/Keychain Access.app)
30283 @item Select the Keychain Access -> Certificate Assistant ->
30284 Create a Certificate... menu
30286 @item Then:
30288 @itemize @bullet
30289 @item Choose a name for the new certificate (this procedure will use
30290 "gdb-cert" as an example)
30292 @item Set "Identity Type" to "Self Signed Root"
30294 @item Set "Certificate Type" to "Code Signing"
30296 @item Activate the "Let me override defaults" option
30298 @end itemize
30300 @item Click several times on "Continue" until the "Specify a Location
30301 For The Certificate" screen appears, then set "Keychain" to "System"
30303 @item Click on "Continue" until the certificate is created
30305 @item Finally, in the view, double-click on the new certificate,
30306 and set "When using this certificate" to "Always Trust"
30308 @item Exit the Keychain Access application and restart the computer
30309 (this is unfortunately required)
30311 @end itemize
30313 Once a certificate has been created, the debugger can be codesigned
30314 as follow. In a Terminal, run the following command...
30316 @smallexample
30317 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
30318 @end smallexample
30320 ... where "gdb-cert" should be replaced by the actual certificate
30321 name chosen above, and <gnat_install_prefix> should be replaced by
30322 the location where you installed GNAT.
30324 @end ifset
30326 @c **********************************
30327 @c * GNU Free Documentation License *
30328 @c **********************************
30329 @include fdl.texi
30330 @c GNU Free Documentation License
30332 @node Index,,GNU Free Documentation License, Top
30333 @unnumbered Index
30335 @printindex cp
30337 @contents
30338 @c Put table of contents at end, otherwise it precedes the "title page" in
30339 @c the .txt version
30340 @c Edit the pdf file to move the contents to the beginning, after the title
30341 @c page
30343 @bye