2013-02-06 Robert Dewar <dewar@adacore.com>
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blobf36faff47014c9d2beb44967c398d315267f702d
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 effect if this switch is present.
4060 @item -fno-inline-functions
4061 @cindex @option{-fno-inline-functions} (@command{gcc})
4062 Suppresses automatic inlining of subprograms, which is enabled
4063 if @option{-O3} is used.
4065 @item -fno-inline-small-functions
4066 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4067 Suppresses automatic inlining of small subprograms, which is enabled
4068 if @option{-O2} is used.
4070 @item -fno-inline-functions-called-once
4071 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4072 Suppresses inlining of subprograms local to the unit and called once
4073 from within it, which is enabled if @option{-O1} is used.
4075 @item -fno-ivopts
4076 @cindex @option{-fno-ivopts} (@command{gcc})
4077 Suppresses high-level loop induction variable optimizations, which are
4078 enabled if @option{-O1} is used. These optimizations are generally
4079 profitable but, for some specific cases of loops with numerous uses
4080 of the iteration variable that follow a common pattern, they may end
4081 up destroying the regularity that could be exploited at a lower level
4082 and thus producing inferior code.
4084 @item -fno-strict-aliasing
4085 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4086 Causes the compiler to avoid assumptions regarding non-aliasing
4087 of objects of different types. See
4088 @ref{Optimization and Strict Aliasing} for details.
4090 @item -fstack-check
4091 @cindex @option{-fstack-check} (@command{gcc})
4092 Activates stack checking.
4093 See @ref{Stack Overflow Checking} for details.
4095 @item -fstack-usage
4096 @cindex @option{-fstack-usage} (@command{gcc})
4097 Makes the compiler output stack usage information for the program, on a
4098 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4100 @item ^-g^/DEBUG^
4101 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4102 Generate debugging information. This information is stored in the object
4103 file and copied from there to the final executable file by the linker,
4104 where it can be read by the debugger. You must use the
4105 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4107 @item -gnat83
4108 @cindex @option{-gnat83} (@command{gcc})
4109 Enforce Ada 83 restrictions.
4111 @item -gnat95
4112 @cindex @option{-gnat95} (@command{gcc})
4113 Enforce Ada 95 restrictions.
4115 @item -gnat05
4116 @cindex @option{-gnat05} (@command{gcc})
4117 Allow full Ada 2005 features.
4119 @item -gnat2005
4120 @cindex @option{-gnat2005} (@command{gcc})
4121 Allow full Ada 2005 features (same as @option{-gnat05})
4123 @item -gnat12
4124 @cindex @option{-gnat12} (@command{gcc})
4126 @item -gnat2012
4127 @cindex @option{-gnat2012} (@command{gcc})
4128 Allow full Ada 2012 features (same as @option{-gnat12})
4130 @item -gnata
4131 @cindex @option{-gnata} (@command{gcc})
4132 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4133 activated. Note that these pragmas can also be controlled using the
4134 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4135 It also activates pragmas @code{Check}, @code{Precondition}, and
4136 @code{Postcondition}. Note that these pragmas can also be controlled
4137 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
4138 also activates all assertions defined in the RM as aspects: preconditions,
4139 postconditions, type invariants and (sub)type predicates. In all Ada modes,
4140 corresponding pragmas for type invariants and (sub)type predicates are
4141 also activated.
4143 @item -gnatA
4144 @cindex @option{-gnatA} (@command{gcc})
4145 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4146 it will be ignored.
4148 @item -gnatb
4149 @cindex @option{-gnatb} (@command{gcc})
4150 Generate brief messages to @file{stderr} even if verbose mode set.
4152 @item -gnatB
4153 @cindex @option{-gnatB} (@command{gcc})
4154 Assume no invalid (bad) values except for 'Valid attribute use
4155 (@pxref{Validity Checking}).
4157 @item -gnatc
4158 @cindex @option{-gnatc} (@command{gcc})
4159 Check syntax and semantics only (no code generation attempted).
4161 @item -gnatC
4162 @cindex @option{-gnatC} (@command{gcc})
4163 Generate CodePeer information (no code generation attempted).
4164 This switch will generate an intermediate representation suitable for
4165 use by CodePeer (@file{.scil} files). This switch is not compatible with
4166 code generation (it will, among other things, disable some switches such
4167 as -gnatn, and enable others such as -gnata).
4169 @item -gnatd
4170 @cindex @option{-gnatd} (@command{gcc})
4171 Specify debug options for the compiler. The string of characters after
4172 the @option{-gnatd} specify the specific debug options. The possible
4173 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4174 compiler source file @file{debug.adb} for details of the implemented
4175 debug options. Certain debug options are relevant to applications
4176 programmers, and these are documented at appropriate points in this
4177 users guide.
4179 @ifclear vms
4180 @item -gnatD
4181 @cindex @option{-gnatD[nn]} (@command{gcc})
4182 @end ifclear
4183 @ifset vms
4184 @item /XDEBUG /LXDEBUG=nnn
4185 @end ifset
4186 Create expanded source files for source level debugging. This switch
4187 also suppress generation of cross-reference information
4188 (see @option{-gnatx}).
4190 @item ^-gnateA^/ALIASING_CHECK^
4191 @cindex @option{-gnateA} (@command{gcc})
4192 Check that there is no aliasing between two parameters of the same subprogram.
4194 @item -gnatec=@var{path}
4195 @cindex @option{-gnatec} (@command{gcc})
4196 Specify a configuration pragma file
4197 @ifclear vms
4198 (the equal sign is optional)
4199 @end ifclear
4200 (@pxref{The Configuration Pragmas Files}).
4202 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
4203 @cindex @option{-gnated} (@command{gcc})
4204 Disable atomic synchronization
4206 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4207 @cindex @option{-gnateD} (@command{gcc})
4208 Defines a symbol, associated with @var{value}, for preprocessing.
4209 (@pxref{Integrated Preprocessing}).
4211 @item -gnateE
4212 @cindex @option{-gnateE} (@command{gcc})
4213 Generate extra information in exception messages. In particular, display
4214 extra column information and the value and range associated with index and
4215 range check failures, and extra column information for access checks.
4216 In cases where the compiler is able to determine at compile time that
4217 a check will fail, it gives a warning, and the extra information is not
4218 produced at run time.
4220 @item -gnatef
4221 @cindex @option{-gnatef} (@command{gcc})
4222 Display full source path name in brief error messages.
4224 @item -gnateF
4225 @cindex @option{-gnateF} (@command{gcc})
4226 Check for overflow on all floating-point operations, including those
4227 for unconstrained predefined types. See description of pragma
4228 @code{Check_Float_Overflow} in GNAT RM.
4230 @item -gnateG
4231 @cindex @option{-gnateG} (@command{gcc})
4232 Save result of preprocessing in a text file.
4234 @item -gnatei@var{nnn}
4235 @cindex @option{-gnatei} (@command{gcc})
4236 Set maximum number of instantiations during compilation of a single unit to
4237 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
4238 the rare case when a single unit legitimately exceeds this limit.
4240 @item -gnateI@var{nnn}
4241 @cindex @option{-gnateI} (@command{gcc})
4242 Indicates that the source is a multi-unit source and that the index of the
4243 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4244 to be a valid index in the multi-unit source.
4246 @item -gnatem=@var{path}
4247 @cindex @option{-gnatem} (@command{gcc})
4248 Specify a mapping file
4249 @ifclear vms
4250 (the equal sign is optional)
4251 @end ifclear
4252 (@pxref{Units to Sources Mapping Files}).
4254 @item -gnatep=@var{file}
4255 @cindex @option{-gnatep} (@command{gcc})
4256 Specify a preprocessing data file
4257 @ifclear vms
4258 (the equal sign is optional)
4259 @end ifclear
4260 (@pxref{Integrated Preprocessing}).
4262 @item -gnateP
4263 @cindex @option{-gnateP} (@command{gcc})
4264 Turn categorization dependency errors into warnings.
4265 Ada requires that units that WITH one another have compatible categories, for
4266 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4267 these errors become warnings (which can be ignored, or suppressed in the usual
4268 manner). This can be useful in some specialized circumstances such as the
4269 temporary use of special test software.
4271 @item -gnateS
4272 @cindex @option{-gnateS} (@command{gcc})
4273 Synonym of @option{-fdump-scos}, kept for backards compatibility.
4275 @item ^-gnatet^/TARGET_DEPENDENT_INFO^
4276 @cindex @option{-gnatet} (@command{gcc})
4277 Generate target dependent information.
4279 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
4280 @cindex @option{-gnateV} (@command{gcc})
4281 Check validity of subprogram parameters.
4283 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
4284 @cindex @option{-gnateY} (@command{gcc})
4285 Ignore all STYLE_CHECKS pragmas. Full legality checks
4286 are still carried out, but the pragmas have no effect
4287 on what style checks are active. This allows all style
4288 checking options to be controlled from the command line.
4290 @item -gnatE
4291 @cindex @option{-gnatE} (@command{gcc})
4292 Full dynamic elaboration checks.
4294 @item -gnatf
4295 @cindex @option{-gnatf} (@command{gcc})
4296 Full errors. Multiple errors per line, all undefined references, do not
4297 attempt to suppress cascaded errors.
4299 @item -gnatF
4300 @cindex @option{-gnatF} (@command{gcc})
4301 Externals names are folded to all uppercase.
4303 @item ^-gnatg^/GNAT_INTERNAL^
4304 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4305 Internal GNAT implementation mode. This should not be used for
4306 applications programs, it is intended only for use by the compiler
4307 and its run-time library. For documentation, see the GNAT sources.
4308 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4309 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4310 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4311 so that all standard warnings and all standard style options are turned on.
4312 All warnings and style messages are treated as errors.
4314 @ifclear vms
4315 @item -gnatG=nn
4316 @cindex @option{-gnatG[nn]} (@command{gcc})
4317 @end ifclear
4318 @ifset vms
4319 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4320 @end ifset
4321 List generated expanded code in source form.
4323 @item ^-gnath^/HELP^
4324 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4325 Output usage information. The output is written to @file{stdout}.
4327 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4328 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4329 Identifier character set
4330 @ifclear vms
4331 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4332 @end ifclear
4333 For details of the possible selections for @var{c},
4334 see @ref{Character Set Control}.
4336 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4337 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4338 Ignore representation clauses. When this switch is used,
4339 representation clauses are treated as comments. This is useful
4340 when initially porting code where you want to ignore rep clause
4341 problems, and also for compiling foreign code (particularly
4342 for use with ASIS). The representation clauses that are ignored
4343 are: enumeration_representation_clause, record_representation_clause,
4344 and attribute_definition_clause for the following attributes:
4345 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4346 Object_Size, Size, Small, Stream_Size, and Value_Size.
4347 Note that this option should be used only for compiling -- the
4348 code is likely to malfunction at run time.
4350 @item -gnatjnn
4351 @cindex @option{-gnatjnn} (@command{gcc})
4352 Reformat error messages to fit on nn character lines
4354 @item -gnatk=@var{n}
4355 @cindex @option{-gnatk} (@command{gcc})
4356 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4358 @item -gnatl
4359 @cindex @option{-gnatl} (@command{gcc})
4360 Output full source listing with embedded error messages.
4362 @item -gnatL
4363 @cindex @option{-gnatL} (@command{gcc})
4364 Used in conjunction with -gnatG or -gnatD to intersperse original
4365 source lines (as comment lines with line numbers) in the expanded
4366 source output.
4368 @item -gnatm=@var{n}
4369 @cindex @option{-gnatm} (@command{gcc})
4370 Limit number of detected error or warning messages to @var{n}
4371 where @var{n} is in the range 1..999999. The default setting if
4372 no switch is given is 9999. If the number of warnings reaches this
4373 limit, then a message is output and further warnings are suppressed,
4374 but the compilation is continued. If the number of error messages
4375 reaches this limit, then a message is output and the compilation
4376 is abandoned. The equal sign here is optional. A value of zero
4377 means that no limit applies.
4379 @item -gnatn[12]
4380 @cindex @option{-gnatn} (@command{gcc})
4381 Activate inlining for subprograms for which pragma @code{Inline} is
4382 specified. This inlining is performed by the GCC back-end. An optional
4383 digit sets the inlining level: 1 for moderate inlining across modules
4384 or 2 for full inlining across modules. If no inlining level is specified,
4385 the compiler will pick it based on the optimization level.
4387 @item -gnatN
4388 @cindex @option{-gnatN} (@command{gcc})
4389 Activate front end inlining for subprograms for which
4390 pragma @code{Inline} is specified. This inlining is performed
4391 by the front end and will be visible in the
4392 @option{-gnatG} output.
4394 When using a gcc-based back end (in practice this means using any version
4395 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4396 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4397 Historically front end inlining was more extensive than the gcc back end
4398 inlining, but that is no longer the case.
4400 @item -gnato??
4401 @cindex @option{-gnato??} (@command{gcc})
4402 Set default mode for handling generation of code to avoid intermediate
4403 arithmetic overflow. Here `@code{??}' is two digits, a
4404 single digit, or nothing. Each digit is one of the digits `@code{1}'
4405 through `@code{3}':
4407 @itemize @bullet
4408 @item   @code{1}:
4409 all intermediate overflows checked against base type (@code{STRICT})
4410 @item   @code{2}:
4411 minimize intermediate overflows (@code{MINIMIZED})
4412 @item   @code{3}:
4413 eliminate intermediate overflows (@code{ELIMINATED})
4414 @end itemize
4416 If only one digit appears then it applies to all
4417 cases; if two digits are given, then the first applies outside
4418 assertions, and the second within assertions.
4420 If no digits follow the @option{-gnato}, then it is equivalent to
4421 @option{-gnato11},
4422 causing all intermediate overflows to be handled in strict mode.
4424 This switch also causes arithmetic overflow checking to be performed
4425 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4427 The default if no option @option{-gnato} is given is that overflow handling
4428 is in @code{STRICT} mode (computations done using the base type), and that
4429 overflow checking is suppressed.
4431 Note that division by zero is a separate check that is not
4432 controlled by this switch (division by zero checking is on by default).
4434 See also @ref{Specifying the Desired Mode}.
4436 @item -gnatp
4437 @cindex @option{-gnatp} (@command{gcc})
4438 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4439 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4441 @item -gnat-p
4442 @cindex @option{-gnat-p} (@command{gcc})
4443 Cancel effect of previous @option{-gnatp} switch.
4445 @item -gnatP
4446 @cindex @option{-gnatP} (@command{gcc})
4447 Enable polling. This is required on some systems (notably Windows NT) to
4448 obtain asynchronous abort and asynchronous transfer of control capability.
4449 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4450 details.
4452 @item -gnatq
4453 @cindex @option{-gnatq} (@command{gcc})
4454 Don't quit. Try semantics, even if parse errors.
4456 @item -gnatQ
4457 @cindex @option{-gnatQ} (@command{gcc})
4458 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4460 @item -gnatr
4461 @cindex @option{-gnatr} (@command{gcc})
4462 Treat pragma Restrictions as Restriction_Warnings.
4464 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4465 @cindex @option{-gnatR} (@command{gcc})
4466 Output representation information for declared types and objects.
4468 @item -gnats
4469 @cindex @option{-gnats} (@command{gcc})
4470 Syntax check only.
4472 @item -gnatS
4473 @cindex @option{-gnatS} (@command{gcc})
4474 Print package Standard.
4476 @item -gnatt
4477 @cindex @option{-gnatt} (@command{gcc})
4478 Generate tree output file.
4480 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4481 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4482 All compiler tables start at @var{nnn} times usual starting size.
4484 @item -gnatu
4485 @cindex @option{-gnatu} (@command{gcc})
4486 List units for this compilation.
4488 @item -gnatU
4489 @cindex @option{-gnatU} (@command{gcc})
4490 Tag all error messages with the unique string ``error:''
4492 @item -gnatv
4493 @cindex @option{-gnatv} (@command{gcc})
4494 Verbose mode. Full error output with source lines to @file{stdout}.
4496 @item -gnatV
4497 @cindex @option{-gnatV} (@command{gcc})
4498 Control level of validity checking (@pxref{Validity Checking}).
4500 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4501 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4502 Warning mode where
4503 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4504 the exact warnings that
4505 are enabled or disabled (@pxref{Warning Message Control}).
4507 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4508 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4509 Wide character encoding method
4510 @ifclear vms
4511 (@var{e}=n/h/u/s/e/8).
4512 @end ifclear
4513 @ifset vms
4514 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4515 @end ifset
4517 @item -gnatx
4518 @cindex @option{-gnatx} (@command{gcc})
4519 Suppress generation of cross-reference information.
4521 @item -gnatX
4522 @cindex @option{-gnatX} (@command{gcc})
4523 Enable GNAT implementation extensions and latest Ada version.
4525 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4526 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4527 Enable built-in style checks (@pxref{Style Checking}).
4529 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4530 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4531 Distribution stub generation and compilation
4532 @ifclear vms
4533 (@var{m}=r/c for receiver/caller stubs).
4534 @end ifclear
4535 @ifset vms
4536 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4537 to be generated and compiled).
4538 @end ifset
4540 @item ^-I^/SEARCH=^@var{dir}
4541 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4542 @cindex RTL
4543 Direct GNAT to search the @var{dir} directory for source files needed by
4544 the current compilation
4545 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4547 @item ^-I-^/NOCURRENT_DIRECTORY^
4548 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4549 @cindex RTL
4550 Except for the source file named in the command line, do not look for source
4551 files in the directory containing the source file named in the command line
4552 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4554 @ifclear vms
4555 @item -mbig-switch
4556 @cindex @option{-mbig-switch} (@command{gcc})
4557 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4558 This standard gcc switch causes the compiler to use larger offsets in its
4559 jump table representation for @code{case} statements.
4560 This may result in less efficient code, but is sometimes necessary
4561 (for example on HP-UX targets)
4562 @cindex HP-UX and @option{-mbig-switch} option
4563 in order to compile large and/or nested @code{case} statements.
4565 @item -o @var{file}
4566 @cindex @option{-o} (@command{gcc})
4567 This switch is used in @command{gcc} to redirect the generated object file
4568 and its associated ALI file. Beware of this switch with GNAT, because it may
4569 cause the object file and ALI file to have different names which in turn
4570 may confuse the binder and the linker.
4571 @end ifclear
4573 @item -nostdinc
4574 @cindex @option{-nostdinc} (@command{gcc})
4575 Inhibit the search of the default location for the GNAT Run Time
4576 Library (RTL) source files.
4578 @item -nostdlib
4579 @cindex @option{-nostdlib} (@command{gcc})
4580 Inhibit the search of the default location for the GNAT Run Time
4581 Library (RTL) ALI files.
4583 @ifclear vms
4584 @c @item -O@ovar{n}
4585 @c Expanding @ovar macro inline (explanation in macro def comments)
4586 @item -O@r{[}@var{n}@r{]}
4587 @cindex @option{-O} (@command{gcc})
4588 @var{n} controls the optimization level.
4590 @table @asis
4591 @item n = 0
4592 No optimization, the default setting if no @option{-O} appears
4594 @item n = 1
4595 Normal optimization, the default if you specify @option{-O} without
4596 an operand. A good compromise between code quality and compilation
4597 time.
4599 @item n = 2
4600 Extensive optimization, may improve execution time, possibly at the cost of
4601 substantially increased compilation time.
4603 @item n = 3
4604 Same as @option{-O2}, and also includes inline expansion for small subprograms
4605 in the same unit.
4607 @item n = s
4608 Optimize space usage
4609 @end table
4611 @noindent
4612 See also @ref{Optimization Levels}.
4613 @end ifclear
4615 @ifset vms
4616 @item  /NOOPTIMIZE
4617 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4618 Equivalent to @option{/OPTIMIZE=NONE}.
4619 This is the default behavior in the absence of an @option{/OPTIMIZE}
4620 qualifier.
4622 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4623 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4624 Selects the level of optimization for your program. The supported
4625 keywords are as follows:
4626 @table @code
4627 @item   ALL
4628 Perform most optimizations, including those that
4629 are expensive.
4630 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4631 without keyword options.
4633 @item   NONE
4634 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4636 @item SOME
4637 Perform some optimizations, but omit ones that are costly.
4639 @item   DEVELOPMENT
4640 Same as @code{SOME}.
4642 @item INLINING
4643 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4644 automatic inlining of small subprograms within a unit
4646 @item   UNROLL_LOOPS
4647 Try to unroll loops. This keyword may be specified together with
4648 any keyword above other than @code{NONE}. Loop unrolling
4649 usually, but not always, improves the performance of programs.
4651 @item SPACE
4652 Optimize space usage
4653 @end table
4655 @noindent
4656 See also @ref{Optimization Levels}.
4657 @end ifset
4659 @ifclear vms
4660 @item -pass-exit-codes
4661 @cindex @option{-pass-exit-codes} (@command{gcc})
4662 Catch exit codes from the compiler and use the most meaningful as
4663 exit status.
4664 @end ifclear
4666 @item --RTS=@var{rts-path}
4667 @cindex @option{--RTS} (@command{gcc})
4668 Specifies the default location of the runtime library. Same meaning as the
4669 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4671 @item ^-S^/ASM^
4672 @cindex @option{^-S^/ASM^} (@command{gcc})
4673 ^Used in place of @option{-c} to^Used to^
4674 cause the assembler source file to be
4675 generated, using @file{^.s^.S^} as the extension,
4676 instead of the object file.
4677 This may be useful if you need to examine the generated assembly code.
4679 @item ^-fverbose-asm^/VERBOSE_ASM^
4680 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4681 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4682 to cause the generated assembly code file to be annotated with variable
4683 names, making it significantly easier to follow.
4685 @item ^-v^/VERBOSE^
4686 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4687 Show commands generated by the @command{gcc} driver. Normally used only for
4688 debugging purposes or if you need to be sure what version of the
4689 compiler you are executing.
4691 @ifclear vms
4692 @item -V @var{ver}
4693 @cindex @option{-V} (@command{gcc})
4694 Execute @var{ver} version of the compiler. This is the @command{gcc}
4695 version, not the GNAT version.
4696 @end ifclear
4698 @item ^-w^/NO_BACK_END_WARNINGS^
4699 @cindex @option{-w} (@command{gcc})
4700 Turn off warnings generated by the back end of the compiler. Use of
4701 this switch also causes the default for front end warnings to be set
4702 to suppress (as though @option{-gnatws} had appeared at the start of
4703 the options).
4705 @end table
4707 @ifclear vms
4708 @c Combining qualifiers does not work on VMS
4709 You may combine a sequence of GNAT switches into a single switch. For
4710 example, the combined switch
4712 @cindex Combining GNAT switches
4713 @smallexample
4714 -gnatofi3
4715 @end smallexample
4717 @noindent
4718 is equivalent to specifying the following sequence of switches:
4720 @smallexample
4721 -gnato -gnatf -gnati3
4722 @end smallexample
4723 @end ifclear
4725 @noindent
4726 The following restrictions apply to the combination of switches
4727 in this manner:
4729 @itemize @bullet
4730 @item
4731 The switch @option{-gnatc} if combined with other switches must come
4732 first in the string.
4734 @item
4735 The switch @option{-gnats} if combined with other switches must come
4736 first in the string.
4738 @item
4739 The switches
4740 ^^@option{/DISTRIBUTION_STUBS=},^
4741 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4742 switches, and only one of them may appear in the command line.
4744 @item
4745 The switch @option{-gnat-p} may not be combined with any other switch.
4747 @ifclear vms
4748 @item
4749 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4750 switch), then all further characters in the switch are interpreted
4751 as style modifiers (see description of @option{-gnaty}).
4753 @item
4754 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4755 switch), then all further characters in the switch are interpreted
4756 as debug flags (see description of @option{-gnatd}).
4758 @item
4759 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4760 switch), then all further characters in the switch are interpreted
4761 as warning mode modifiers (see description of @option{-gnatw}).
4763 @item
4764 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4765 switch), then all further characters in the switch are interpreted
4766 as validity checking options (@pxref{Validity Checking}).
4768 @item
4769 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4770 a combined list of options.
4771 @end ifclear
4772 @end itemize
4774 @node Output and Error Message Control
4775 @subsection Output and Error Message Control
4776 @findex stderr
4778 @noindent
4779 The standard default format for error messages is called ``brief format''.
4780 Brief format messages are written to @file{stderr} (the standard error
4781 file) and have the following form:
4783 @smallexample
4784 e.adb:3:04: Incorrect spelling of keyword "function"
4785 e.adb:4:20: ";" should be "is"
4786 @end smallexample
4788 @noindent
4789 The first integer after the file name is the line number in the file,
4790 and the second integer is the column number within the line.
4791 @ifclear vms
4792 @code{GPS} can parse the error messages
4793 and point to the referenced character.
4794 @end ifclear
4795 The following switches provide control over the error message
4796 format:
4798 @table @option
4799 @c !sort!
4800 @item -gnatv
4801 @cindex @option{-gnatv} (@command{gcc})
4802 @findex stdout
4803 @ifclear vms
4804 The v stands for verbose.
4805 @end ifclear
4806 The effect of this setting is to write long-format error
4807 messages to @file{stdout} (the standard output file.
4808 The same program compiled with the
4809 @option{-gnatv} switch would generate:
4811 @smallexample
4812 @cartouche
4813 3. funcion X (Q : Integer)
4814    |
4815 >>> Incorrect spelling of keyword "function"
4816 4. return Integer;
4817                  |
4818 >>> ";" should be "is"
4819 @end cartouche
4820 @end smallexample
4822 @noindent
4823 The vertical bar indicates the location of the error, and the @samp{>>>}
4824 prefix can be used to search for error messages. When this switch is
4825 used the only source lines output are those with errors.
4827 @item -gnatl
4828 @cindex @option{-gnatl} (@command{gcc})
4829 @ifclear vms
4830 The @code{l} stands for list.
4831 @end ifclear
4832 This switch causes a full listing of
4833 the file to be generated. In the case where a body is
4834 compiled, the corresponding spec is also listed, along
4835 with any subunits. Typical output from compiling a package
4836 body @file{p.adb} might look like:
4838 @smallexample @c ada
4839 @cartouche
4840  Compiling: p.adb
4842      1. package body p is
4843      2.    procedure a;
4844      3.    procedure a is separate;
4845      4. begin
4846      5.    null
4847                |
4848         >>> missing ";"
4850      6. end;
4852 Compiling: p.ads
4854      1. package p is
4855      2.    pragma Elaborate_Body
4856                                 |
4857         >>> missing ";"
4859      3. end p;
4861 Compiling: p-a.adb
4863      1. separate p
4864                 |
4865         >>> missing "("
4867      2. procedure a is
4868      3. begin
4869      4.    null
4870                |
4871         >>> missing ";"
4873      5. end;
4874 @end cartouche
4875 @end smallexample
4877 @noindent
4878 @findex stderr
4879 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4880 standard output is redirected, a brief summary is written to
4881 @file{stderr} (standard error) giving the number of error messages and
4882 warning messages generated.
4884 @item ^-gnatl^/OUTPUT_FILE^=file
4885 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4886 This has the same effect as @option{-gnatl} except that the output is
4887 written to a file instead of to standard output. If the given name
4888 @file{fname} does not start with a period, then it is the full name
4889 of the file to be written. If @file{fname} is an extension, it is
4890 appended to the name of the file being compiled. For example, if
4891 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4892 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4894 @item -gnatU
4895 @cindex @option{-gnatU} (@command{gcc})
4896 This switch forces all error messages to be preceded by the unique
4897 string ``error:''. This means that error messages take a few more
4898 characters in space, but allows easy searching for and identification
4899 of error messages.
4901 @item -gnatb
4902 @cindex @option{-gnatb} (@command{gcc})
4903 @ifclear vms
4904 The @code{b} stands for brief.
4905 @end ifclear
4906 This switch causes GNAT to generate the
4907 brief format error messages to @file{stderr} (the standard error
4908 file) as well as the verbose
4909 format message or full listing (which as usual is written to
4910 @file{stdout} (the standard output file).
4912 @item -gnatm=@var{n}
4913 @cindex @option{-gnatm} (@command{gcc})
4914 @ifclear vms
4915 The @code{m} stands for maximum.
4916 @end ifclear
4917 @var{n} is a decimal integer in the
4918 range of 1 to 999999 and limits the number of error or warning
4919 messages to be generated. For example, using
4920 @option{-gnatm2} might yield
4922 @smallexample
4923 e.adb:3:04: Incorrect spelling of keyword "function"
4924 e.adb:5:35: missing ".."
4925 fatal error: maximum number of errors detected
4926 compilation abandoned
4927 @end smallexample
4929 @noindent
4930 The default setting if
4931 no switch is given is 9999. If the number of warnings reaches this
4932 limit, then a message is output and further warnings are suppressed,
4933 but the compilation is continued. If the number of error messages
4934 reaches this limit, then a message is output and the compilation
4935 is abandoned. A value of zero means that no limit applies.
4937 @noindent
4938 Note that the equal sign is optional, so the switches
4939 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4941 @item -gnatf
4942 @cindex @option{-gnatf} (@command{gcc})
4943 @cindex Error messages, suppressing
4944 @ifclear vms
4945 The @code{f} stands for full.
4946 @end ifclear
4947 Normally, the compiler suppresses error messages that are likely to be
4948 redundant. This switch causes all error
4949 messages to be generated. In particular, in the case of
4950 references to undefined variables. If a given variable is referenced
4951 several times, the normal format of messages is
4952 @smallexample
4953 e.adb:7:07: "V" is undefined (more references follow)
4954 @end smallexample
4956 @noindent
4957 where the parenthetical comment warns that there are additional
4958 references to the variable @code{V}. Compiling the same program with the
4959 @option{-gnatf} switch yields
4961 @smallexample
4962 e.adb:7:07: "V" is undefined
4963 e.adb:8:07: "V" is undefined
4964 e.adb:8:12: "V" is undefined
4965 e.adb:8:16: "V" is undefined
4966 e.adb:9:07: "V" is undefined
4967 e.adb:9:12: "V" is undefined
4968 @end smallexample
4970 @noindent
4971 The @option{-gnatf} switch also generates additional information for
4972 some error messages.  Some examples are:
4974 @itemize @bullet
4975 @item
4976 Details on possibly non-portable unchecked conversion
4977 @item
4978 List possible interpretations for ambiguous calls
4979 @item
4980 Additional details on incorrect parameters
4981 @end itemize
4983 @item -gnatjnn
4984 @cindex @option{-gnatjnn} (@command{gcc})
4985 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4986 with continuation lines are treated as though the continuation lines were
4987 separate messages (and so a warning with two continuation lines counts as
4988 three warnings, and is listed as three separate messages).
4990 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4991 messages are output in a different manner. A message and all its continuation
4992 lines are treated as a unit, and count as only one warning or message in the
4993 statistics totals. Furthermore, the message is reformatted so that no line
4994 is longer than nn characters.
4996 @item -gnatq
4997 @cindex @option{-gnatq} (@command{gcc})
4998 @ifclear vms
4999 The @code{q} stands for quit (really ``don't quit'').
5000 @end ifclear
5001 In normal operation mode, the compiler first parses the program and
5002 determines if there are any syntax errors. If there are, appropriate
5003 error messages are generated and compilation is immediately terminated.
5004 This switch tells
5005 GNAT to continue with semantic analysis even if syntax errors have been
5006 found. This may enable the detection of more errors in a single run. On
5007 the other hand, the semantic analyzer is more likely to encounter some
5008 internal fatal error when given a syntactically invalid tree.
5010 @item -gnatQ
5011 @cindex @option{-gnatQ} (@command{gcc})
5012 In normal operation mode, the @file{ALI} file is not generated if any
5013 illegalities are detected in the program. The use of @option{-gnatQ} forces
5014 generation of the @file{ALI} file. This file is marked as being in
5015 error, so it cannot be used for binding purposes, but it does contain
5016 reasonably complete cross-reference information, and thus may be useful
5017 for use by tools (e.g., semantic browsing tools or integrated development
5018 environments) that are driven from the @file{ALI} file. This switch
5019 implies @option{-gnatq}, since the semantic phase must be run to get a
5020 meaningful ALI file.
5022 In addition, if @option{-gnatt} is also specified, then the tree file is
5023 generated even if there are illegalities. It may be useful in this case
5024 to also specify @option{-gnatq} to ensure that full semantic processing
5025 occurs. The resulting tree file can be processed by ASIS, for the purpose
5026 of providing partial information about illegal units, but if the error
5027 causes the tree to be badly malformed, then ASIS may crash during the
5028 analysis.
5030 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
5031 being in error, @command{gnatmake} will attempt to recompile the source when it
5032 finds such an @file{ALI} file, including with switch @option{-gnatc}.
5034 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
5035 since ALI files are never generated if @option{-gnats} is set.
5037 @end table
5039 @node Warning Message Control
5040 @subsection Warning Message Control
5041 @cindex Warning messages
5042 @noindent
5043 In addition to error messages, which correspond to illegalities as defined
5044 in the Ada Reference Manual, the compiler detects two kinds of warning
5045 situations.
5047 First, the compiler considers some constructs suspicious and generates a
5048 warning message to alert you to a possible error. Second, if the
5049 compiler detects a situation that is sure to raise an exception at
5050 run time, it generates a warning message. The following shows an example
5051 of warning messages:
5052 @smallexample
5053 e.adb:4:24: warning: creation of object may raise Storage_Error
5054 e.adb:10:17: warning: static value out of range
5055 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
5056 @end smallexample
5058 @noindent
5059 GNAT considers a large number of situations as appropriate
5060 for the generation of warning messages. As always, warnings are not
5061 definite indications of errors. For example, if you do an out-of-range
5062 assignment with the deliberate intention of raising a
5063 @code{Constraint_Error} exception, then the warning that may be
5064 issued does not indicate an error. Some of the situations for which GNAT
5065 issues warnings (at least some of the time) are given in the following
5066 list. This list is not complete, and new warnings are often added to
5067 subsequent versions of GNAT. The list is intended to give a general idea
5068 of the kinds of warnings that are generated.
5070 @itemize @bullet
5071 @item
5072 Possible infinitely recursive calls
5074 @item
5075 Out-of-range values being assigned
5077 @item
5078 Possible order of elaboration problems
5080 @item
5081 Assertions (pragma Assert) that are sure to fail
5083 @item
5084 Unreachable code
5086 @item
5087 Address clauses with possibly unaligned values, or where an attempt is
5088 made to overlay a smaller variable with a larger one.
5090 @item
5091 Fixed-point type declarations with a null range
5093 @item
5094 Direct_IO or Sequential_IO instantiated with a type that has access values
5096 @item
5097 Variables that are never assigned a value
5099 @item
5100 Variables that are referenced before being initialized
5102 @item
5103 Task entries with no corresponding @code{accept} statement
5105 @item
5106 Duplicate accepts for the same task entry in a @code{select}
5108 @item
5109 Objects that take too much storage
5111 @item
5112 Unchecked conversion between types of differing sizes
5114 @item
5115 Missing @code{return} statement along some execution path in a function
5117 @item
5118 Incorrect (unrecognized) pragmas
5120 @item
5121 Incorrect external names
5123 @item
5124 Allocation from empty storage pool
5126 @item
5127 Potentially blocking operation in protected type
5129 @item
5130 Suspicious parenthesization of expressions
5132 @item
5133 Mismatching bounds in an aggregate
5135 @item
5136 Attempt to return local value by reference
5138 @item
5139 Premature instantiation of a generic body
5141 @item
5142 Attempt to pack aliased components
5144 @item
5145 Out of bounds array subscripts
5147 @item
5148 Wrong length on string assignment
5150 @item
5151 Violations of style rules if style checking is enabled
5153 @item
5154 Unused @code{with} clauses
5156 @item
5157 @code{Bit_Order} usage that does not have any effect
5159 @item
5160 @code{Standard.Duration} used to resolve universal fixed expression
5162 @item
5163 Dereference of possibly null value
5165 @item
5166 Declaration that is likely to cause storage error
5168 @item
5169 Internal GNAT unit @code{with}'ed by application unit
5171 @item
5172 Values known to be out of range at compile time
5174 @item
5175 Unreferenced labels and variables
5177 @item
5178 Address overlays that could clobber memory
5180 @item
5181 Unexpected initialization when address clause present
5183 @item
5184 Bad alignment for address clause
5186 @item
5187 Useless type conversions
5189 @item
5190 Redundant assignment statements and other redundant constructs
5192 @item
5193 Useless exception handlers
5195 @item
5196 Accidental hiding of name by child unit
5198 @item
5199 Access before elaboration detected at compile time
5201 @item
5202 A range in a @code{for} loop that is known to be null or might be null
5204 @end itemize
5206 @noindent
5207 The following section lists compiler switches that are available
5208 to control the handling of warning messages. It is also possible
5209 to exercise much finer control over what warnings are issued and
5210 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5211 gnat_rm, GNAT Reference manual}.
5213 @table @option
5214 @c !sort!
5215 @item -gnatwa
5216 @emph{Activate most optional warnings.}
5217 @cindex @option{-gnatwa} (@command{gcc})
5218 This switch activates most optional warning messages.  See the remaining list
5219 in this section for details on optional warning messages that can be
5220 individually controlled.  The warnings that are not turned on by this
5221 switch are
5222 @option{-gnatwd} (implicit dereferencing),
5223 @option{-gnatwh} (hiding),
5224 @ifclear vms
5225 @option{-gnatw.d} (tag warnings with -gnatw switch)
5226 @end ifclear
5227 @option{-gnatw.h} (holes (gaps) in record layouts)
5228 @option{-gnatw.i} (overlapping actuals),
5229 @option{-gnatw.k} (redefinition of names in standard),
5230 @option{-gnatwl} (elaboration warnings),
5231 @option{-gnatw.l} (inherited aspects),
5232 @option{-gnatw.o} (warn on values set by out parameters ignored),
5233 @option{-gnatwt} (tracking of deleted conditional code)
5234 and @option{-gnatw.u} (unordered enumeration),
5235 All other optional warnings are turned on.
5237 @item -gnatwA
5238 @emph{Suppress all optional errors.}
5239 @cindex @option{-gnatwA} (@command{gcc})
5240 This switch suppresses all optional warning messages, see remaining list
5241 in this section for details on optional warning messages that can be
5242 individually controlled. Note that unlike switch @option{-gnatws}, the
5243 use of switch @option{-gnatwA} does not suppress warnings that are
5244 normally given unconditionally and cannot be individually controlled
5245 (for example, the warning about a missing exit path in a function).
5246 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5247 the use of switch @option{-gnatwA} can be individually turned back
5248 on. For example the use of switch @option{-gnatwA} followed by
5249 switch @option{-gnatwd} will suppress all optional warnings except
5250 the warnings for implicit dereferencing.
5252 @item -gnatw.a
5253 @emph{Activate warnings on failing assertions.}
5254 @cindex @option{-gnatw.a} (@command{gcc})
5255 @cindex Assert failures
5256 This switch activates warnings for assertions where the compiler can tell at
5257 compile time that the assertion will fail. Note that this warning is given
5258 even if assertions are disabled. The default is that such warnings are
5259 generated.
5261 @item -gnatw.A
5262 @emph{Suppress warnings on failing assertions.}
5263 @cindex @option{-gnatw.A} (@command{gcc})
5264 @cindex Assert failures
5265 This switch suppresses warnings for assertions where the compiler can tell at
5266 compile time that the assertion will fail.
5268 @item -gnatwb
5269 @emph{Activate warnings on bad fixed values.}
5270 @cindex @option{-gnatwb} (@command{gcc})
5271 @cindex Bad fixed values
5272 @cindex Fixed-point Small value
5273 @cindex Small value
5274 This switch activates warnings for static fixed-point expressions whose
5275 value is not an exact multiple of Small. Such values are implementation
5276 dependent, since an implementation is free to choose either of the multiples
5277 that surround the value. GNAT always chooses the closer one, but this is not
5278 required behavior, and it is better to specify a value that is an exact
5279 multiple, ensuring predictable execution. The default is that such warnings
5280 are not generated.
5282 @item -gnatwB
5283 @emph{Suppress warnings on bad fixed values.}
5284 @cindex @option{-gnatwB} (@command{gcc})
5285 This switch suppresses warnings for static fixed-point expressions whose
5286 value is not an exact multiple of Small.
5288 @item -gnatw.b
5289 @emph{Activate warnings on biased representation.}
5290 @cindex @option{-gnatw.b} (@command{gcc})
5291 @cindex Biased representation
5292 This switch activates warnings when a size clause, value size clause, component
5293 clause, or component size clause forces the use of biased representation for an
5294 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5295 to represent 10/11). The default is that such warnings are generated.
5297 @item -gnatw.B
5298 @emph{Suppress warnings on biased representation.}
5299 @cindex @option{-gnatwB} (@command{gcc})
5300 This switch suppresses warnings for representation clauses that force the use
5301 of biased representation.
5303 @item -gnatwc
5304 @emph{Activate warnings on conditionals.}
5305 @cindex @option{-gnatwc} (@command{gcc})
5306 @cindex Conditionals, constant
5307 This switch activates warnings for conditional expressions used in
5308 tests that are known to be True or False at compile time. The default
5309 is that such warnings are not generated.
5310 Note that this warning does
5311 not get issued for the use of boolean variables or constants whose
5312 values are known at compile time, since this is a standard technique
5313 for conditional compilation in Ada, and this would generate too many
5314 false positive warnings.
5316 This warning option also activates a special test for comparisons using
5317 the operators ``>='' and`` <=''.
5318 If the compiler can tell that only the equality condition is possible,
5319 then it will warn that the ``>'' or ``<'' part of the test
5320 is useless and that the operator could be replaced by ``=''.
5321 An example would be comparing a @code{Natural} variable <= 0.
5323 This warning option also generates warnings if
5324 one or both tests is optimized away in a membership test for integer
5325 values if the result can be determined at compile time. Range tests on
5326 enumeration types are not included, since it is common for such tests
5327 to include an end point.
5329 This warning can also be turned on using @option{-gnatwa}.
5331 @item -gnatwC
5332 @emph{Suppress warnings on conditionals.}
5333 @cindex @option{-gnatwC} (@command{gcc})
5334 This switch suppresses warnings for conditional expressions used in
5335 tests that are known to be True or False at compile time.
5337 @item -gnatw.c
5338 @emph{Activate warnings on missing component clauses.}
5339 @cindex @option{-gnatw.c} (@command{gcc})
5340 @cindex Component clause, missing
5341 This switch activates warnings for record components where a record
5342 representation clause is present and has component clauses for the
5343 majority, but not all, of the components. A warning is given for each
5344 component for which no component clause is present.
5346 This warning can also be turned on using @option{-gnatwa}.
5348 @item -gnatw.C
5349 @emph{Suppress warnings on missing component clauses.}
5350 @cindex @option{-gnatwC} (@command{gcc})
5351 This switch suppresses warnings for record components that are
5352 missing a component clause in the situation described above.
5354 @item -gnatwd
5355 @emph{Activate warnings on implicit dereferencing.}
5356 @cindex @option{-gnatwd} (@command{gcc})
5357 If this switch is set, then the use of a prefix of an access type
5358 in an indexed component, slice, or selected component without an
5359 explicit @code{.all} will generate a warning. With this warning
5360 enabled, access checks occur only at points where an explicit
5361 @code{.all} appears in the source code (assuming no warnings are
5362 generated as a result of this switch). The default is that such
5363 warnings are not generated.
5364 Note that @option{-gnatwa} does not affect the setting of
5365 this warning option.
5367 @item -gnatwD
5368 @emph{Suppress warnings on implicit dereferencing.}
5369 @cindex @option{-gnatwD} (@command{gcc})
5370 @cindex Implicit dereferencing
5371 @cindex Dereferencing, implicit
5372 This switch suppresses warnings for implicit dereferences in
5373 indexed components, slices, and selected components.
5375 @ifclear vms
5376 @item -gnatw.d
5377 @emph{Activate tagging of warning messages.}
5378 @cindex @option{-gnatw.d} (@command{gcc})
5379 If this switch is set, then warning messages are tagged, either with
5380 the string ``@option{-gnatw?}'' showing which switch controls the warning,
5381 or with ``[enabled by default]'' if the warning is not under control of a
5382 specific @option{-gnatw?} switch. This mode is off by default, and is not
5383 affected by the use of @code{-gnatwa}.
5385 @item -gnatw.D
5386 @emph{Deactivate tagging of warning messages.}
5387 @cindex @option{-gnatw.d} (@command{gcc})
5388 If this switch is set, then warning messages return to the default
5389 mode in which warnings are not tagged as described above for
5390 @code{-gnatw.d}.
5391 @end ifclear
5393 @item -gnatwe
5394 @emph{Treat warnings and style checks as errors.}
5395 @cindex @option{-gnatwe} (@command{gcc})
5396 @cindex Warnings, treat as error
5397 This switch causes warning messages and style check messages to be
5398 treated as errors.
5399 The warning string still appears, but the warning messages are counted
5400 as errors, and prevent the generation of an object file. Note that this
5401 is the only -gnatw switch that affects the handling of style check messages.
5403 @item -gnatw.e
5404 @emph{Activate every optional warning}
5405 @cindex @option{-gnatw.e} (@command{gcc})
5406 @cindex Warnings, activate every optional warning
5407 This switch activates all optional warnings, including those which
5408 are not activated by @code{-gnatwa}. The use of this switch is not
5409 recommended for normal use. If you turn this switch on, it is almost
5410 certain that you will get large numbers of useless warnings. The
5411 warnings that are excluded from @code{-gnatwa} are typically highly
5412 specialized warnings that are suitable for use only in code that has
5413 been specifically designed according to specialized coding rules.
5415 @item -gnatwf
5416 @emph{Activate warnings on unreferenced formals.}
5417 @cindex @option{-gnatwf} (@command{gcc})
5418 @cindex Formals, unreferenced
5419 This switch causes a warning to be generated if a formal parameter
5420 is not referenced in the body of the subprogram. This warning can
5421 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5422 default is that these warnings are not generated.
5424 @item -gnatwF
5425 @emph{Suppress warnings on unreferenced formals.}
5426 @cindex @option{-gnatwF} (@command{gcc})
5427 This switch suppresses warnings for unreferenced formal
5428 parameters. Note that the
5429 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5430 effect of warning on unreferenced entities other than subprogram
5431 formals.
5433 @item -gnatwg
5434 @emph{Activate warnings on unrecognized pragmas.}
5435 @cindex @option{-gnatwg} (@command{gcc})
5436 @cindex Pragmas, unrecognized
5437 This switch causes a warning to be generated if an unrecognized
5438 pragma is encountered. Apart from issuing this warning, the
5439 pragma is ignored and has no effect. This warning can
5440 also be turned on using @option{-gnatwa}. The default
5441 is that such warnings are issued (satisfying the Ada Reference
5442 Manual requirement that such warnings appear).
5444 @item -gnatwG
5445 @emph{Suppress warnings on unrecognized pragmas.}
5446 @cindex @option{-gnatwG} (@command{gcc})
5447 This switch suppresses warnings for unrecognized pragmas.
5449 @item -gnatwh
5450 @emph{Activate warnings on hiding.}
5451 @cindex @option{-gnatwh} (@command{gcc})
5452 @cindex Hiding of Declarations
5453 This switch activates warnings on hiding declarations.
5454 A declaration is considered hiding
5455 if it is for a non-overloadable entity, and it declares an entity with the
5456 same name as some other entity that is directly or use-visible. The default
5457 is that such warnings are not generated.
5458 Note that @option{-gnatwa} does not affect the setting of this warning option.
5460 @item -gnatwH
5461 @emph{Suppress warnings on hiding.}
5462 @cindex @option{-gnatwH} (@command{gcc})
5463 This switch suppresses warnings on hiding declarations.
5465 @item -gnatw.h
5466 @emph{Activate warnings on holes/gaps in records.}
5467 @cindex @option{-gnatw.h} (@command{gcc})
5468 @cindex Record Representation (gaps)
5469 This switch activates warnings on component clauses in record
5470 representation clauses that leave holes (gaps) in the record layout.
5471 If this warning option is active, then record representation clauses
5472 should specify a contiguous layout, adding unused fill fields if needed.
5473 Note that @option{-gnatwa} does not affect the setting of this warning option.
5475 @item -gnatw.H
5476 @emph{Suppress warnings on holes/gaps in records.}
5477 @cindex @option{-gnatw.H} (@command{gcc})
5478 This switch suppresses warnings on component clauses in record
5479 representation clauses that leave holes (haps) in the record layout.
5481 @item -gnatwi
5482 @emph{Activate warnings on implementation units.}
5483 @cindex @option{-gnatwi} (@command{gcc})
5484 This switch activates warnings for a @code{with} of an internal GNAT
5485 implementation unit, defined as any unit from the @code{Ada},
5486 @code{Interfaces}, @code{GNAT},
5487 ^^@code{DEC},^ or @code{System}
5488 hierarchies that is not
5489 documented in either the Ada Reference Manual or the GNAT
5490 Programmer's Reference Manual. Such units are intended only
5491 for internal implementation purposes and should not be @code{with}'ed
5492 by user programs. The default is that such warnings are generated
5493 This warning can also be turned on using @option{-gnatwa}.
5495 @item -gnatwI
5496 @emph{Disable warnings on implementation units.}
5497 @cindex @option{-gnatwI} (@command{gcc})
5498 This switch disables warnings for a @code{with} of an internal GNAT
5499 implementation unit.
5501 @item -gnatw.i
5502 @emph{Activate warnings on overlapping actuals.}
5503 @cindex @option{-gnatw.i} (@command{gcc})
5504 This switch enables a warning on statically detectable overlapping actuals in
5505 a subprogram call, when one of the actuals is an in-out parameter, and the
5506 types of the actuals are not by-copy types. The warning is off by default,
5507 and is not included under -gnatwa.
5509 @item -gnatw.I
5510 @emph{Disable warnings on overlapping actuals.}
5511 @cindex @option{-gnatw.I} (@command{gcc})
5512 This switch disables warnings on overlapping actuals in a call..
5514 @item -gnatwj
5515 @emph{Activate warnings on obsolescent features (Annex J).}
5516 @cindex @option{-gnatwj} (@command{gcc})
5517 @cindex Features, obsolescent
5518 @cindex Obsolescent features
5519 If this warning option is activated, then warnings are generated for
5520 calls to subprograms marked with @code{pragma Obsolescent} and
5521 for use of features in Annex J of the Ada Reference Manual. In the
5522 case of Annex J, not all features are flagged. In particular use
5523 of the renamed packages (like @code{Text_IO}) and use of package
5524 @code{ASCII} are not flagged, since these are very common and
5525 would generate many annoying positive warnings. The default is that
5526 such warnings are not generated. This warning is also turned on by
5527 the use of @option{-gnatwa}.
5529 In addition to the above cases, warnings are also generated for
5530 GNAT features that have been provided in past versions but which
5531 have been superseded (typically by features in the new Ada standard).
5532 For example, @code{pragma Ravenscar} will be flagged since its
5533 function is replaced by @code{pragma Profile(Ravenscar)}, and
5534 @code{pragma Interface_Name} will be flagged since its function
5535 is replaced by @code{pragma Import}.
5537 Note that this warning option functions differently from the
5538 restriction @code{No_Obsolescent_Features} in two respects.
5539 First, the restriction applies only to annex J features.
5540 Second, the restriction does flag uses of package @code{ASCII}.
5542 @item -gnatwJ
5543 @emph{Suppress warnings on obsolescent features (Annex J).}
5544 @cindex @option{-gnatwJ} (@command{gcc})
5545 This switch disables warnings on use of obsolescent features.
5547 @item -gnatwk
5548 @emph{Activate warnings on variables that could be constants.}
5549 @cindex @option{-gnatwk} (@command{gcc})
5550 This switch activates warnings for variables that are initialized but
5551 never modified, and then could be declared constants. The default is that
5552 such warnings are not given.
5553 This warning can also be turned on using @option{-gnatwa}.
5555 @item -gnatwK
5556 @emph{Suppress warnings on variables that could be constants.}
5557 @cindex @option{-gnatwK} (@command{gcc})
5558 This switch disables warnings on variables that could be declared constants.
5560 @item -gnatw.k
5561 @emph{Activate warnings on redefinition of names in standard.}
5562 @cindex @option{-gnatw.k} (@command{gcc})
5563 This switch activates warnings for declarations that declare a name that
5564 is defined in package Standard. Such declarations can be confusing,
5565 especially since the names in package Standard continue to be directly
5566 visible, meaning that use visibiliy on such redeclared names does not
5567 work as expected. Names of discriminants and components in records are
5568 not included in this check.
5569 This warning is not part of the warnings activated by @option{-gnatwa}.
5570 It must be explicitly activated.
5572 @item -gnatw.K
5573 @emph{Suppress warnings on variables that could be constants.}
5574 @cindex @option{-gnatwK} (@command{gcc})
5575 This switch activates warnings for declarations that declare a name that
5576 is defined in package Standard.
5578 @item -gnatwl
5579 @emph{Activate warnings for elaboration pragmas.}
5580 @cindex @option{-gnatwl} (@command{gcc})
5581 @cindex Elaboration, warnings
5582 This switch activates warnings on missing
5583 @code{Elaborate_All} and @code{Elaborate} pragmas.
5584 See the section in this guide on elaboration checking for details on
5585 when such pragmas should be used. In dynamic elaboration mode, this switch
5586 generations warnings about the need to add elaboration pragmas. Note however,
5587 that if you blindly follow these warnings, and add @code{Elaborate_All}
5588 warnings wherever they are recommended, you basically end up with the
5589 equivalent of the static elaboration model, which may not be what you want for
5590 legacy code for which the static model does not work.
5592 For the static model, the messages generated are labeled "info:" (for
5593 information messages). They are not warnings to add elaboration pragmas,
5594 merely informational messages showing what implicit elaboration pragmas
5595 have been added, for use in analyzing elaboration circularity problems.
5597 Warnings are also generated if you
5598 are using the static mode of elaboration, and a @code{pragma Elaborate}
5599 is encountered. The default is that such warnings
5600 are not generated.
5601 This warning is not automatically turned on by the use of @option{-gnatwa}.
5603 @item -gnatwL
5604 @emph{Suppress warnings for elaboration pragmas.}
5605 @cindex @option{-gnatwL} (@command{gcc})
5606 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5607 See the section in this guide on elaboration checking for details on
5608 when such pragmas should be used.
5610 @item -gnatw.l
5611 @emph{List inherited aspects.}
5612 @cindex @option{-gnatw.l} (@command{gcc})
5613 This switch causes the compiler to list inherited invariants,
5614 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5615 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5616 These messages are not automatically turned on by the use of @option{-gnatwa}.
5618 @item -gnatw.L
5619 @emph{Suppress listing of inherited aspects.}
5620 @cindex @option{-gnatw.L} (@command{gcc})
5621 This switch suppresses listing of inherited aspects.
5623 @item -gnatwm
5624 @emph{Activate warnings on modified but unreferenced variables.}
5625 @cindex @option{-gnatwm} (@command{gcc})
5626 This switch activates warnings for variables that are assigned (using
5627 an initialization value or with one or more assignment statements) but
5628 whose value is never read. The warning is suppressed for volatile
5629 variables and also for variables that are renamings of other variables
5630 or for which an address clause is given.
5631 This warning can also be turned on using @option{-gnatwa}.
5632 The default is that these warnings are not given.
5634 @item -gnatwM
5635 @emph{Disable warnings on modified but unreferenced variables.}
5636 @cindex @option{-gnatwM} (@command{gcc})
5637 This switch disables warnings for variables that are assigned or
5638 initialized, but never read.
5640 @item -gnatw.m
5641 @emph{Activate warnings on suspicious modulus values.}
5642 @cindex @option{-gnatw.m} (@command{gcc})
5643 This switch activates warnings for modulus values that seem suspicious.
5644 The cases caught are where the size is the same as the modulus (e.g.
5645 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5646 with no size clause. The guess in both cases is that 2**x was intended
5647 rather than x. In addition expressions of the form 2*x for small x
5648 generate a warning (the almost certainly accurate guess being that
5649 2**x was intended). The default is that these warnings are given.
5651 @item -gnatw.M
5652 @emph{Disable warnings on suspicious modulus values.}
5653 @cindex @option{-gnatw.M} (@command{gcc})
5654 This switch disables warnings for suspicious modulus values.
5656 @item -gnatwn
5657 @emph{Set normal warnings mode.}
5658 @cindex @option{-gnatwn} (@command{gcc})
5659 This switch sets normal warning mode, in which enabled warnings are
5660 issued and treated as warnings rather than errors. This is the default
5661 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5662 an explicit @option{-gnatws} or
5663 @option{-gnatwe}. It also cancels the effect of the
5664 implicit @option{-gnatwe} that is activated by the
5665 use of @option{-gnatg}.
5667 @item -gnatwo
5668 @emph{Activate warnings on address clause overlays.}
5669 @cindex @option{-gnatwo} (@command{gcc})
5670 @cindex Address Clauses, warnings
5671 This switch activates warnings for possibly unintended initialization
5672 effects of defining address clauses that cause one variable to overlap
5673 another. The default is that such warnings are generated.
5674 This warning can also be turned on using @option{-gnatwa}.
5676 @item -gnatwO
5677 @emph{Suppress warnings on address clause overlays.}
5678 @cindex @option{-gnatwO} (@command{gcc})
5679 This switch suppresses warnings on possibly unintended initialization
5680 effects of defining address clauses that cause one variable to overlap
5681 another.
5683 @item -gnatw.o
5684 @emph{Activate warnings on modified but unreferenced out parameters.}
5685 @cindex @option{-gnatw.o} (@command{gcc})
5686 This switch activates warnings for variables that are modified by using
5687 them as actuals for a call to a procedure with an out mode formal, where
5688 the resulting assigned value is never read. It is applicable in the case
5689 where there is more than one out mode formal. If there is only one out
5690 mode formal, the warning is issued by default (controlled by -gnatwu).
5691 The warning is suppressed for volatile
5692 variables and also for variables that are renamings of other variables
5693 or for which an address clause is given.
5694 The default is that these warnings are not given. Note that this warning
5695 is not included in -gnatwa, it must be activated explicitly.
5697 @item -gnatw.O
5698 @emph{Disable warnings on modified but unreferenced out parameters.}
5699 @cindex @option{-gnatw.O} (@command{gcc})
5700 This switch suppresses warnings for variables that are modified by using
5701 them as actuals for a call to a procedure with an out mode formal, where
5702 the resulting assigned value is never read.
5704 @item -gnatwp
5705 @emph{Activate warnings on ineffective pragma Inlines.}
5706 @cindex @option{-gnatwp} (@command{gcc})
5707 @cindex Inlining, warnings
5708 This switch activates warnings for failure of front end inlining
5709 (activated by @option{-gnatN}) to inline a particular call. There are
5710 many reasons for not being able to inline a call, including most
5711 commonly that the call is too complex to inline. The default is
5712 that such warnings are not given.
5713 This warning can also be turned on using @option{-gnatwa}.
5714 Warnings on ineffective inlining by the gcc back-end can be activated
5715 separately, using the gcc switch -Winline.
5717 @item -gnatwP
5718 @emph{Suppress warnings on ineffective pragma Inlines.}
5719 @cindex @option{-gnatwP} (@command{gcc})
5720 This switch suppresses warnings on ineffective pragma Inlines. If the
5721 inlining mechanism cannot inline a call, it will simply ignore the
5722 request silently.
5724 @item -gnatw.p
5725 @emph{Activate warnings on parameter ordering.}
5726 @cindex @option{-gnatw.p} (@command{gcc})
5727 @cindex Parameter order, warnings
5728 This switch activates warnings for cases of suspicious parameter
5729 ordering when the list of arguments are all simple identifiers that
5730 match the names of the formals, but are in a different order. The
5731 warning is suppressed if any use of named parameter notation is used,
5732 so this is the appropriate way to suppress a false positive (and
5733 serves to emphasize that the "misordering" is deliberate). The
5734 default is
5735 that such warnings are not given.
5736 This warning can also be turned on using @option{-gnatwa}.
5738 @item -gnatw.P
5739 @emph{Suppress warnings on parameter ordering.}
5740 @cindex @option{-gnatw.P} (@command{gcc})
5741 This switch suppresses warnings on cases of suspicious parameter
5742 ordering.
5744 @item -gnatwq
5745 @emph{Activate warnings on questionable missing parentheses.}
5746 @cindex @option{-gnatwq} (@command{gcc})
5747 @cindex Parentheses, warnings
5748 This switch activates warnings for cases where parentheses are not used and
5749 the result is potential ambiguity from a readers point of view. For example
5750 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5751 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5752 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5753 follow the rule of always parenthesizing to make the association clear, and
5754 this warning switch warns if such parentheses are not present. The default
5755 is that these warnings are given.
5756 This warning can also be turned on using @option{-gnatwa}.
5758 @item -gnatwQ
5759 @emph{Suppress warnings on questionable missing parentheses.}
5760 @cindex @option{-gnatwQ} (@command{gcc})
5761 This switch suppresses warnings for cases where the association is not
5762 clear and the use of parentheses is preferred.
5764 @item -gnatwr
5765 @emph{Activate warnings on redundant constructs.}
5766 @cindex @option{-gnatwr} (@command{gcc})
5767 This switch activates warnings for redundant constructs. The following
5768 is the current list of constructs regarded as redundant:
5770 @itemize @bullet
5771 @item
5772 Assignment of an item to itself.
5773 @item
5774 Type conversion that converts an expression to its own type.
5775 @item
5776 Use of the attribute @code{Base} where @code{typ'Base} is the same
5777 as @code{typ}.
5778 @item
5779 Use of pragma @code{Pack} when all components are placed by a record
5780 representation clause.
5781 @item
5782 Exception handler containing only a reraise statement (raise with no
5783 operand) which has no effect.
5784 @item
5785 Use of the operator abs on an operand that is known at compile time
5786 to be non-negative
5787 @item
5788 Comparison of boolean expressions to an explicit True value.
5789 @end itemize
5791 This warning can also be turned on using @option{-gnatwa}.
5792 The default is that warnings for redundant constructs are not given.
5794 @item -gnatwR
5795 @emph{Suppress warnings on redundant constructs.}
5796 @cindex @option{-gnatwR} (@command{gcc})
5797 This switch suppresses warnings for redundant constructs.
5799 @item -gnatw.r
5800 @emph{Activate warnings for object renaming function.}
5801 @cindex @option{-gnatw.r} (@command{gcc})
5802 This switch activates warnings for an object renaming that renames a
5803 function call, which is equivalent to a constant declaration (as
5804 opposed to renaming the function itself).  The default is that these
5805 warnings are given.  This warning can also be turned on using
5806 @option{-gnatwa}.
5808 @item -gnatw.R
5809 @emph{Suppress warnings for object renaming function.}
5810 @cindex @option{-gnatwT} (@command{gcc})
5811 This switch suppresses warnings for object renaming function.
5813 @item -gnatws
5814 @emph{Suppress all warnings.}
5815 @cindex @option{-gnatws} (@command{gcc})
5816 This switch completely suppresses the
5817 output of all warning messages from the GNAT front end, including
5818 both warnings that can be controlled by switches described in this
5819 section, and those that are normally given unconditionally. The
5820 effect of this suppress action can only be cancelled by a subsequent
5821 use of the switch @option{-gnatwn}.
5823 Note that switch @option{-gnatws} does not suppress
5824 warnings from the @command{gcc} back end.
5825 To suppress these back end warnings as well, use the switch @option{-w}
5826 in addition to @option{-gnatws}. Also this switch has no effect on the
5827 handling of style check messages.
5829 @item -gnatw.s
5830 @emph{Activate warnings on overridden size clauses.}
5831 @cindex @option{-gnatw.s} (@command{gcc})
5832 @cindex Record Representation (component sizes)
5833 This switch activates warnings on component clauses in record
5834 representation clauses where the length given overrides that
5835 specified by an explicit size clause for the component type. A
5836 warning is similarly given in the array case if a specified
5837 component size overrides an explicit size clause for the array
5838 component type.
5839 Note that @option{-gnatwa} does not affect the setting of this warning option.
5841 @item -gnatw.S
5842 @emph{Suppress warnings on overridden size clauses.}
5843 @cindex @option{-gnatw.S} (@command{gcc})
5844 This switch suppresses warnings on component clauses in record
5845 representation clauses that override size clauses, and similar
5846 warnings when an array component size overrides a size clause.
5848 @item -gnatwt
5849 @emph{Activate warnings for tracking of deleted conditional code.}
5850 @cindex @option{-gnatwt} (@command{gcc})
5851 @cindex Deactivated code, warnings
5852 @cindex Deleted code, warnings
5853 This switch activates warnings for tracking of code in conditionals (IF and
5854 CASE statements) that is detected to be dead code which cannot be executed, and
5855 which is removed by the front end. This warning is off by default, and is not
5856 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5857 useful for detecting deactivated code in certified applications.
5859 @item -gnatwT
5860 @emph{Suppress warnings for tracking of deleted conditional code.}
5861 @cindex @option{-gnatwT} (@command{gcc})
5862 This switch suppresses warnings for tracking of deleted conditional code.
5864 @item -gnatw.t
5865 @emph{Activate warnings on suspicious contracts.}
5866 @cindex @option{-gnatw.t} (@command{gcc})
5867 This switch activates warnings on suspicious postconditions (whether a
5868 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5869 and suspicious contract cases (pragma @code{Contract_Case}). A
5870 function postcondition or contract case is suspicious when no postcondition
5871 or contract case for this function mentions the result of the function.
5872 A procedure postcondition or contract case is suspicious when it only
5873 refers to the pre-state of the procedure, because in that case it should
5874 rather be expressed as a precondition. The default is that such warnings
5875 are not generated. This warning can also be turned on using @option{-gnatwa}.
5877 @item -gnatw.T
5878 @emph{Suppress warnings on suspicious contracts.}
5879 @cindex @option{-gnatw.T} (@command{gcc})
5880 This switch suppresses warnings on suspicious postconditions.
5882 @item -gnatwu
5883 @emph{Activate warnings on unused entities.}
5884 @cindex @option{-gnatwu} (@command{gcc})
5885 This switch activates warnings to be generated for entities that
5886 are declared but not referenced, and for units that are @code{with}'ed
5887 and not
5888 referenced. In the case of packages, a warning is also generated if
5889 no entities in the package are referenced. This means that if a with'ed
5890 package is referenced but the only references are in @code{use}
5891 clauses or @code{renames}
5892 declarations, a warning is still generated. A warning is also generated
5893 for a generic package that is @code{with}'ed but never instantiated.
5894 In the case where a package or subprogram body is compiled, and there
5895 is a @code{with} on the corresponding spec
5896 that is only referenced in the body,
5897 a warning is also generated, noting that the
5898 @code{with} can be moved to the body. The default is that
5899 such warnings are not generated.
5900 This switch also activates warnings on unreferenced formals
5901 (it includes the effect of @option{-gnatwf}).
5902 This warning can also be turned on using @option{-gnatwa}.
5904 @item -gnatwU
5905 @emph{Suppress warnings on unused entities.}
5906 @cindex @option{-gnatwU} (@command{gcc})
5907 This switch suppresses warnings for unused entities and packages.
5908 It also turns off warnings on unreferenced formals (and thus includes
5909 the effect of @option{-gnatwF}).
5911 @item -gnatw.u
5912 @emph{Activate warnings on unordered enumeration types.}
5913 @cindex @option{-gnatw.u} (@command{gcc})
5914 This switch causes enumeration types to be considered as conceptually
5915 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5916 The effect is to generate warnings in clients that use explicit comparisons
5917 or subranges, since these constructs both treat objects of the type as
5918 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5919 which the type is declared, or its body or subunits.) Please refer to
5920 the description of pragma @code{Ordered} in the
5921 @cite{@value{EDITION} Reference Manual} for further details.
5922 The default is that such warnings are not generated.
5923 This warning is not automatically turned on by the use of @option{-gnatwa}.
5925 @item -gnatw.U
5926 @emph{Deactivate warnings on unordered enumeration types.}
5927 @cindex @option{-gnatw.U} (@command{gcc})
5928 This switch causes all enumeration types to be considered as ordered, so
5929 that no warnings are given for comparisons or subranges for any type.
5931 @item -gnatwv
5932 @emph{Activate warnings on unassigned variables.}
5933 @cindex @option{-gnatwv} (@command{gcc})
5934 @cindex Unassigned variable warnings
5935 This switch activates warnings for access to variables which
5936 may not be properly initialized. The default is that
5937 such warnings are generated.
5938 This warning can also be turned on using @option{-gnatwa}.
5940 @item -gnatwV
5941 @emph{Suppress warnings on unassigned variables.}
5942 @cindex @option{-gnatwV} (@command{gcc})
5943 This switch suppresses warnings for access to variables which
5944 may not be properly initialized.
5945 For variables of a composite type, the warning can also be suppressed in
5946 Ada 2005 by using a default initialization with a box. For example, if
5947 Table is an array of records whose components are only partially uninitialized,
5948 then the following code:
5950 @smallexample @c ada
5951    Tab : Table := (others => <>);
5952 @end smallexample
5954 will suppress warnings on subsequent statements that access components
5955 of variable Tab.
5957 @item -gnatw.v
5958 @emph{Activate info messages for non-default bit order.}
5959 @cindex @option{-gnatw.v} (@command{gcc})
5960 @cindex bit order warnings
5961 This switch activates messages (labeled "info", they are not warnings,
5962 just informational messages) about the effects of non-default bit-order
5963 on records to which a component clause is applied. The effect of specifying
5964 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5965 these messages, which are given by default, are useful in understanding the
5966 exact consequences of using this feature. These messages
5967 can also be turned on using @option{-gnatwa}
5969 @item -gnatw.V
5970 @emph{Suppress info messages for non-default bit order.}
5971 @cindex @option{-gnatw.V} (@command{gcc})
5972 This switch suppresses information messages for the effects of specifying
5973 non-default bit order on record components with component clauses.
5975 @item -gnatww
5976 @emph{Activate warnings on wrong low bound assumption.}
5977 @cindex @option{-gnatww} (@command{gcc})
5978 @cindex String indexing warnings
5979 This switch activates warnings for indexing an unconstrained string parameter
5980 with a literal or S'Length. This is a case where the code is assuming that the
5981 low bound is one, which is in general not true (for example when a slice is
5982 passed). The default is that such warnings are generated.
5983 This warning can also be turned on using @option{-gnatwa}.
5985 @item -gnatwW
5986 @emph{Suppress warnings on wrong low bound assumption.}
5987 @cindex @option{-gnatwW} (@command{gcc})
5988 This switch suppresses warnings for indexing an unconstrained string parameter
5989 with a literal or S'Length. Note that this warning can also be suppressed
5990 in a particular case by adding an
5991 assertion that the lower bound is 1,
5992 as shown in the following example.
5994 @smallexample @c ada
5995    procedure K (S : String) is
5996       pragma Assert (S'First = 1);
5997       @dots{}
5998 @end smallexample
6000 @item -gnatw.w
6001 @emph{Activate warnings on unnecessary Warnings Off pragmas}
6002 @cindex @option{-gnatw.w} (@command{gcc})
6003 @cindex Warnings Off control
6004 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
6005 where either the pragma is entirely useless (because it suppresses no
6006 warnings), or it could be replaced by @code{pragma Unreferenced} or
6007 @code{pragma Unmodified}. The default is that these warnings are not given.
6008 Note that this warning is not included in -gnatwa, it must be
6009 activated explicitly.
6011 @item -gnatw.W
6012 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
6013 @cindex @option{-gnatw.W} (@command{gcc})
6014 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
6016 @item -gnatwx
6017 @emph{Activate warnings on Export/Import pragmas.}
6018 @cindex @option{-gnatwx} (@command{gcc})
6019 @cindex Export/Import pragma warnings
6020 This switch activates warnings on Export/Import pragmas when
6021 the compiler detects a possible conflict between the Ada and
6022 foreign language calling sequences. For example, the use of
6023 default parameters in a convention C procedure is dubious
6024 because the C compiler cannot supply the proper default, so
6025 a warning is issued. The default is that such warnings are
6026 generated.
6027 This warning can also be turned on using @option{-gnatwa}.
6029 @item -gnatwX
6030 @emph{Suppress warnings on Export/Import pragmas.}
6031 @cindex @option{-gnatwX} (@command{gcc})
6032 This switch suppresses warnings on Export/Import pragmas.
6033 The sense of this is that you are telling the compiler that
6034 you know what you are doing in writing the pragma, and it
6035 should not complain at you.
6037 @item -gnatw.x
6038 @emph{Activate warnings for No_Exception_Propagation mode.}
6039 @cindex @option{-gnatwm} (@command{gcc})
6040 This switch activates warnings for exception usage when pragma Restrictions
6041 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
6042 explicit exception raises which are not covered by a local handler, and for
6043 exception handlers which do not cover a local raise. The default is that these
6044 warnings are not given.
6046 @item -gnatw.X
6047 @emph{Disable warnings for No_Exception_Propagation mode.}
6048 This switch disables warnings for exception usage when pragma Restrictions
6049 (No_Exception_Propagation) is in effect.
6051 @item -gnatwy
6052 @emph{Activate warnings for Ada compatibility issues.}
6053 @cindex @option{-gnatwy} (@command{gcc})
6054 @cindex Ada compatibility issues warnings
6055 For the most part, newer versions of Ada are upwards compatible
6056 with older versions. For example, Ada 2005 programs will almost
6057 always work when compiled as Ada 2012.
6058 However there are some exceptions (for example the fact that
6059 @code{some} is now a reserved word in Ada 2012). This
6060 switch activates several warnings to help in identifying
6061 and correcting such incompatibilities. The default is that
6062 these warnings are generated. Note that at one point Ada 2005
6063 was called Ada 0Y, hence the choice of character.
6064 This warning can also be turned on using @option{-gnatwa}.
6066 @item -gnatwY
6067 @emph{Disable warnings for Ada compatibility issues.}
6068 @cindex @option{-gnatwY} (@command{gcc})
6069 @cindex Ada compatibility issues warnings
6070 This switch suppresses the warnings intended to help in identifying
6071 incompatibilities between Ada language versions.
6073 @item -gnatwz
6074 @emph{Activate warnings on unchecked conversions.}
6075 @cindex @option{-gnatwz} (@command{gcc})
6076 @cindex Unchecked_Conversion warnings
6077 This switch activates warnings for unchecked conversions
6078 where the types are known at compile time to have different
6079 sizes. The default
6080 is that such warnings are generated. Warnings are also
6081 generated for subprogram pointers with different conventions,
6082 and, on VMS only, for data pointers with different conventions.
6083 This warning can also be turned on using @option{-gnatwa}.
6085 @item -gnatwZ
6086 @emph{Suppress warnings on unchecked conversions.}
6087 @cindex @option{-gnatwZ} (@command{gcc})
6088 This switch suppresses warnings for unchecked conversions
6089 where the types are known at compile time to have different
6090 sizes or conventions.
6092 @item ^-Wunused^WARNINGS=UNUSED^
6093 @cindex @option{-Wunused}
6094 The warnings controlled by the @option{-gnatw} switch are generated by
6095 the front end of the compiler. The @option{GCC} back end can provide
6096 additional warnings and they are controlled by the @option{-W} switch.
6097 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
6098 warnings for entities that are declared but not referenced.
6100 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
6101 @cindex @option{-Wuninitialized}
6102 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
6103 the back end warning for uninitialized variables. This switch must be
6104 used in conjunction with an optimization level greater than zero.
6106 @item -Wstack-usage=@var{len}
6107 @cindex @option{-Wstack-usage}
6108 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
6109 See @ref{Static Stack Usage Analysis} for details.
6111 @item ^-Wall^/ALL_BACK_END_WARNINGS^
6112 @cindex @option{-Wall}
6113 This switch enables most warnings from the @option{GCC} back end.
6114 The code generator detects a number of warning situations that are missed
6115 by the @option{GNAT} front end, and this switch can be used to activate them.
6116 The use of this switch also sets the default front end warning mode to
6117 @option{-gnatwa}, that is, most front end warnings activated as well.
6119 @item ^-w^/NO_BACK_END_WARNINGS^
6120 @cindex @option{-w}
6121 Conversely, this switch suppresses warnings from the @option{GCC} back end.
6122 The use of this switch also sets the default front end warning mode to
6123 @option{-gnatws}, that is, front end warnings suppressed as well.
6125 @end table
6127 @noindent
6128 @ifclear vms
6129 A string of warning parameters can be used in the same parameter. For example:
6131 @smallexample
6132 -gnatwaGe
6133 @end smallexample
6135 @noindent
6136 will turn on all optional warnings except for unrecognized pragma warnings,
6137 and also specify that warnings should be treated as errors.
6138 @end ifclear
6140 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
6142 @table @option
6143 @c !sort!
6144 @item -gnatw.a
6145 @item -gnatwB
6146 @item -gnatw.b
6147 @item -gnatwC
6148 @item -gnatw.C
6149 @item -gnatwD
6150 @item -gnatwF
6151 @item -gnatwg
6152 @item -gnatwH
6153 @item -gnatwi
6154 @item -gnatw.I
6155 @item -gnatwJ
6156 @item -gnatwK
6157 @item -gnatwL
6158 @item -gnatw.L
6159 @item -gnatwM
6160 @item -gnatw.m
6161 @item -gnatwn
6162 @item -gnatwo
6163 @item -gnatw.O
6164 @item -gnatwP
6165 @item -gnatw.P
6166 @item -gnatwq
6167 @item -gnatwR
6168 @item -gnatw.R
6169 @item -gnatw.S
6170 @item -gnatwT
6171 @item -gnatw.T
6172 @item -gnatwU
6173 @item -gnatwv
6174 @item -gnatww
6175 @item -gnatw.W
6176 @item -gnatwx
6177 @item -gnatw.X
6178 @item -gnatwy
6179 @item -gnatwz
6181 @end table
6183 @node Debugging and Assertion Control
6184 @subsection Debugging and Assertion Control
6186 @table @option
6187 @item -gnata
6188 @cindex @option{-gnata} (@command{gcc})
6189 @findex Assert
6190 @findex Debug
6191 @cindex Assertions
6193 @noindent
6194 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6195 are ignored. This switch, where @samp{a} stands for assert, causes
6196 @code{Assert} and @code{Debug} pragmas to be activated.
6198 The pragmas have the form:
6200 @smallexample
6201 @cartouche
6202    @b{pragma} Assert (@var{Boolean-expression} @r{[},
6203                       @var{static-string-expression}@r{]})
6204    @b{pragma} Debug (@var{procedure call})
6205 @end cartouche
6206 @end smallexample
6208 @noindent
6209 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6210 If the result is @code{True}, the pragma has no effect (other than
6211 possible side effects from evaluating the expression). If the result is
6212 @code{False}, the exception @code{Assert_Failure} declared in the package
6213 @code{System.Assertions} is
6214 raised (passing @var{static-string-expression}, if present, as the
6215 message associated with the exception). If no string expression is
6216 given the default is a string giving the file name and line number
6217 of the pragma.
6219 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6220 @code{pragma Debug} may appear within a declaration sequence, allowing
6221 debugging procedures to be called between declarations.
6223 @ifset vms
6224 @item /DEBUG@r{[}=debug-level@r{]}
6225 @itemx  /NODEBUG
6226 Specifies how much debugging information is to be included in
6227 the resulting object file where 'debug-level' is one of the following:
6228 @table @code
6229 @item   TRACEBACK
6230 Include both debugger symbol records and traceback
6231 the object file.
6232 This is the default setting.
6233 @item   ALL
6234 Include both debugger symbol records and traceback in
6235 object file.
6236 @item   NONE
6237 Excludes both debugger symbol records and traceback
6238 the object file. Same as /NODEBUG.
6239 @item   SYMBOLS
6240 Includes only debugger symbol records in the object
6241 file. Note that this doesn't include traceback information.
6242 @end table
6243 @end ifset
6244 @end table
6246 @node Validity Checking
6247 @subsection Validity Checking
6248 @findex Validity Checking
6250 @noindent
6251 The Ada Reference Manual defines the concept of invalid values (see
6252 RM 13.9.1). The primary source of invalid values is uninitialized
6253 variables. A scalar variable that is left uninitialized may contain
6254 an invalid value; the concept of invalid does not apply to access or
6255 composite types.
6257 It is an error to read an invalid value, but the RM does not require
6258 run-time checks to detect such errors, except for some minimal
6259 checking to prevent erroneous execution (i.e. unpredictable
6260 behavior). This corresponds to the @option{-gnatVd} switch below,
6261 which is the default. For example, by default, if the expression of a
6262 case statement is invalid, it will raise Constraint_Error rather than
6263 causing a wild jump, and if an array index on the left-hand side of an
6264 assignment is invalid, it will raise Constraint_Error rather than
6265 overwriting an arbitrary memory location.
6267 The @option{-gnatVa} may be used to enable additional validity checks,
6268 which are not required by the RM. These checks are often very
6269 expensive (which is why the RM does not require them). These checks
6270 are useful in tracking down uninitialized variables, but they are
6271 not usually recommended for production builds.
6273 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6274 control; you can enable whichever validity checks you desire. However,
6275 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6276 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6277 sufficient for non-debugging use.
6279 The @option{-gnatB} switch tells the compiler to assume that all
6280 values are valid (that is, within their declared subtype range)
6281 except in the context of a use of the Valid attribute. This means
6282 the compiler can generate more efficient code, since the range
6283 of values is better known at compile time. However, an uninitialized
6284 variable can cause wild jumps and memory corruption in this mode.
6286 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6287 checking mode as described below.
6288 @ifclear vms
6289 The @code{x} argument is a string of letters that
6290 indicate validity checks that are performed or not performed in addition
6291 to the default checks required by Ada as described above.
6292 @end ifclear
6293 @ifset vms
6294 The options allowed for this qualifier
6295 indicate validity checks that are performed or not performed in addition
6296 to the default checks required by Ada as described above.
6297 @end ifset
6299 @table @option
6300 @c !sort!
6301 @item -gnatVa
6302 @emph{All validity checks.}
6303 @cindex @option{-gnatVa} (@command{gcc})
6304 All validity checks are turned on.
6305 @ifclear vms
6306 That is, @option{-gnatVa} is
6307 equivalent to @option{gnatVcdfimorst}.
6308 @end ifclear
6310 @item -gnatVc
6311 @emph{Validity checks for copies.}
6312 @cindex @option{-gnatVc} (@command{gcc})
6313 The right hand side of assignments, and the initializing values of
6314 object declarations are validity checked.
6316 @item -gnatVd
6317 @emph{Default (RM) validity checks.}
6318 @cindex @option{-gnatVd} (@command{gcc})
6319 Some validity checks are done by default following normal Ada semantics
6320 (RM 13.9.1 (9-11)).
6321 A check is done in case statements that the expression is within the range
6322 of the subtype. If it is not, Constraint_Error is raised.
6323 For assignments to array components, a check is done that the expression used
6324 as index is within the range. If it is not, Constraint_Error is raised.
6325 Both these validity checks may be turned off using switch @option{-gnatVD}.
6326 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6327 switch @option{-gnatVd} will leave the checks turned on.
6328 Switch @option{-gnatVD} should be used only if you are sure that all such
6329 expressions have valid values. If you use this switch and invalid values
6330 are present, then the program is erroneous, and wild jumps or memory
6331 overwriting may occur.
6333 @item -gnatVe
6334 @emph{Validity checks for elementary components.}
6335 @cindex @option{-gnatVe} (@command{gcc})
6336 In the absence of this switch, assignments to record or array components are
6337 not validity checked, even if validity checks for assignments generally
6338 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6339 require valid data, but assignment of individual components does. So for
6340 example, there is a difference between copying the elements of an array with a
6341 slice assignment, compared to assigning element by element in a loop. This
6342 switch allows you to turn off validity checking for components, even when they
6343 are assigned component by component.
6345 @item -gnatVf
6346 @emph{Validity checks for floating-point values.}
6347 @cindex @option{-gnatVf} (@command{gcc})
6348 In the absence of this switch, validity checking occurs only for discrete
6349 values. If @option{-gnatVf} is specified, then validity checking also applies
6350 for floating-point values, and NaNs and infinities are considered invalid,
6351 as well as out of range values for constrained types. Note that this means
6352 that standard IEEE infinity mode is not allowed. The exact contexts
6353 in which floating-point values are checked depends on the setting of other
6354 options. For example,
6355 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6356 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6357 (the order does not matter) specifies that floating-point parameters of mode
6358 @code{in} should be validity checked.
6360 @item -gnatVi
6361 @emph{Validity checks for @code{in} mode parameters}
6362 @cindex @option{-gnatVi} (@command{gcc})
6363 Arguments for parameters of mode @code{in} are validity checked in function
6364 and procedure calls at the point of call.
6366 @item -gnatVm
6367 @emph{Validity checks for @code{in out} mode parameters.}
6368 @cindex @option{-gnatVm} (@command{gcc})
6369 Arguments for parameters of mode @code{in out} are validity checked in
6370 procedure calls at the point of call. The @code{'m'} here stands for
6371 modify, since this concerns parameters that can be modified by the call.
6372 Note that there is no specific option to test @code{out} parameters,
6373 but any reference within the subprogram will be tested in the usual
6374 manner, and if an invalid value is copied back, any reference to it
6375 will be subject to validity checking.
6377 @item -gnatVn
6378 @emph{No validity checks.}
6379 @cindex @option{-gnatVn} (@command{gcc})
6380 This switch turns off all validity checking, including the default checking
6381 for case statements and left hand side subscripts. Note that the use of
6382 the switch @option{-gnatp} suppresses all run-time checks, including
6383 validity checks, and thus implies @option{-gnatVn}. When this switch
6384 is used, it cancels any other @option{-gnatV} previously issued.
6386 @item -gnatVo
6387 @emph{Validity checks for operator and attribute operands.}
6388 @cindex @option{-gnatVo} (@command{gcc})
6389 Arguments for predefined operators and attributes are validity checked.
6390 This includes all operators in package @code{Standard},
6391 the shift operators defined as intrinsic in package @code{Interfaces}
6392 and operands for attributes such as @code{Pos}. Checks are also made
6393 on individual component values for composite comparisons, and on the
6394 expressions in type conversions and qualified expressions. Checks are
6395 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6397 @item -gnatVp
6398 @emph{Validity checks for parameters.}
6399 @cindex @option{-gnatVp} (@command{gcc})
6400 This controls the treatment of parameters within a subprogram (as opposed
6401 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6402 of parameters on a call. If either of these call options is used, then
6403 normally an assumption is made within a subprogram that the input arguments
6404 have been validity checking at the point of call, and do not need checking
6405 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6406 is not made, and parameters are not assumed to be valid, so their validity
6407 will be checked (or rechecked) within the subprogram.
6409 @item -gnatVr
6410 @emph{Validity checks for function returns.}
6411 @cindex @option{-gnatVr} (@command{gcc})
6412 The expression in @code{return} statements in functions is validity
6413 checked.
6415 @item -gnatVs
6416 @emph{Validity checks for subscripts.}
6417 @cindex @option{-gnatVs} (@command{gcc})
6418 All subscripts expressions are checked for validity, whether they appear
6419 on the right side or left side (in default mode only left side subscripts
6420 are validity checked).
6422 @item -gnatVt
6423 @emph{Validity checks for tests.}
6424 @cindex @option{-gnatVt} (@command{gcc})
6425 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6426 statements are checked, as well as guard expressions in entry calls.
6428 @end table
6430 @noindent
6431 The @option{-gnatV} switch may be followed by
6432 ^a string of letters^a list of options^
6433 to turn on a series of validity checking options.
6434 For example,
6435 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6436 specifies that in addition to the default validity checking, copies and
6437 function return expressions are to be validity checked.
6438 In order to make it easier
6439 to specify the desired combination of effects,
6440 @ifclear vms
6441 the upper case letters @code{CDFIMORST} may
6442 be used to turn off the corresponding lower case option.
6443 @end ifclear
6444 @ifset vms
6445 the prefix @code{NO} on an option turns off the corresponding validity
6446 checking:
6447 @itemize @bullet
6448 @item @code{NOCOPIES}
6449 @item @code{NODEFAULT}
6450 @item @code{NOFLOATS}
6451 @item @code{NOIN_PARAMS}
6452 @item @code{NOMOD_PARAMS}
6453 @item @code{NOOPERANDS}
6454 @item @code{NORETURNS}
6455 @item @code{NOSUBSCRIPTS}
6456 @item @code{NOTESTS}
6457 @end itemize
6458 @end ifset
6459 Thus
6460 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6461 turns on all validity checking options except for
6462 checking of @code{@b{in out}} procedure arguments.
6464 The specification of additional validity checking generates extra code (and
6465 in the case of @option{-gnatVa} the code expansion can be substantial).
6466 However, these additional checks can be very useful in detecting
6467 uninitialized variables, incorrect use of unchecked conversion, and other
6468 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6469 is useful in conjunction with the extra validity checking, since this
6470 ensures that wherever possible uninitialized variables have invalid values.
6472 See also the pragma @code{Validity_Checks} which allows modification of
6473 the validity checking mode at the program source level, and also allows for
6474 temporary disabling of validity checks.
6476 @node Style Checking
6477 @subsection Style Checking
6478 @findex Style checking
6480 @noindent
6481 The @option{-gnaty^x^(option,option,@dots{})^} switch
6482 @cindex @option{-gnaty} (@command{gcc})
6483 causes the compiler to
6484 enforce specified style rules. A limited set of style rules has been used
6485 in writing the GNAT sources themselves. This switch allows user programs
6486 to activate all or some of these checks. If the source program fails a
6487 specified style check, an appropriate message is given, preceded by
6488 the character sequence ``(style)''. This message does not prevent
6489 successful compilation (unless the @option{-gnatwe} switch is used).
6491 Note that this is by no means intended to be a general facility for
6492 checking arbitrary coding standards. It is simply an embedding of the
6493 style rules we have chosen for the GNAT sources. If you are starting
6494 a project which does not have established style standards, you may
6495 find it useful to adopt the entire set of GNAT coding standards, or
6496 some subset of them. If you already have an established set of coding
6497 standards, then it may be that selected style checking options do
6498 indeed correspond to choices you have made, but for general checking
6499 of an existing set of coding rules, you should look to the gnatcheck
6500 tool, which is designed for that purpose.
6502 @ifset vms
6503 @code{(option,option,@dots{})} is a sequence of keywords
6504 @end ifset
6505 @ifclear vms
6506 The string @var{x} is a sequence of letters or digits
6507 @end ifclear
6508 indicating the particular style
6509 checks to be performed. The following checks are defined:
6511 @table @option
6512 @c !sort!
6513 @item 0-9
6514 @emph{Specify indentation level.}
6515 If a digit from 1-9 appears
6516 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6517 then proper indentation is checked, with the digit indicating the
6518 indentation level required. A value of zero turns off this style check.
6519 The general style of required indentation is as specified by
6520 the examples in the Ada Reference Manual. Full line comments must be
6521 aligned with the @code{--} starting on a column that is a multiple of
6522 the alignment level, or they may be aligned the same way as the following
6523 non-blank line (this is useful when full line comments appear in the middle
6524 of a statement.
6526 @item ^a^ATTRIBUTE^
6527 @emph{Check attribute casing.}
6528 Attribute names, including the case of keywords such as @code{digits}
6529 used as attributes names, must be written in mixed case, that is, the
6530 initial letter and any letter following an underscore must be uppercase.
6531 All other letters must be lowercase.
6533 @item ^A^ARRAY_INDEXES^
6534 @emph{Use of array index numbers in array attributes.}
6535 When using the array attributes First, Last, Range,
6536 or Length, the index number must be omitted for one-dimensional arrays
6537 and is required for multi-dimensional arrays.
6539 @item ^b^BLANKS^
6540 @emph{Blanks not allowed at statement end.}
6541 Trailing blanks are not allowed at the end of statements. The purpose of this
6542 rule, together with h (no horizontal tabs), is to enforce a canonical format
6543 for the use of blanks to separate source tokens.
6545 @item ^B^BOOLEAN_OPERATORS^
6546 @emph{Check Boolean operators.}
6547 The use of AND/OR operators is not permitted except in the cases of modular
6548 operands, array operands, and simple stand-alone boolean variables or
6549 boolean constants. In all other cases @code{and then}/@code{or else} are
6550 required.
6552 @item ^c^COMMENTS^
6553 @emph{Check comments, double space.}
6554 Comments must meet the following set of rules:
6556 @itemize @bullet
6558 @item
6559 The ``@code{--}'' that starts the column must either start in column one,
6560 or else at least one blank must precede this sequence.
6562 @item
6563 Comments that follow other tokens on a line must have at least one blank
6564 following the ``@code{--}'' at the start of the comment.
6566 @item
6567 Full line comments must have at least two blanks following the
6568 ``@code{--}'' that starts the comment, with the following exceptions.
6570 @item
6571 A line consisting only of the ``@code{--}'' characters, possibly preceded
6572 by blanks is permitted.
6574 @item
6575 A comment starting with ``@code{--x}'' where @code{x} is a special character
6576 is permitted.
6577 This allows proper processing of the output generated by specialized tools
6578 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6579 annotation
6580 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6581 special character is defined as being in one of the ASCII ranges
6582 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6583 Note that this usage is not permitted
6584 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6586 @item
6587 A line consisting entirely of minus signs, possibly preceded by blanks, is
6588 permitted. This allows the construction of box comments where lines of minus
6589 signs are used to form the top and bottom of the box.
6591 @item
6592 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6593 least one blank follows the initial ``@code{--}''. Together with the preceding
6594 rule, this allows the construction of box comments, as shown in the following
6595 example:
6596 @smallexample
6597 ---------------------------
6598 -- This is a box comment --
6599 -- with two text lines.  --
6600 ---------------------------
6601 @end smallexample
6602 @end itemize
6604 @item ^C^COMMENTS1^
6605 @emph{Check comments, single space.}
6606 This is identical to @code{^c^COMMENTS^} except that only one space
6607 is required following the @code{--} of a comment instead of two.
6609 @item ^d^DOS_LINE_ENDINGS^
6610 @emph{Check no DOS line terminators present.}
6611 All lines must be terminated by a single ASCII.LF
6612 character (in particular the DOS line terminator sequence CR/LF is not
6613 allowed).
6615 @item ^e^END^
6616 @emph{Check end/exit labels.}
6617 Optional labels on @code{end} statements ending subprograms and on
6618 @code{exit} statements exiting named loops, are required to be present.
6620 @item ^f^VTABS^
6621 @emph{No form feeds or vertical tabs.}
6622 Neither form feeds nor vertical tab characters are permitted
6623 in the source text.
6625 @item ^g^GNAT^
6626 @emph{GNAT style mode.}
6627 The set of style check switches is set to match that used by the GNAT sources.
6628 This may be useful when developing code that is eventually intended to be
6629 incorporated into GNAT. For further details, see GNAT sources.
6631 @item ^h^HTABS^
6632 @emph{No horizontal tabs.}
6633 Horizontal tab characters are not permitted in the source text.
6634 Together with the b (no blanks at end of line) check, this
6635 enforces a canonical form for the use of blanks to separate
6636 source tokens.
6638 @item ^i^IF_THEN^
6639 @emph{Check if-then layout.}
6640 The keyword @code{then} must appear either on the same
6641 line as corresponding @code{if}, or on a line on its own, lined
6642 up under the @code{if} with at least one non-blank line in between
6643 containing all or part of the condition to be tested.
6645 @item ^I^IN_MODE^
6646 @emph{check mode IN keywords.}
6647 Mode @code{in} (the default mode) is not
6648 allowed to be given explicitly. @code{in out} is fine,
6649 but not @code{in} on its own.
6651 @item ^k^KEYWORD^
6652 @emph{Check keyword casing.}
6653 All keywords must be in lower case (with the exception of keywords
6654 such as @code{digits} used as attribute names to which this check
6655 does not apply).
6657 @item ^l^LAYOUT^
6658 @emph{Check layout.}
6659 Layout of statement and declaration constructs must follow the
6660 recommendations in the Ada Reference Manual, as indicated by the
6661 form of the syntax rules. For example an @code{else} keyword must
6662 be lined up with the corresponding @code{if} keyword.
6664 There are two respects in which the style rule enforced by this check
6665 option are more liberal than those in the Ada Reference Manual. First
6666 in the case of record declarations, it is permissible to put the
6667 @code{record} keyword on the same line as the @code{type} keyword, and
6668 then the @code{end} in @code{end record} must line up under @code{type}.
6669 This is also permitted when the type declaration is split on two lines.
6670 For example, any of the following three layouts is acceptable:
6672 @smallexample @c ada
6673 @cartouche
6674 type q is record
6675    a : integer;
6676    b : integer;
6677 end record;
6679 type q is
6680    record
6681       a : integer;
6682       b : integer;
6683    end record;
6685 type q is
6686    record
6687       a : integer;
6688       b : integer;
6689 end record;
6691 @end cartouche
6692 @end smallexample
6694 @noindent
6695 Second, in the case of a block statement, a permitted alternative
6696 is to put the block label on the same line as the @code{declare} or
6697 @code{begin} keyword, and then line the @code{end} keyword up under
6698 the block label. For example both the following are permitted:
6700 @smallexample @c ada
6701 @cartouche
6702 Block : declare
6703    A : Integer := 3;
6704 begin
6705    Proc (A, A);
6706 end Block;
6708 Block :
6709    declare
6710       A : Integer := 3;
6711    begin
6712       Proc (A, A);
6713    end Block;
6714 @end cartouche
6715 @end smallexample
6717 @noindent
6718 The same alternative format is allowed for loops. For example, both of
6719 the following are permitted:
6721 @smallexample @c ada
6722 @cartouche
6723 Clear : while J < 10 loop
6724    A (J) := 0;
6725 end loop Clear;
6727 Clear :
6728    while J < 10 loop
6729       A (J) := 0;
6730    end loop Clear;
6731 @end cartouche
6732 @end smallexample
6734 @item ^Lnnn^MAX_NESTING=nnn^
6735 @emph{Set maximum nesting level.}
6736 The maximum level of nesting of constructs (including subprograms, loops,
6737 blocks, packages, and conditionals) may not exceed the given value
6738 @option{nnn}. A value of zero disconnects this style check.
6740 @item ^m^LINE_LENGTH^
6741 @emph{Check maximum line length.}
6742 The length of source lines must not exceed 79 characters, including
6743 any trailing blanks. The value of 79 allows convenient display on an
6744 80 character wide device or window, allowing for possible special
6745 treatment of 80 character lines. Note that this count is of
6746 characters in the source text. This means that a tab character counts
6747 as one character in this count and a wide character sequence counts as
6748 a single character (however many bytes are needed in the encoding).
6750 @item ^Mnnn^MAX_LENGTH=nnn^
6751 @emph{Set maximum line length.}
6752 The length of lines must not exceed the
6753 given value @option{nnn}. The maximum value that can be specified is 32767.
6754 If neither style option for setting the line length is used, then the
6755 default is 255. This also controls the maximum length of lexical elements,
6756 where the only restriction is that they must fit on a single line.
6758 @item ^n^STANDARD_CASING^
6759 @emph{Check casing of entities in Standard.}
6760 Any identifier from Standard must be cased
6761 to match the presentation in the Ada Reference Manual (for example,
6762 @code{Integer} and @code{ASCII.NUL}).
6764 @item ^N^NONE^
6765 @emph{Turn off all style checks.}
6766 All style check options are turned off.
6768 @item ^o^ORDERED_SUBPROGRAMS^
6769 @emph{Check order of subprogram bodies.}
6770 All subprogram bodies in a given scope
6771 (e.g.@: a package body) must be in alphabetical order. The ordering
6772 rule uses normal Ada rules for comparing strings, ignoring casing
6773 of letters, except that if there is a trailing numeric suffix, then
6774 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6775 before Junk10).
6777 @item ^O^OVERRIDING_INDICATORS^
6778 @emph{Check that overriding subprograms are explicitly marked as such.}
6779 The declaration of a primitive operation of a type extension that overrides
6780 an inherited operation must carry an overriding indicator.
6782 @item ^p^PRAGMA^
6783 @emph{Check pragma casing.}
6784 Pragma names must be written in mixed case, that is, the
6785 initial letter and any letter following an underscore must be uppercase.
6786 All other letters must be lowercase.
6788 @item ^r^REFERENCES^
6789 @emph{Check references.}
6790 All identifier references must be cased in the same way as the
6791 corresponding declaration. No specific casing style is imposed on
6792 identifiers. The only requirement is for consistency of references
6793 with declarations.
6795 @item ^s^SPECS^
6796 @emph{Check separate specs.}
6797 Separate declarations (``specs'') are required for subprograms (a
6798 body is not allowed to serve as its own declaration). The only
6799 exception is that parameterless library level procedures are
6800 not required to have a separate declaration. This exception covers
6801 the most frequent form of main program procedures.
6803 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6804 @emph{Check no statements after @code{then}/@code{else}.}
6805 No statements are allowed
6806 on the same line as a @code{then} or @code{else} keyword following the
6807 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6808 affected, and a special exception allows a pragma to appear after @code{else}.
6810 @item ^t^TOKEN^
6811 @emph{Check token spacing.}
6812 The following token spacing rules are enforced:
6814 @itemize @bullet
6816 @item
6817 The keywords @code{abs} and @code{not} must be followed by a space.
6819 @item
6820 The token @code{=>} must be surrounded by spaces.
6822 @item
6823 The token @code{<>} must be preceded by a space or a left parenthesis.
6825 @item
6826 Binary operators other than @code{**} must be surrounded by spaces.
6827 There is no restriction on the layout of the @code{**} binary operator.
6829 @item
6830 Colon must be surrounded by spaces.
6832 @item
6833 Colon-equal (assignment, initialization) must be surrounded by spaces.
6835 @item
6836 Comma must be the first non-blank character on the line, or be
6837 immediately preceded by a non-blank character, and must be followed
6838 by a space.
6840 @item
6841 If the token preceding a left parenthesis ends with a letter or digit, then
6842 a space must separate the two tokens.
6844 @item
6845 if the token following a right parenthesis starts with a letter or digit, then
6846 a space must separate the two tokens.
6848 @item
6849 A right parenthesis must either be the first non-blank character on
6850 a line, or it must be preceded by a non-blank character.
6852 @item
6853 A semicolon must not be preceded by a space, and must not be followed by
6854 a non-blank character.
6856 @item
6857 A unary plus or minus may not be followed by a space.
6859 @item
6860 A vertical bar must be surrounded by spaces.
6861 @end itemize
6863 @item
6864 Exactly one blank (and no other white space) must appear between
6865 a @code{not} token and a following @code{in} token.
6867 @item ^u^UNNECESSARY_BLANK_LINES^
6868 @emph{Check unnecessary blank lines.}
6869 Unnecessary blank lines are not allowed. A blank line is considered
6870 unnecessary if it appears at the end of the file, or if more than
6871 one blank line occurs in sequence.
6873 @item ^x^XTRA_PARENS^
6874 @emph{Check extra parentheses.}
6875 Unnecessary extra level of parentheses (C-style) are not allowed
6876 around conditions in @code{if} statements, @code{while} statements and
6877 @code{exit} statements.
6879 @item ^y^ALL_BUILTIN^
6880 @emph{Set all standard style check options}
6881 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6882 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6883 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6884 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6886 @ifclear vms
6887 @item -
6888 @emph{Remove style check options}
6889 This causes any subsequent options in the string to act as canceling the
6890 corresponding style check option. To cancel maximum nesting level control,
6891 use @option{L} parameter witout any integer value after that, because any
6892 digit following @option{-} in the parameter string of the @option{-gnaty}
6893 option will be threated as canceling indentation check. The same is true
6894 for @option{M} parameter. @option{y} and @option{N} parameters are not
6895 allowed after @option{-}.
6897 @item +
6898 This causes any subsequent options in the string to enable the corresponding
6899 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6900 if any.
6901 @end ifclear
6903 @ifset vms
6904 @item NOxxx
6905 @emph{Removing style check options}
6906 If the name of a style check is preceded by @option{NO} then the corresponding
6907 style check is turned off. For example @option{NOCOMMENTS} turns off style
6908 checking for comments.
6909 @end ifset
6910 @end table
6912 @noindent
6913 In the above rules, appearing in column one is always permitted, that is,
6914 counts as meeting either a requirement for a required preceding space,
6915 or as meeting a requirement for no preceding space.
6917 Appearing at the end of a line is also always permitted, that is, counts
6918 as meeting either a requirement for a following space, or as meeting
6919 a requirement for no following space.
6921 @noindent
6922 If any of these style rules is violated, a message is generated giving
6923 details on the violation. The initial characters of such messages are
6924 always ``@code{(style)}''. Note that these messages are treated as warning
6925 messages, so they normally do not prevent the generation of an object
6926 file. The @option{-gnatwe} switch can be used to treat warning messages,
6927 including style messages, as fatal errors.
6929 The switch
6930 @ifclear vms
6931 @option{-gnaty} on its own (that is not
6932 followed by any letters or digits) is equivalent
6933 to the use of @option{-gnatyy} as described above, that is all
6934 built-in standard style check options are enabled.
6936 @end ifclear
6937 @ifset vms
6938 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6939 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6940 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6941 @end ifset
6943 The switch
6944 @ifclear vms
6945 @option{-gnatyN}
6946 @end ifclear
6947 @ifset vms
6948 /STYLE_CHECKS=NONE
6949 @end ifset
6950 clears any previously set style checks.
6952 @node Run-Time Checks
6953 @subsection Run-Time Checks
6954 @cindex Division by zero
6955 @cindex Access before elaboration
6956 @cindex Checks, division by zero
6957 @cindex Checks, access before elaboration
6958 @cindex Checks, stack overflow checking
6960 @noindent
6961 By default, the following checks are suppressed: integer overflow
6962 checks, stack overflow checks, and checks for access before
6963 elaboration on subprogram calls. All other checks, including range
6964 checks and array bounds checks, are turned on by default. The
6965 following @command{gcc} switches refine this default behavior.
6967 @table @option
6968 @c !sort!
6969 @item -gnatp
6970 @cindex @option{-gnatp} (@command{gcc})
6971 @cindex Suppressing checks
6972 @cindex Checks, suppressing
6973 @findex Suppress
6974 This switch causes the unit to be compiled
6975 as though @code{pragma Suppress (All_checks)}
6976 had been present in the source. Validity checks are also eliminated (in
6977 other words @option{-gnatp} also implies @option{-gnatVn}.
6978 Use this switch to improve the performance
6979 of the code at the expense of safety in the presence of invalid data or
6980 program bugs.
6982 Note that when checks are suppressed, the compiler is allowed, but not
6983 required, to omit the checking code. If the run-time cost of the
6984 checking code is zero or near-zero, the compiler will generate it even
6985 if checks are suppressed. In particular, if the compiler can prove
6986 that a certain check will necessarily fail, it will generate code to
6987 do an unconditional ``raise'', even if checks are suppressed. The
6988 compiler warns in this case. Another case in which checks may not be
6989 eliminated is when they are embedded in certain run time routines such
6990 as math library routines.
6992 Of course, run-time checks are omitted whenever the compiler can prove
6993 that they will not fail, whether or not checks are suppressed.
6995 Note that if you suppress a check that would have failed, program
6996 execution is erroneous, which means the behavior is totally
6997 unpredictable. The program might crash, or print wrong answers, or
6998 do anything else. It might even do exactly what you wanted it to do
6999 (and then it might start failing mysteriously next week or next
7000 year). The compiler will generate code based on the assumption that
7001 the condition being checked is true, which can result in disaster if
7002 that assumption is wrong.
7004 The @option{-gnatp} switch has no effect if a subsequent
7005 @option{-gnat-p} switch appears.
7007 @item -gnat-p
7008 @cindex @option{-gnat-p} (@command{gcc})
7009 @cindex Suppressing checks
7010 @cindex Checks, suppressing
7011 @findex Suppress
7012 This switch cancels the effect of a previous @option{gnatp} switch.
7014 @item -gnato??
7015 @cindex @option{-gnato??} (@command{gcc})
7016 @cindex Overflow checks
7017 @cindex Overflow mode
7018 @cindex Check, overflow
7019 This switch controls the mode used for computing intermediate
7020 arithmetic integer operations, and also enables overflow checking.
7021 For a full description of overflow mode and checking control, see
7022 the ``Overflow Check Handling in GNAT'' appendix in this
7023 User's Guide.
7025 Overflow checks are always enabled by this switch. The argument
7026 controls the mode, using the codes
7028 @itemize
7029 @item 1 = STRICT
7030 In STRICT mode, intermediate operations are always done using the
7031 base type, and overflow checking ensures that the result is within
7032 the base type range.
7034 @item 2 = MINIMIZED
7035 In MINIMIZED mode, overflows in intermediate operations are avoided
7036 where possible by using a larger integer type for the computation
7037 (typically @code{Long_Long_Integer}). Overflow checking ensures that
7038 the result fits in this larger integer type.
7040 @item 3 = ELIMINATED
7041 In ELIMINATED mode, overflows in intermediate operations are avoided
7042 by using multi-precision arithmetic. In this case, overflow checking
7043 has no effect on intermediate operations (since overflow is impossible).
7044 @end itemize
7046 If two digits are present after @option{-gnato} then the first digit
7047 sets the mode for expressions outside assertions, and the second digit
7048 sets the mode for expressions within assertions. Here assertions is used
7049 in the technical sense (which includes for example precondition and
7050 postcondition expressions).
7052 If one digit is present, the corresponding mode is applicable to both
7053 expressions within and outside assertion expressions.
7055 If no digits are present, the default is to enable overflow checks
7056 and set STRICT mode for both kinds of expressions. This is compatible
7057 with the use of @option{-gnato} in previous versions of GNAT.
7059 @findex Machine_Overflows
7060 Note that the @option{-gnato??} switch does not affect the code generated
7061 for any floating-point operations; it applies only to integer
7062 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}, so overflow checking is
7077 not performed in default mode. This means that out of the box, with the
7078 default settings, @value{EDITION} does not do all the checks expected from the
7079 language description in the Ada Reference Manual. If you want all constraint
7080 checks to be performed, as described in this Manual, then you must
7081 explicitly use the @option{-gnato??} switch either on the @command{gnatmake} or
7082 @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 You can obtain information about the vectorization performed by the compiler
10982 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10983 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10984 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10986 @node Other Optimization Switches
10987 @subsection Other Optimization Switches
10988 @cindex Optimization Switches
10990 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10991 @command{gcc} optimization switches are potentially usable. These switches
10992 have not been extensively tested with GNAT but can generally be expected
10993 to work. Examples of switches in this category are @option{-funroll-loops}
10994 and the various target-specific @option{-m} options (in particular, it has
10995 been observed that @option{-march=xxx} can significantly improve performance
10996 on appropriate machines). For full details of these switches, see
10997 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10998 the GNU Compiler Collection (GCC)}.
11000 @node Optimization and Strict Aliasing
11001 @subsection Optimization and Strict Aliasing
11002 @cindex Aliasing
11003 @cindex Strict Aliasing
11004 @cindex No_Strict_Aliasing
11006 @noindent
11007 The strong typing capabilities of Ada allow an optimizer to generate
11008 efficient code in situations where other languages would be forced to
11009 make worst case assumptions preventing such optimizations. Consider
11010 the following example:
11012 @smallexample @c ada
11013 @cartouche
11014 procedure R is
11015    type Int1 is new Integer;
11016    type Int2 is new Integer;
11017    type Int1A is access Int1;
11018    type Int2A is access Int2;
11019    Int1V : Int1A;
11020    Int2V : Int2A;
11021    @dots{}
11023 begin
11024    @dots{}
11025    for J in Data'Range loop
11026       if Data (J) = Int1V.all then
11027          Int2V.all := Int2V.all + 1;
11028       end if;
11029    end loop;
11030    @dots{}
11031 end R;
11032 @end cartouche
11033 @end smallexample
11035 @noindent
11036 In this example, since the variable @code{Int1V} can only access objects
11037 of type @code{Int1}, and @code{Int2V} can only access objects of type
11038 @code{Int2}, there is no possibility that the assignment to
11039 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
11040 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
11041 for all iterations of the loop and avoid the extra memory reference
11042 required to dereference it each time through the loop.
11044 This kind of optimization, called strict aliasing analysis, is
11045 triggered by specifying an optimization level of @option{-O2} or
11046 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
11047 when access values are involved.
11049 However, although this optimization is always correct in terms of
11050 the formal semantics of the Ada Reference Manual, difficulties can
11051 arise if features like @code{Unchecked_Conversion} are used to break
11052 the typing system. Consider the following complete program example:
11054 @smallexample @c ada
11055 @cartouche
11056 package p1 is
11057    type int1 is new integer;
11058    type int2 is new integer;
11059    type a1 is access int1;
11060    type a2 is access int2;
11061 end p1;
11063 with p1; use p1;
11064 package p2 is
11065    function to_a2 (Input : a1) return a2;
11066 end p2;
11068 with Unchecked_Conversion;
11069 package body p2 is
11070    function to_a2 (Input : a1) return a2 is
11071       function to_a2u is
11072         new Unchecked_Conversion (a1, a2);
11073    begin
11074       return to_a2u (Input);
11075    end to_a2;
11076 end p2;
11078 with p2; use p2;
11079 with p1; use p1;
11080 with Text_IO; use Text_IO;
11081 procedure m is
11082    v1 : a1 := new int1;
11083    v2 : a2 := to_a2 (v1);
11084 begin
11085    v1.all := 1;
11086    v2.all := 0;
11087    put_line (int1'image (v1.all));
11088 end;
11089 @end cartouche
11090 @end smallexample
11092 @noindent
11093 This program prints out 0 in @option{-O0} or @option{-O1}
11094 mode, but it prints out 1 in @option{-O2} mode. That's
11095 because in strict aliasing mode, the compiler can and
11096 does assume that the assignment to @code{v2.all} could not
11097 affect the value of @code{v1.all}, since different types
11098 are involved.
11100 This behavior is not a case of non-conformance with the standard, since
11101 the Ada RM specifies that an unchecked conversion where the resulting
11102 bit pattern is not a correct value of the target type can result in an
11103 abnormal value and attempting to reference an abnormal value makes the
11104 execution of a program erroneous.  That's the case here since the result
11105 does not point to an object of type @code{int2}.  This means that the
11106 effect is entirely unpredictable.
11108 However, although that explanation may satisfy a language
11109 lawyer, in practice an applications programmer expects an
11110 unchecked conversion involving pointers to create true
11111 aliases and the behavior of printing 1 seems plain wrong.
11112 In this case, the strict aliasing optimization is unwelcome.
11114 Indeed the compiler recognizes this possibility, and the
11115 unchecked conversion generates a warning:
11117 @smallexample
11118 p2.adb:5:07: warning: possible aliasing problem with type "a2"
11119 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
11120 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
11121 @end smallexample
11123 @noindent
11124 Unfortunately the problem is recognized when compiling the body of
11125 package @code{p2}, but the actual "bad" code is generated while
11126 compiling the body of @code{m} and this latter compilation does not see
11127 the suspicious @code{Unchecked_Conversion}.
11129 As implied by the warning message, there are approaches you can use to
11130 avoid the unwanted strict aliasing optimization in a case like this.
11132 One possibility is to simply avoid the use of @option{-O2}, but
11133 that is a bit drastic, since it throws away a number of useful
11134 optimizations that do not involve strict aliasing assumptions.
11136 A less drastic approach is to compile the program using the
11137 option @option{-fno-strict-aliasing}. Actually it is only the
11138 unit containing the dereferencing of the suspicious pointer
11139 that needs to be compiled. So in this case, if we compile
11140 unit @code{m} with this switch, then we get the expected
11141 value of zero printed. Analyzing which units might need
11142 the switch can be painful, so a more reasonable approach
11143 is to compile the entire program with options @option{-O2}
11144 and @option{-fno-strict-aliasing}. If the performance is
11145 satisfactory with this combination of options, then the
11146 advantage is that the entire issue of possible "wrong"
11147 optimization due to strict aliasing is avoided.
11149 To avoid the use of compiler switches, the configuration
11150 pragma @code{No_Strict_Aliasing} with no parameters may be
11151 used to specify that for all access types, the strict
11152 aliasing optimization should be suppressed.
11154 However, these approaches are still overkill, in that they causes
11155 all manipulations of all access values to be deoptimized. A more
11156 refined approach is to concentrate attention on the specific
11157 access type identified as problematic.
11159 First, if a careful analysis of uses of the pointer shows
11160 that there are no possible problematic references, then
11161 the warning can be suppressed by bracketing the
11162 instantiation of @code{Unchecked_Conversion} to turn
11163 the warning off:
11165 @smallexample @c ada
11166    pragma Warnings (Off);
11167    function to_a2u is
11168      new Unchecked_Conversion (a1, a2);
11169    pragma Warnings (On);
11170 @end smallexample
11172 @noindent
11173 Of course that approach is not appropriate for this particular
11174 example, since indeed there is a problematic reference. In this
11175 case we can take one of two other approaches.
11177 The first possibility is to move the instantiation of unchecked
11178 conversion to the unit in which the type is declared. In
11179 this example, we would move the instantiation of
11180 @code{Unchecked_Conversion} from the body of package
11181 @code{p2} to the spec of package @code{p1}. Now the
11182 warning disappears. That's because any use of the
11183 access type knows there is a suspicious unchecked
11184 conversion, and the strict aliasing optimization
11185 is automatically suppressed for the type.
11187 If it is not practical to move the unchecked conversion to the same unit
11188 in which the destination access type is declared (perhaps because the
11189 source type is not visible in that unit), you may use pragma
11190 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11191 same declarative sequence as the declaration of the access type:
11193 @smallexample @c ada
11194    type a2 is access int2;
11195    pragma No_Strict_Aliasing (a2);
11196 @end smallexample
11198 @noindent
11199 Here again, the compiler now knows that the strict aliasing optimization
11200 should be suppressed for any reference to type @code{a2} and the
11201 expected behavior is obtained.
11203 Finally, note that although the compiler can generate warnings for
11204 simple cases of unchecked conversions, there are tricker and more
11205 indirect ways of creating type incorrect aliases which the compiler
11206 cannot detect. Examples are the use of address overlays and unchecked
11207 conversions involving composite types containing access types as
11208 components. In such cases, no warnings are generated, but there can
11209 still be aliasing problems. One safe coding practice is to forbid the
11210 use of address clauses for type overlaying, and to allow unchecked
11211 conversion only for primitive types. This is not really a significant
11212 restriction since any possible desired effect can be achieved by
11213 unchecked conversion of access values.
11215 The aliasing analysis done in strict aliasing mode can certainly
11216 have significant benefits. We have seen cases of large scale
11217 application code where the time is increased by up to 5% by turning
11218 this optimization off. If you have code that includes significant
11219 usage of unchecked conversion, you might want to just stick with
11220 @option{-O1} and avoid the entire issue. If you get adequate
11221 performance at this level of optimization level, that's probably
11222 the safest approach. If tests show that you really need higher
11223 levels of optimization, then you can experiment with @option{-O2}
11224 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11225 has on size and speed of the code. If you really need to use
11226 @option{-O2} with strict aliasing in effect, then you should
11227 review any uses of unchecked conversion of access types,
11228 particularly if you are getting the warnings described above.
11230 @ifset vms
11231 @node Coverage Analysis
11232 @subsection Coverage Analysis
11234 @noindent
11235 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11236 the user to determine the distribution of execution time across a program,
11237 @pxref{Profiling} for details of usage.
11238 @end ifset
11241 @node Text_IO Suggestions
11242 @section @code{Text_IO} Suggestions
11243 @cindex @code{Text_IO} and performance
11245 @noindent
11246 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11247 the requirement of maintaining page and line counts. If performance
11248 is critical, a recommendation is to use @code{Stream_IO} instead of
11249 @code{Text_IO} for volume output, since this package has less overhead.
11251 If @code{Text_IO} must be used, note that by default output to the standard
11252 output and standard error files is unbuffered (this provides better
11253 behavior when output statements are used for debugging, or if the
11254 progress of a program is observed by tracking the output, e.g. by
11255 using the Unix @command{tail -f} command to watch redirected output.
11257 If you are generating large volumes of output with @code{Text_IO} and
11258 performance is an important factor, use a designated file instead
11259 of the standard output file, or change the standard output file to
11260 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11264 @node Reducing Size of Ada Executables with gnatelim
11265 @section Reducing Size of Ada Executables with @code{gnatelim}
11266 @findex gnatelim
11268 @noindent
11269 This section describes @command{gnatelim}, a tool which detects unused
11270 subprograms and helps the compiler to create a smaller executable for your
11271 program.
11273 @menu
11274 * About gnatelim::
11275 * Running gnatelim::
11276 * Processing Precompiled Libraries::
11277 * Correcting the List of Eliminate Pragmas::
11278 * Making Your Executables Smaller::
11279 * Summary of the gnatelim Usage Cycle::
11280 @end menu
11282 @node About gnatelim
11283 @subsection About @code{gnatelim}
11285 @noindent
11286 When a program shares a set of Ada
11287 packages with other programs, it may happen that this program uses
11288 only a fraction of the subprograms defined in these packages. The code
11289 created for these unused subprograms increases the size of the executable.
11291 @code{gnatelim} tracks unused subprograms in an Ada program and
11292 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11293 subprograms that are declared but never called. By placing the list of
11294 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11295 recompiling your program, you may decrease the size of its executable,
11296 because the compiler will not generate the code for 'eliminated' subprograms.
11297 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11298 information about this pragma.
11300 @code{gnatelim} needs as its input data the name of the main subprogram.
11302 If a set of source files is specified as @code{gnatelim} arguments, it
11303 treats these files as a complete set of sources making up a program to
11304 analyse, and analyses only these sources.
11306 After a full successful build of the main subprogram @code{gnatelim} can be
11307 called without  specifying sources to analyse, in this case it computes
11308 the source closure of the main unit from the @file{ALI} files.
11310 The following command will create the set of @file{ALI} files needed for
11311 @code{gnatelim}:
11313 @smallexample
11314 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11315 @end smallexample
11317 Note that @code{gnatelim} does not need object files.
11319 @node Running gnatelim
11320 @subsection Running @code{gnatelim}
11322 @noindent
11323 @code{gnatelim} has the following command-line interface:
11325 @smallexample
11326 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11327 @end smallexample
11329 @noindent
11330 @var{main_unit_name} should be a name of a source file that contains the main
11331 subprogram of a program (partition).
11333 Each @var{filename} is the name (including the extension) of a source
11334 file to process. ``Wildcards'' are allowed, and
11335 the file name may contain path information.
11337 @samp{@var{gcc_switches}} is a list of switches for
11338 @command{gcc}. They will be passed on to all compiler invocations made by
11339 @command{gnatelim} to generate the ASIS trees. Here you can provide
11340 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11341 use the @option{-gnatec} switch to set the configuration file,
11342 use the @option{-gnat05} switch if sources should be compiled in
11343 Ada 2005 mode etc.
11345 @code{gnatelim} has the following switches:
11347 @table @option
11348 @c !sort!
11349 @item ^-files^/FILES^=@var{filename}
11350 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11351 Take the argument source files from the specified file. This file should be an
11352 ordinary text file containing file names separated by spaces or
11353 line breaks. You can use this switch more than once in the same call to
11354 @command{gnatelim}. You also can combine this switch with
11355 an explicit list of files.
11357 @item ^-log^/LOG^
11358 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11359 Duplicate all the output sent to @file{stderr} into a log file. The log file
11360 is named @file{gnatelim.log} and is located in the current directory.
11362 @item ^-log^/LOGFILE^=@var{filename}
11363 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11364 Duplicate all the output sent to @file{stderr} into a specified log file.
11366 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11367 @item ^--no-elim-dispatch^/NO_DISPATCH^
11368 Do not generate pragmas for dispatching operations.
11370 @item ^--ignore^/IGNORE^=@var{filename}
11371 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11372 Do not generate pragmas for subprograms declared in the sources
11373 listed in a specified file
11375 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11376 @item ^-o^/OUTPUT^=@var{report_file}
11377 Put @command{gnatelim} output into a specified file. If this file already exists,
11378 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11379 into @file{stderr}
11381 @item ^-q^/QUIET^
11382 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11383 Quiet mode: by default @code{gnatelim} outputs to the standard error
11384 stream the number of program units left to be processed. This option turns
11385 this trace off.
11387 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11388 @item ^-t^/TIME^
11389 Print out execution time.
11391 @item ^-v^/VERBOSE^
11392 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11393 Verbose mode: @code{gnatelim} version information is printed as Ada
11394 comments to the standard output stream. Also, in addition to the number of
11395 program units left @code{gnatelim} will output the name of the current unit
11396 being processed.
11398 @item ^-wq^/WARNINGS=QUIET^
11399 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11400 Quiet warning mode - some warnings are suppressed. In particular warnings that
11401 indicate that the analysed set of sources is incomplete to make up a
11402 partition and that some subprogram bodies are missing are not generated.
11403 @end table
11405 @noindent
11406 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11407 driver (see @ref{The GNAT Driver and Project Files}).
11409 @node Processing Precompiled Libraries
11410 @subsection Processing Precompiled Libraries
11412 @noindent
11413 If some program uses a precompiled Ada library, it can be processed by
11414 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11415 Eliminate pragma for a subprogram if the body of this subprogram has not
11416 been analysed, this is a typical case for subprograms from precompiled
11417 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11418 warnings about missing source files and non-analyzed subprogram bodies
11419 that can be generated when processing precompiled Ada libraries.
11421 @node Correcting the List of Eliminate Pragmas
11422 @subsection Correcting the List of Eliminate Pragmas
11424 @noindent
11425 In some rare cases @code{gnatelim} may try to eliminate
11426 subprograms that are actually called in the program. In this case, the
11427 compiler will generate an error message of the form:
11429 @smallexample
11430 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11431 @end smallexample
11433 @noindent
11434 You will need to manually remove the wrong @code{Eliminate} pragmas from
11435 the configuration file indicated in the error message. You should recompile
11436 your program from scratch after that, because you need a consistent
11437 configuration file(s) during the entire compilation.
11439 @node Making Your Executables Smaller
11440 @subsection Making Your Executables Smaller
11442 @noindent
11443 In order to get a smaller executable for your program you now have to
11444 recompile the program completely with the configuration file containing
11445 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11446 @file{gnat.adc} file located in your current directory, just do:
11448 @smallexample
11449 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11450 @end smallexample
11452 @noindent
11453 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11454 recompile everything
11455 with the set of pragmas @code{Eliminate} that you have obtained with
11456 @command{gnatelim}).
11458 Be aware that the set of @code{Eliminate} pragmas is specific to each
11459 program. It is not recommended to merge sets of @code{Eliminate}
11460 pragmas created for different programs in one configuration file.
11462 @node Summary of the gnatelim Usage Cycle
11463 @subsection Summary of the @code{gnatelim} Usage Cycle
11465 @noindent
11466 Here is a quick summary of the steps to be taken in order to reduce
11467 the size of your executables with @code{gnatelim}. You may use
11468 other GNAT options to control the optimization level,
11469 to produce the debugging information, to set search path, etc.
11471 @enumerate
11472 @item
11473 Create a complete set of @file{ALI} files (if the program has not been
11474 built already)
11476 @smallexample
11477 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11478 @end smallexample
11480 @item
11481 Generate a list of @code{Eliminate} pragmas in default configuration file
11482 @file{gnat.adc} in the current directory
11483 @smallexample
11484 @ifset vms
11485 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11486 @end ifset
11487 @ifclear vms
11488 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11489 @end ifclear
11490 @end smallexample
11492 @item
11493 Recompile the application
11495 @smallexample
11496 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11497 @end smallexample
11499 @end enumerate
11501 @node Reducing Size of Executables with unused subprogram/data elimination
11502 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11503 @findex unused subprogram/data elimination
11505 @noindent
11506 This section describes how you can eliminate unused subprograms and data from
11507 your executable just by setting options at compilation time.
11509 @menu
11510 * About unused subprogram/data elimination::
11511 * Compilation options::
11512 * Example of unused subprogram/data elimination::
11513 @end menu
11515 @node About unused subprogram/data elimination
11516 @subsection About unused subprogram/data elimination
11518 @noindent
11519 By default, an executable contains all code and data of its composing objects
11520 (directly linked or coming from statically linked libraries), even data or code
11521 never used by this executable.
11523 This feature will allow you to eliminate such unused code from your
11524 executable, making it smaller (in disk and in memory).
11526 This functionality is available on all Linux platforms except for the IA-64
11527 architecture and on all cross platforms using the ELF binary file format.
11528 In both cases GNU binutils version 2.16 or later are required to enable it.
11530 @node Compilation options
11531 @subsection Compilation options
11533 @noindent
11534 The operation of eliminating the unused code and data from the final executable
11535 is directly performed by the linker.
11537 In order to do this, it has to work with objects compiled with the
11538 following options:
11539 @option{-ffunction-sections} @option{-fdata-sections}.
11540 @cindex @option{-ffunction-sections} (@command{gcc})
11541 @cindex @option{-fdata-sections} (@command{gcc})
11542 These options are usable with C and Ada files.
11543 They will place respectively each
11544 function or data in a separate section in the resulting object file.
11546 Once the objects and static libraries are created with these options, the
11547 linker can perform the dead code elimination. You can do this by setting
11548 the @option{-Wl,--gc-sections} option to gcc command or in the
11549 @option{-largs} section of @command{gnatmake}. This will perform a
11550 garbage collection of code and data never referenced.
11552 If the linker performs a partial link (@option{-r} ld linker option), then you
11553 will need to provide one or several entry point using the
11554 @option{-e} / @option{--entry} ld option.
11556 Note that objects compiled without the @option{-ffunction-sections} and
11557 @option{-fdata-sections} options can still be linked with the executable.
11558 However, no dead code elimination will be performed on those objects (they will
11559 be linked as is).
11561 The GNAT static library is now compiled with -ffunction-sections and
11562 -fdata-sections on some platforms. This allows you to eliminate the unused code
11563 and data of the GNAT library from your executable.
11565 @node Example of unused subprogram/data elimination
11566 @subsection Example of unused subprogram/data elimination
11568 @noindent
11569 Here is a simple example:
11571 @smallexample @c ada
11572 with Aux;
11574 procedure Test is
11575 begin
11576    Aux.Used (10);
11577 end Test;
11579 package Aux is
11580    Used_Data   : Integer;
11581    Unused_Data : Integer;
11583    procedure Used   (Data : Integer);
11584    procedure Unused (Data : Integer);
11585 end Aux;
11587 package body Aux is
11588    procedure Used (Data : Integer) is
11589    begin
11590       Used_Data := Data;
11591    end Used;
11593    procedure Unused (Data : Integer) is
11594    begin
11595       Unused_Data := Data;
11596    end Unused;
11597 end Aux;
11598 @end smallexample
11600 @noindent
11601 @code{Unused} and @code{Unused_Data} are never referenced in this code
11602 excerpt, and hence they may be safely removed from the final executable.
11604 @smallexample
11605 $ gnatmake test
11607 $ nm test | grep used
11608 020015f0 T aux__unused
11609 02005d88 B aux__unused_data
11610 020015cc T aux__used
11611 02005d84 B aux__used_data
11613 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11614      -largs -Wl,--gc-sections
11616 $ nm test | grep used
11617 02005350 T aux__used
11618 0201ffe0 B aux__used_data
11619 @end smallexample
11621 @noindent
11622 It can be observed that the procedure @code{Unused} and the object
11623 @code{Unused_Data} are removed by the linker when using the
11624 appropriate options.
11626 @c ********************************
11627 @node Renaming Files Using gnatchop
11628 @chapter Renaming Files Using @code{gnatchop}
11629 @findex gnatchop
11631 @noindent
11632 This chapter discusses how to handle files with multiple units by using
11633 the @code{gnatchop} utility. This utility is also useful in renaming
11634 files to meet the standard GNAT default file naming conventions.
11636 @menu
11637 * Handling Files with Multiple Units::
11638 * Operating gnatchop in Compilation Mode::
11639 * Command Line for gnatchop::
11640 * Switches for gnatchop::
11641 * Examples of gnatchop Usage::
11642 @end menu
11644 @node Handling Files with Multiple Units
11645 @section Handling Files with Multiple Units
11647 @noindent
11648 The basic compilation model of GNAT requires that a file submitted to the
11649 compiler have only one unit and there be a strict correspondence
11650 between the file name and the unit name.
11652 The @code{gnatchop} utility allows both of these rules to be relaxed,
11653 allowing GNAT to process files which contain multiple compilation units
11654 and files with arbitrary file names. @code{gnatchop}
11655 reads the specified file and generates one or more output files,
11656 containing one unit per file. The unit and the file name correspond,
11657 as required by GNAT.
11659 If you want to permanently restructure a set of ``foreign'' files so that
11660 they match the GNAT rules, and do the remaining development using the
11661 GNAT structure, you can simply use @command{gnatchop} once, generate the
11662 new set of files and work with them from that point on.
11664 Alternatively, if you want to keep your files in the ``foreign'' format,
11665 perhaps to maintain compatibility with some other Ada compilation
11666 system, you can set up a procedure where you use @command{gnatchop} each
11667 time you compile, regarding the source files that it writes as temporary
11668 files that you throw away.
11670 Note that if your file containing multiple units starts with a byte order
11671 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11672 will each start with a copy of this BOM, meaning that they can be compiled
11673 automatically in UTF-8 mode without needing to specify an explicit encoding.
11675 @node Operating gnatchop in Compilation Mode
11676 @section Operating gnatchop in Compilation Mode
11678 @noindent
11679 The basic function of @code{gnatchop} is to take a file with multiple units
11680 and split it into separate files. The boundary between files is reasonably
11681 clear, except for the issue of comments and pragmas. In default mode, the
11682 rule is that any pragmas between units belong to the previous unit, except
11683 that configuration pragmas always belong to the following unit. Any comments
11684 belong to the following unit. These rules
11685 almost always result in the right choice of
11686 the split point without needing to mark it explicitly and most users will
11687 find this default to be what they want. In this default mode it is incorrect to
11688 submit a file containing only configuration pragmas, or one that ends in
11689 configuration pragmas, to @code{gnatchop}.
11691 However, using a special option to activate ``compilation mode'',
11692 @code{gnatchop}
11693 can perform another function, which is to provide exactly the semantics
11694 required by the RM for handling of configuration pragmas in a compilation.
11695 In the absence of configuration pragmas (at the main file level), this
11696 option has no effect, but it causes such configuration pragmas to be handled
11697 in a quite different manner.
11699 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11700 only configuration pragmas, then this file is appended to the
11701 @file{gnat.adc} file in the current directory. This behavior provides
11702 the required behavior described in the RM for the actions to be taken
11703 on submitting such a file to the compiler, namely that these pragmas
11704 should apply to all subsequent compilations in the same compilation
11705 environment. Using GNAT, the current directory, possibly containing a
11706 @file{gnat.adc} file is the representation
11707 of a compilation environment. For more information on the
11708 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11710 Second, in compilation mode, if @code{gnatchop}
11711 is given a file that starts with
11712 configuration pragmas, and contains one or more units, then these
11713 configuration pragmas are prepended to each of the chopped files. This
11714 behavior provides the required behavior described in the RM for the
11715 actions to be taken on compiling such a file, namely that the pragmas
11716 apply to all units in the compilation, but not to subsequently compiled
11717 units.
11719 Finally, if configuration pragmas appear between units, they are appended
11720 to the previous unit. This results in the previous unit being illegal,
11721 since the compiler does not accept configuration pragmas that follow
11722 a unit. This provides the required RM behavior that forbids configuration
11723 pragmas other than those preceding the first compilation unit of a
11724 compilation.
11726 For most purposes, @code{gnatchop} will be used in default mode. The
11727 compilation mode described above is used only if you need exactly
11728 accurate behavior with respect to compilations, and you have files
11729 that contain multiple units and configuration pragmas. In this
11730 circumstance the use of @code{gnatchop} with the compilation mode
11731 switch provides the required behavior, and is for example the mode
11732 in which GNAT processes the ACVC tests.
11734 @node Command Line for gnatchop
11735 @section Command Line for @code{gnatchop}
11737 @noindent
11738 The @code{gnatchop} command has the form:
11740 @smallexample
11741 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11742 @c      @ovar{directory}
11743 @c Expanding @ovar macro inline (explanation in macro def comments)
11744 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11745       @r{[}@var{directory}@r{]}
11746 @end smallexample
11748 @noindent
11749 The only required argument is the file name of the file to be chopped.
11750 There are no restrictions on the form of this file name. The file itself
11751 contains one or more Ada units, in normal GNAT format, concatenated
11752 together. As shown, more than one file may be presented to be chopped.
11754 When run in default mode, @code{gnatchop} generates one output file in
11755 the current directory for each unit in each of the files.
11757 @var{directory}, if specified, gives the name of the directory to which
11758 the output files will be written. If it is not specified, all files are
11759 written to the current directory.
11761 For example, given a
11762 file called @file{hellofiles} containing
11764 @smallexample @c ada
11765 @group
11766 @cartouche
11767 procedure hello;
11769 with Text_IO; use Text_IO;
11770 procedure hello is
11771 begin
11772    Put_Line ("Hello");
11773 end hello;
11774 @end cartouche
11775 @end group
11776 @end smallexample
11778 @noindent
11779 the command
11781 @smallexample
11782 $ gnatchop ^hellofiles^HELLOFILES.^
11783 @end smallexample
11785 @noindent
11786 generates two files in the current directory, one called
11787 @file{hello.ads} containing the single line that is the procedure spec,
11788 and the other called @file{hello.adb} containing the remaining text. The
11789 original file is not affected. The generated files can be compiled in
11790 the normal manner.
11792 @noindent
11793 When gnatchop is invoked on a file that is empty or that contains only empty
11794 lines and/or comments, gnatchop will not fail, but will not produce any
11795 new sources.
11797 For example, given a
11798 file called @file{toto.txt} containing
11800 @smallexample @c ada
11801 @group
11802 @cartouche
11803 --  Just a comment
11804 @end cartouche
11805 @end group
11806 @end smallexample
11808 @noindent
11809 the command
11811 @smallexample
11812 $ gnatchop ^toto.txt^TOT.TXT^
11813 @end smallexample
11815 @noindent
11816 will not produce any new file and will result in the following warnings:
11818 @smallexample
11819 toto.txt:1:01: warning: empty file, contains no compilation units
11820 no compilation units found
11821 no source files written
11822 @end smallexample
11824 @node Switches for gnatchop
11825 @section Switches for @code{gnatchop}
11827 @noindent
11828 @command{gnatchop} recognizes the following switches:
11830 @table @option
11831 @c !sort!
11833 @item --version
11834 @cindex @option{--version} @command{gnatchop}
11835 Display Copyright and version, then exit disregarding all other options.
11837 @item --help
11838 @cindex @option{--help} @command{gnatchop}
11839 If @option{--version} was not used, display usage, then exit disregarding
11840 all other options.
11842 @item ^-c^/COMPILATION^
11843 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11844 Causes @code{gnatchop} to operate in compilation mode, in which
11845 configuration pragmas are handled according to strict RM rules. See
11846 previous section for a full description of this mode.
11848 @ifclear vms
11849 @item -gnat@var{xxx}
11850 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11851 used to parse the given file. Not all @var{xxx} options make sense,
11852 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11853 process a source file that uses Latin-2 coding for identifiers.
11854 @end ifclear
11856 @item ^-h^/HELP^
11857 Causes @code{gnatchop} to generate a brief help summary to the standard
11858 output file showing usage information.
11860 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11861 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11862 Limit generated file names to the specified number @code{mm}
11863 of characters.
11864 This is useful if the
11865 resulting set of files is required to be interoperable with systems
11866 which limit the length of file names.
11867 @ifset vms
11868 If no value is given, or
11869 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11870 a default of 39, suitable for OpenVMS Alpha
11871 Systems, is assumed
11872 @end ifset
11873 @ifclear vms
11874 No space is allowed between the @option{-k} and the numeric value. The numeric
11875 value may be omitted in which case a default of @option{-k8},
11876 suitable for use
11877 with DOS-like file systems, is used. If no @option{-k} switch
11878 is present then
11879 there is no limit on the length of file names.
11880 @end ifclear
11882 @item ^-p^/PRESERVE^
11883 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11884 Causes the file ^modification^creation^ time stamp of the input file to be
11885 preserved and used for the time stamp of the output file(s). This may be
11886 useful for preserving coherency of time stamps in an environment where
11887 @code{gnatchop} is used as part of a standard build process.
11889 @item ^-q^/QUIET^
11890 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11891 Causes output of informational messages indicating the set of generated
11892 files to be suppressed. Warnings and error messages are unaffected.
11894 @item ^-r^/REFERENCE^
11895 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11896 @findex Source_Reference
11897 Generate @code{Source_Reference} pragmas. Use this switch if the output
11898 files are regarded as temporary and development is to be done in terms
11899 of the original unchopped file. This switch causes
11900 @code{Source_Reference} pragmas to be inserted into each of the
11901 generated files to refers back to the original file name and line number.
11902 The result is that all error messages refer back to the original
11903 unchopped file.
11904 In addition, the debugging information placed into the object file (when
11905 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11906 specified)
11907 also refers back to this original file so that tools like profilers and
11908 debuggers will give information in terms of the original unchopped file.
11910 If the original file to be chopped itself contains
11911 a @code{Source_Reference}
11912 pragma referencing a third file, then gnatchop respects
11913 this pragma, and the generated @code{Source_Reference} pragmas
11914 in the chopped file refer to the original file, with appropriate
11915 line numbers. This is particularly useful when @code{gnatchop}
11916 is used in conjunction with @code{gnatprep} to compile files that
11917 contain preprocessing statements and multiple units.
11919 @item ^-v^/VERBOSE^
11920 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11921 Causes @code{gnatchop} to operate in verbose mode. The version
11922 number and copyright notice are output, as well as exact copies of
11923 the gnat1 commands spawned to obtain the chop control information.
11925 @item ^-w^/OVERWRITE^
11926 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11927 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11928 fatal error if there is already a file with the same name as a
11929 file it would otherwise output, in other words if the files to be
11930 chopped contain duplicated units. This switch bypasses this
11931 check, and causes all but the last instance of such duplicated
11932 units to be skipped.
11934 @ifclear vms
11935 @item --GCC=@var{xxxx}
11936 @cindex @option{--GCC=} (@code{gnatchop})
11937 Specify the path of the GNAT parser to be used. When this switch is used,
11938 no attempt is made to add the prefix to the GNAT parser executable.
11939 @end ifclear
11940 @end table
11942 @node Examples of gnatchop Usage
11943 @section Examples of @code{gnatchop} Usage
11945 @table @code
11946 @ifset vms
11947 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11948 @end ifset
11949 @ifclear vms
11950 @item gnatchop -w hello_s.ada prerelease/files
11951 @end ifclear
11953 Chops the source file @file{hello_s.ada}. The output files will be
11954 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11955 overwriting any
11956 files with matching names in that directory (no files in the current
11957 directory are modified).
11959 @item gnatchop ^archive^ARCHIVE.^
11960 Chops the source file @file{^archive^ARCHIVE.^}
11961 into the current directory. One
11962 useful application of @code{gnatchop} is in sending sets of sources
11963 around, for example in email messages. The required sources are simply
11964 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11965 command), and then
11966 @command{gnatchop} is used at the other end to reconstitute the original
11967 file names.
11969 @item gnatchop file1 file2 file3 direc
11970 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11971 the resulting files in the directory @file{direc}. Note that if any units
11972 occur more than once anywhere within this set of files, an error message
11973 is generated, and no files are written. To override this check, use the
11974 @option{^-w^/OVERWRITE^} switch,
11975 in which case the last occurrence in the last file will
11976 be the one that is output, and earlier duplicate occurrences for a given
11977 unit will be skipped.
11978 @end table
11980 @node Configuration Pragmas
11981 @chapter Configuration Pragmas
11982 @cindex Configuration pragmas
11983 @cindex Pragmas, configuration
11985 @noindent
11986 Configuration pragmas include those pragmas described as
11987 such in the Ada Reference Manual, as well as
11988 implementation-dependent pragmas that are configuration pragmas.
11989 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11990 for details on these additional GNAT-specific configuration pragmas.
11991 Most notably, the pragma @code{Source_File_Name}, which allows
11992 specifying non-default names for source files, is a configuration
11993 pragma. The following is a complete list of configuration pragmas
11994 recognized by GNAT:
11996 @smallexample
11997    Ada_83
11998    Ada_95
11999    Ada_05
12000    Ada_2005
12001    Ada_12
12002    Ada_2012
12003    Annotate
12004    Assertion_Policy
12005    Assume_No_Invalid_Values
12006    C_Pass_By_Copy
12007    Check_Name
12008    Check_Policy
12009    Compile_Time_Error
12010    Compile_Time_Warning
12011    Compiler_Unit
12012    Component_Alignment
12013    Convention_Identifier
12014    Debug_Policy
12015    Detect_Blocking
12016    Default_Storage_Pool
12017    Discard_Names
12018    Elaboration_Checks
12019    Eliminate
12020    Extend_System
12021    Extensions_Allowed
12022    External_Name_Casing
12023    Fast_Math
12024    Favor_Top_Level
12025    Float_Representation
12026    Implicit_Packing
12027    Initialize_Scalars
12028    Interrupt_State
12029    License
12030    Locking_Policy
12031    Long_Float
12032    No_Run_Time
12033    No_Strict_Aliasing
12034    Normalize_Scalars
12035    Optimize_Alignment
12036    Persistent_BSS
12037    Polling
12038    Priority_Specific_Dispatching
12039    Profile
12040    Profile_Warnings
12041    Propagate_Exceptions
12042    Queuing_Policy
12043    Ravenscar
12044    Restricted_Run_Time
12045    Restrictions
12046    Restrictions_Warnings
12047    Reviewable
12048    Short_Circuit_And_Or
12049    Source_File_Name
12050    Source_File_Name_Project
12051    Style_Checks
12052    Suppress
12053    Suppress_Exception_Locations
12054    Task_Dispatching_Policy
12055    Universal_Data
12056    Unsuppress
12057    Use_VADS_Size
12058    Validity_Checks
12059    Warnings
12060    Wide_Character_Encoding
12062 @end smallexample
12064 @menu
12065 * Handling of Configuration Pragmas::
12066 * The Configuration Pragmas Files::
12067 @end menu
12069 @node Handling of Configuration Pragmas
12070 @section Handling of Configuration Pragmas
12072 Configuration pragmas may either appear at the start of a compilation
12073 unit, or they can appear in a configuration pragma file to apply to
12074 all compilations performed in a given compilation environment.
12076 GNAT also provides the @code{gnatchop} utility to provide an automatic
12077 way to handle configuration pragmas following the semantics for
12078 compilations (that is, files with multiple units), described in the RM.
12079 See @ref{Operating gnatchop in Compilation Mode} for details.
12080 However, for most purposes, it will be more convenient to edit the
12081 @file{gnat.adc} file that contains configuration pragmas directly,
12082 as described in the following section.
12084 In the case of @code{Restrictions} pragmas appearing as configuration
12085 pragmas in individual compilation units, the exact handling depends on
12086 the type of restriction.
12088 Restrictions that require partition-wide consistency (like
12089 @code{No_Tasking}) are
12090 recognized wherever they appear
12091 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12092 unit. This makes sense since the binder will in any case insist on seeing
12093 consistent use, so any unit not conforming to any restrictions that are
12094 anywhere in the partition will be rejected, and you might as well find
12095 that out at compile time rather than at bind time.
12097 For restrictions that do not require partition-wide consistency, e.g.
12098 SPARK or No_Implementation_Attributes, in general the restriction applies
12099 only to the unit in which the pragma appears, and not to any other units.
12101 The exception is No_Elaboration_Code which always applies to the entire
12102 object file from a compilation, i.e. to the body, spec, and all subunits.
12103 This restriction can be specified in a configuration pragma file, or it
12104 can be on the body and/or the spec (in eithe case it applies to all the
12105 relevant units). It can appear on a subunit only if it has previously
12106 appeared in the body of spec.
12108 @node The Configuration Pragmas Files
12109 @section The Configuration Pragmas Files
12110 @cindex @file{gnat.adc}
12112 @noindent
12113 In GNAT a compilation environment is defined by the current
12114 directory at the time that a compile command is given. This current
12115 directory is searched for a file whose name is @file{gnat.adc}. If
12116 this file is present, it is expected to contain one or more
12117 configuration pragmas that will be applied to the current compilation.
12118 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12119 considered.
12121 Configuration pragmas may be entered into the @file{gnat.adc} file
12122 either by running @code{gnatchop} on a source file that consists only of
12123 configuration pragmas, or more conveniently  by
12124 direct editing of the @file{gnat.adc} file, which is a standard format
12125 source file.
12127 In addition to @file{gnat.adc}, additional files containing configuration
12128 pragmas may be applied to the current compilation using the switch
12129 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12130 contains only configuration pragmas. These configuration pragmas are
12131 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12132 is present and switch @option{-gnatA} is not used).
12134 It is allowed to specify several switches @option{-gnatec}, all of which
12135 will be taken into account.
12137 If you are using project file, a separate mechanism is provided using
12138 project attributes, see @ref{Specifying Configuration Pragmas} for more
12139 details.
12141 @ifset vms
12142 Of special interest to GNAT OpenVMS Alpha is the following
12143 configuration pragma:
12145 @smallexample @c ada
12146 @cartouche
12147 pragma Extend_System (Aux_DEC);
12148 @end cartouche
12149 @end smallexample
12151 @noindent
12152 In the presence of this pragma, GNAT adds to the definition of the
12153 predefined package SYSTEM all the additional types and subprograms that are
12154 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12155 @end ifset
12157 @node Handling Arbitrary File Naming Conventions Using gnatname
12158 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
12159 @cindex Arbitrary File Naming Conventions
12161 @menu
12162 * Arbitrary File Naming Conventions::
12163 * Running gnatname::
12164 * Switches for gnatname::
12165 * Examples of gnatname Usage::
12166 @end menu
12168 @node Arbitrary File Naming Conventions
12169 @section Arbitrary File Naming Conventions
12171 @noindent
12172 The GNAT compiler must be able to know the source file name of a compilation
12173 unit.  When using the standard GNAT default file naming conventions
12174 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12175 does not need additional information.
12177 @noindent
12178 When the source file names do not follow the standard GNAT default file naming
12179 conventions, the GNAT compiler must be given additional information through
12180 a configuration pragmas file (@pxref{Configuration Pragmas})
12181 or a project file.
12182 When the non-standard file naming conventions are well-defined,
12183 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12184 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12185 if the file naming conventions are irregular or arbitrary, a number
12186 of pragma @code{Source_File_Name} for individual compilation units
12187 must be defined.
12188 To help maintain the correspondence between compilation unit names and
12189 source file names within the compiler,
12190 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12191 set of files.
12193 @node Running gnatname
12194 @section Running @code{gnatname}
12196 @noindent
12197 The usual form of the @code{gnatname} command is
12199 @smallexample
12200 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12201 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12202 @c Expanding @ovar macro inline (explanation in macro def comments)
12203 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12204       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12205 @end smallexample
12207 @noindent
12208 All of the arguments are optional. If invoked without any argument,
12209 @code{gnatname} will display its usage.
12211 @noindent
12212 When used with at least one naming pattern, @code{gnatname} will attempt to
12213 find all the compilation units in files that follow at least one of the
12214 naming patterns. To find these compilation units,
12215 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12216 regular files.
12218 @noindent
12219 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12220 Each Naming Pattern is enclosed between double quotes (or single
12221 quotes on Windows).
12222 A Naming Pattern is a regular expression similar to the wildcard patterns
12223 used in file names by the Unix shells or the DOS prompt.
12225 @noindent
12226 @code{gnatname} may be called with several sections of directories/patterns.
12227 Sections are separated by switch @code{--and}. In each section, there must be
12228 at least one pattern. If no directory is specified in a section, the current
12229 directory (or the project directory is @code{-P} is used) is implied.
12230 The options other that the directory switches and the patterns apply globally
12231 even if they are in different sections.
12233 @noindent
12234 Examples of Naming Patterns are
12236 @smallexample
12237    "*.[12].ada"
12238    "*.ad[sb]*"
12239    "body_*"    "spec_*"
12240 @end smallexample
12242 @noindent
12243 For a more complete description of the syntax of Naming Patterns,
12244 see the second kind of regular expressions described in @file{g-regexp.ads}
12245 (the ``Glob'' regular expressions).
12247 @noindent
12248 When invoked with no switch @code{-P}, @code{gnatname} will create a
12249 configuration pragmas file @file{gnat.adc} in the current working directory,
12250 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12251 unit.
12253 @node Switches for gnatname
12254 @section Switches for @code{gnatname}
12256 @noindent
12257 Switches for @code{gnatname} must precede any specified Naming Pattern.
12259 @noindent
12260 You may specify any of the following switches to @code{gnatname}:
12262 @table @option
12263 @c !sort!
12265 @item --version
12266 @cindex @option{--version} @command{gnatname}
12267 Display Copyright and version, then exit disregarding all other options.
12269 @item --help
12270 @cindex @option{--help} @command{gnatname}
12271 If @option{--version} was not used, display usage, then exit disregarding
12272 all other options.
12274 @item --and
12275 Start another section of directories/patterns.
12277 @item ^-c^/CONFIG_FILE=^@file{file}
12278 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12279 Create a configuration pragmas file @file{file} (instead of the default
12280 @file{gnat.adc}).
12281 @ifclear vms
12282 There may be zero, one or more space between @option{-c} and
12283 @file{file}.
12284 @end ifclear
12285 @file{file} may include directory information. @file{file} must be
12286 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12287 When a switch @option{^-c^/CONFIG_FILE^} is
12288 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12290 @item ^-d^/SOURCE_DIRS=^@file{dir}
12291 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12292 Look for source files in directory @file{dir}. There may be zero, one or more
12293 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12294 When a switch @option{^-d^/SOURCE_DIRS^}
12295 is specified, the current working directory will not be searched for source
12296 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12297 or @option{^-D^/DIR_FILES^} switch.
12298 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12299 If @file{dir} is a relative path, it is relative to the directory of
12300 the configuration pragmas file specified with switch
12301 @option{^-c^/CONFIG_FILE^},
12302 or to the directory of the project file specified with switch
12303 @option{^-P^/PROJECT_FILE^} or,
12304 if neither switch @option{^-c^/CONFIG_FILE^}
12305 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12306 current working directory. The directory
12307 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12309 @item ^-D^/DIRS_FILE=^@file{file}
12310 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12311 Look for source files in all directories listed in text file @file{file}.
12312 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12313 and @file{file}.
12314 @file{file} must be an existing, readable text file.
12315 Each nonempty line in @file{file} must be a directory.
12316 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12317 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12318 @file{file}.
12320 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12321 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12322 Foreign patterns. Using this switch, it is possible to add sources of languages
12323 other than Ada to the list of sources of a project file.
12324 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12325 For example,
12326 @smallexample
12327 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12328 @end smallexample
12329 @noindent
12330 will look for Ada units in all files with the @file{.ada} extension,
12331 and will add to the list of file for project @file{prj.gpr} the C files
12332 with extension @file{.^c^C^}.
12334 @item ^-h^/HELP^
12335 @cindex @option{^-h^/HELP^} (@code{gnatname})
12336 Output usage (help) information. The output is written to @file{stdout}.
12338 @item ^-P^/PROJECT_FILE=^@file{proj}
12339 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12340 Create or update project file @file{proj}. There may be zero, one or more space
12341 between @option{-P} and @file{proj}. @file{proj} may include directory
12342 information. @file{proj} must be writable.
12343 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12344 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12345 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12347 @item ^-v^/VERBOSE^
12348 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12349 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12350 This includes name of the file written, the name of the directories to search
12351 and, for each file in those directories whose name matches at least one of
12352 the Naming Patterns, an indication of whether the file contains a unit,
12353 and if so the name of the unit.
12355 @item ^-v -v^/VERBOSE /VERBOSE^
12356 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12357 Very Verbose mode. In addition to the output produced in verbose mode,
12358 for each file in the searched directories whose name matches none of
12359 the Naming Patterns, an indication is given that there is no match.
12361 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12362 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12363 Excluded patterns. Using this switch, it is possible to exclude some files
12364 that would match the name patterns. For example,
12365 @smallexample
12366 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12367 @end smallexample
12368 @noindent
12369 will look for Ada units in all files with the @file{.ada} extension,
12370 except those whose names end with @file{_nt.ada}.
12372 @end table
12374 @node Examples of gnatname Usage
12375 @section Examples of @code{gnatname} Usage
12377 @ifset vms
12378 @smallexample
12379 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12380 @end smallexample
12381 @end ifset
12383 @ifclear vms
12384 @smallexample
12385 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12386 @end smallexample
12387 @end ifclear
12389 @noindent
12390 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12391 and be writable. In addition, the directory
12392 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12393 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12395 @ifclear vms
12396 Note the optional spaces after @option{-c} and @option{-d}.
12397 @end ifclear
12399 @smallexample
12400 @ifclear vms
12401 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12402   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12403 @end ifclear
12404 @ifset vms
12405 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12406   /EXCLUDED_PATTERN=*_nt_body.ada
12407   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12408   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12409 @end ifset
12410 @end smallexample
12412 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12413 even in conjunction with one or several switches
12414 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12415 are used in this example.
12417 @c *****************************************
12418 @c * G N A T  P r o j e c t  M a n a g e r *
12419 @c *****************************************
12421 @c ------ macros for projects.texi
12422 @c These macros are needed when building the gprbuild documentation, but
12423 @c should have no effect in the gnat user's guide
12425 @macro CODESAMPLE{TXT}
12426 @smallexample
12427 @group
12428 \TXT\
12429 @end group
12430 @end smallexample
12431 @end macro
12433 @macro PROJECTFILE{TXT}
12434 @CODESAMPLE{\TXT\}
12435 @end macro
12437 @c simulates a newline when in a @CODESAMPLE
12438 @macro NL{}
12439 @end macro
12441 @macro TIP{TXT}
12442 @quotation
12443 @noindent
12444 \TXT\
12445 @end quotation
12446 @end macro
12448 @macro TIPHTML{TXT}
12449 \TXT\
12450 @end macro
12452 @macro IMPORTANT{TXT}
12453 @quotation
12454 @noindent
12455 \TXT\
12456 @end quotation
12458 @end macro
12460 @macro NOTE{TXT}
12461 @quotation
12462 @noindent
12463 \TXT\
12464 @end quotation
12465 @end macro
12467 @include projects.texi
12469 @c *****************************************
12470 @c * Cross-referencing tools
12471 @c *****************************************
12473 @node The Cross-Referencing Tools gnatxref and gnatfind
12474 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12475 @findex gnatxref
12476 @findex gnatfind
12478 @noindent
12479 The compiler generates cross-referencing information (unless
12480 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12481 This information indicates where in the source each entity is declared and
12482 referenced. Note that entities in package Standard are not included, but
12483 entities in all other predefined units are included in the output.
12485 Before using any of these two tools, you need to compile successfully your
12486 application, so that GNAT gets a chance to generate the cross-referencing
12487 information.
12489 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12490 information to provide the user with the capability to easily locate the
12491 declaration and references to an entity. These tools are quite similar,
12492 the difference being that @code{gnatfind} is intended for locating
12493 definitions and/or references to a specified entity or entities, whereas
12494 @code{gnatxref} is oriented to generating a full report of all
12495 cross-references.
12497 To use these tools, you must not compile your application using the
12498 @option{-gnatx} switch on the @command{gnatmake} command line
12499 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12500 information will not be generated.
12502 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12503 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12505 @menu
12506 * Switches for gnatxref::
12507 * Switches for gnatfind::
12508 * Project Files for gnatxref and gnatfind::
12509 * Regular Expressions in gnatfind and gnatxref::
12510 * Examples of gnatxref Usage::
12511 * Examples of gnatfind Usage::
12512 @end menu
12514 @node Switches for gnatxref
12515 @section @code{gnatxref} Switches
12517 @noindent
12518 The command invocation for @code{gnatxref} is:
12519 @smallexample
12520 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12521 @c Expanding @ovar macro inline (explanation in macro def comments)
12522 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12523 @end smallexample
12525 @noindent
12526 where
12528 @table @var
12529 @item sourcefile1
12530 @itemx sourcefile2
12531 identifies the source files for which a report is to be generated. The
12532 ``with''ed units will be processed too. You must provide at least one file.
12534 These file names are considered to be regular expressions, so for instance
12535 specifying @file{source*.adb} is the same as giving every file in the current
12536 directory whose name starts with @file{source} and whose extension is
12537 @file{adb}.
12539 You shouldn't specify any directory name, just base names. @command{gnatxref}
12540 and @command{gnatfind} will be able to locate these files by themselves using
12541 the source path. If you specify directories, no result is produced.
12543 @end table
12545 @noindent
12546 The switches can be:
12547 @table @option
12548 @c !sort!
12549 @item --version
12550 @cindex @option{--version} @command{gnatxref}
12551 Display Copyright and version, then exit disregarding all other options.
12553 @item --help
12554 @cindex @option{--help} @command{gnatxref}
12555 If @option{--version} was not used, display usage, then exit disregarding
12556 all other options.
12558 @item ^-a^/ALL_FILES^
12559 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12560 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12561 the read-only files found in the library search path. Otherwise, these files
12562 will be ignored. This option can be used to protect Gnat sources or your own
12563 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12564 much faster, and their output much smaller. Read-only here refers to access
12565 or permissions status in the file system for the current user.
12567 @item -aIDIR
12568 @cindex @option{-aIDIR} (@command{gnatxref})
12569 When looking for source files also look in directory DIR. The order in which
12570 source file search is undertaken is the same as for @command{gnatmake}.
12572 @item -aODIR
12573 @cindex @option{-aODIR} (@command{gnatxref})
12574 When searching for library and object files, look in directory
12575 DIR. The order in which library files are searched is the same as for
12576 @command{gnatmake}.
12578 @item -nostdinc
12579 @cindex @option{-nostdinc} (@command{gnatxref})
12580 Do not look for sources in the system default directory.
12582 @item -nostdlib
12583 @cindex @option{-nostdlib} (@command{gnatxref})
12584 Do not look for library files in the system default directory.
12586 @item --ext=@var{extension}
12587 @cindex @option{--ext} (@command{gnatxref})
12588 Specify an alternate ali file extension. The default is @code{ali} and other
12589 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12590 switch. Note that if this switch overrides the default, which means that only
12591 the new extension will be considered.
12593 @item --RTS=@var{rts-path}
12594 @cindex @option{--RTS} (@command{gnatxref})
12595 Specifies the default location of the runtime library. Same meaning as the
12596 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12598 @item ^-d^/DERIVED_TYPES^
12599 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12600 If this switch is set @code{gnatxref} will output the parent type
12601 reference for each matching derived types.
12603 @item ^-f^/FULL_PATHNAME^
12604 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12605 If this switch is set, the output file names will be preceded by their
12606 directory (if the file was found in the search path). If this switch is
12607 not set, the directory will not be printed.
12609 @item ^-g^/IGNORE_LOCALS^
12610 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12611 If this switch is set, information is output only for library-level
12612 entities, ignoring local entities. The use of this switch may accelerate
12613 @code{gnatfind} and @code{gnatxref}.
12615 @item -IDIR
12616 @cindex @option{-IDIR} (@command{gnatxref})
12617 Equivalent to @samp{-aODIR -aIDIR}.
12619 @item -pFILE
12620 @cindex @option{-pFILE} (@command{gnatxref})
12621 Specify a project file to use @xref{GNAT Project Manager}.
12622 If you need to use the @file{.gpr}
12623 project files, you should use gnatxref through the GNAT driver
12624 (@command{gnat xref -Pproject}).
12626 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12627 project file in the current directory.
12629 If a project file is either specified or found by the tools, then the content
12630 of the source directory and object directory lines are added as if they
12631 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12632 and @samp{^-aO^OBJECT_SEARCH^}.
12633 @item ^-u^/UNUSED^
12634 Output only unused symbols. This may be really useful if you give your
12635 main compilation unit on the command line, as @code{gnatxref} will then
12636 display every unused entity and 'with'ed package.
12638 @ifclear vms
12639 @item -v
12640 Instead of producing the default output, @code{gnatxref} will generate a
12641 @file{tags} file that can be used by vi. For examples how to use this
12642 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12643 to the standard output, thus you will have to redirect it to a file.
12644 @end ifclear
12646 @end table
12648 @noindent
12649 All these switches may be in any order on the command line, and may even
12650 appear after the file names. They need not be separated by spaces, thus
12651 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12652 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12654 @node Switches for gnatfind
12655 @section @code{gnatfind} Switches
12657 @noindent
12658 The command line for @code{gnatfind} is:
12660 @smallexample
12661 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12662 @c       @r{[}@var{file1} @var{file2} @dots{}]
12663 @c Expanding @ovar macro inline (explanation in macro def comments)
12664 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12665       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12666 @end smallexample
12668 @noindent
12669 where
12671 @table @var
12672 @item pattern
12673 An entity will be output only if it matches the regular expression found
12674 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12676 Omitting the pattern is equivalent to specifying @samp{*}, which
12677 will match any entity. Note that if you do not provide a pattern, you
12678 have to provide both a sourcefile and a line.
12680 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12681 for matching purposes. At the current time there is no support for
12682 8-bit codes other than Latin-1, or for wide characters in identifiers.
12684 @item sourcefile
12685 @code{gnatfind} will look for references, bodies or declarations
12686 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12687 and column @var{column}. See @ref{Examples of gnatfind Usage}
12688 for syntax examples.
12690 @item line
12691 is a decimal integer identifying the line number containing
12692 the reference to the entity (or entities) to be located.
12694 @item column
12695 is a decimal integer identifying the exact location on the
12696 line of the first character of the identifier for the
12697 entity reference. Columns are numbered from 1.
12699 @item file1 file2 @dots{}
12700 The search will be restricted to these source files. If none are given, then
12701 the search will be done for every library file in the search path.
12702 These file must appear only after the pattern or sourcefile.
12704 These file names are considered to be regular expressions, so for instance
12705 specifying @file{source*.adb} is the same as giving every file in the current
12706 directory whose name starts with @file{source} and whose extension is
12707 @file{adb}.
12709 The location of the spec of the entity will always be displayed, even if it
12710 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12711 occurrences of the entity in the separate units of the ones given on the
12712 command line will also be displayed.
12714 Note that if you specify at least one file in this part, @code{gnatfind} may
12715 sometimes not be able to find the body of the subprograms.
12717 @end table
12719 @noindent
12720 At least one of 'sourcefile' or 'pattern' has to be present on
12721 the command line.
12723 The following switches are available:
12724 @table @option
12725 @c !sort!
12727 @cindex @option{--version} @command{gnatfind}
12728 Display Copyright and version, then exit disregarding all other options.
12730 @item --help
12731 @cindex @option{--help} @command{gnatfind}
12732 If @option{--version} was not used, display usage, then exit disregarding
12733 all other options.
12735 @item ^-a^/ALL_FILES^
12736 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12737 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12738 the read-only files found in the library search path. Otherwise, these files
12739 will be ignored. This option can be used to protect Gnat sources or your own
12740 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12741 much faster, and their output much smaller. Read-only here refers to access
12742 or permission status in the file system for the current user.
12744 @item -aIDIR
12745 @cindex @option{-aIDIR} (@command{gnatfind})
12746 When looking for source files also look in directory DIR. The order in which
12747 source file search is undertaken is the same as for @command{gnatmake}.
12749 @item -aODIR
12750 @cindex @option{-aODIR} (@command{gnatfind})
12751 When searching for library and object files, look in directory
12752 DIR. The order in which library files are searched is the same as for
12753 @command{gnatmake}.
12755 @item -nostdinc
12756 @cindex @option{-nostdinc} (@command{gnatfind})
12757 Do not look for sources in the system default directory.
12759 @item -nostdlib
12760 @cindex @option{-nostdlib} (@command{gnatfind})
12761 Do not look for library files in the system default directory.
12763 @item --ext=@var{extension}
12764 @cindex @option{--ext} (@command{gnatfind})
12765 Specify an alternate ali file extension. The default is @code{ali} and other
12766 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12767 switch. Note that if this switch overrides the default, which means that only
12768 the new extension will be considered.
12770 @item --RTS=@var{rts-path}
12771 @cindex @option{--RTS} (@command{gnatfind})
12772 Specifies the default location of the runtime library. Same meaning as the
12773 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12775 @item ^-d^/DERIVED_TYPE_INFORMATION^
12776 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12777 If this switch is set, then @code{gnatfind} will output the parent type
12778 reference for each matching derived types.
12780 @item ^-e^/EXPRESSIONS^
12781 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12782 By default, @code{gnatfind} accept the simple regular expression set for
12783 @samp{pattern}. If this switch is set, then the pattern will be
12784 considered as full Unix-style regular expression.
12786 @item ^-f^/FULL_PATHNAME^
12787 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12788 If this switch is set, the output file names will be preceded by their
12789 directory (if the file was found in the search path). If this switch is
12790 not set, the directory will not be printed.
12792 @item ^-g^/IGNORE_LOCALS^
12793 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12794 If this switch is set, information is output only for library-level
12795 entities, ignoring local entities. The use of this switch may accelerate
12796 @code{gnatfind} and @code{gnatxref}.
12798 @item -IDIR
12799 @cindex @option{-IDIR} (@command{gnatfind})
12800 Equivalent to @samp{-aODIR -aIDIR}.
12802 @item -pFILE
12803 @cindex @option{-pFILE} (@command{gnatfind})
12804 Specify a project file (@pxref{GNAT Project Manager}) to use.
12805 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12806 project file in the current directory.
12808 If a project file is either specified or found by the tools, then the content
12809 of the source directory and object directory lines are added as if they
12810 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12811 @samp{^-aO^/OBJECT_SEARCH^}.
12813 @item ^-r^/REFERENCES^
12814 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12815 By default, @code{gnatfind} will output only the information about the
12816 declaration, body or type completion of the entities. If this switch is
12817 set, the @code{gnatfind} will locate every reference to the entities in
12818 the files specified on the command line (or in every file in the search
12819 path if no file is given on the command line).
12821 @item ^-s^/PRINT_LINES^
12822 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12823 If this switch is set, then @code{gnatfind} will output the content
12824 of the Ada source file lines were the entity was found.
12826 @item ^-t^/TYPE_HIERARCHY^
12827 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12828 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12829 the specified type. It act like -d option but recursively from parent
12830 type to parent type. When this switch is set it is not possible to
12831 specify more than one file.
12833 @end table
12835 @noindent
12836 All these switches may be in any order on the command line, and may even
12837 appear after the file names. They need not be separated by spaces, thus
12838 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12839 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12841 As stated previously, gnatfind will search in every directory in the
12842 search path. You can force it to look only in the current directory if
12843 you specify @code{*} at the end of the command line.
12845 @node Project Files for gnatxref and gnatfind
12846 @section Project Files for @command{gnatxref} and @command{gnatfind}
12848 @noindent
12849 Project files allow a programmer to specify how to compile its
12850 application, where to find sources, etc.  These files are used
12851 @ifclear vms
12852 primarily by GPS, but they can also be used
12853 @end ifclear
12854 by the two tools
12855 @code{gnatxref} and @code{gnatfind}.
12857 A project file name must end with @file{.gpr}. If a single one is
12858 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12859 extract the information from it. If multiple project files are found, none of
12860 them is read, and you have to use the @samp{-p} switch to specify the one
12861 you want to use.
12863 The following lines can be included, even though most of them have default
12864 values which can be used in most cases.
12865 The lines can be entered in any order in the file.
12866 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12867 each line. If you have multiple instances, only the last one is taken into
12868 account.
12870 @table @code
12871 @item src_dir=DIR
12872 [default: @code{"^./^[]^"}]
12873 specifies a directory where to look for source files. Multiple @code{src_dir}
12874 lines can be specified and they will be searched in the order they
12875 are specified.
12877 @item obj_dir=DIR
12878 [default: @code{"^./^[]^"}]
12879 specifies a directory where to look for object and library files. Multiple
12880 @code{obj_dir} lines can be specified, and they will be searched in the order
12881 they are specified
12883 @item comp_opt=SWITCHES
12884 [default: @code{""}]
12885 creates a variable which can be referred to subsequently by using
12886 the @code{$@{comp_opt@}} notation. This is intended to store the default
12887 switches given to @command{gnatmake} and @command{gcc}.
12889 @item bind_opt=SWITCHES
12890 [default: @code{""}]
12891 creates a variable which can be referred to subsequently by using
12892 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12893 switches given to @command{gnatbind}.
12895 @item link_opt=SWITCHES
12896 [default: @code{""}]
12897 creates a variable which can be referred to subsequently by using
12898 the @samp{$@{link_opt@}} notation. This is intended to store the default
12899 switches given to @command{gnatlink}.
12901 @item main=EXECUTABLE
12902 [default: @code{""}]
12903 specifies the name of the executable for the application. This variable can
12904 be referred to in the following lines by using the @samp{$@{main@}} notation.
12906 @ifset vms
12907 @item comp_cmd=COMMAND
12908 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12909 @end ifset
12910 @ifclear vms
12911 @item comp_cmd=COMMAND
12912 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12913 @end ifclear
12914 specifies the command used to compile a single file in the application.
12916 @ifset vms
12917 @item make_cmd=COMMAND
12918 [default: @code{"GNAT MAKE $@{main@}
12919 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12920 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12921 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12922 @end ifset
12923 @ifclear vms
12924 @item make_cmd=COMMAND
12925 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12926 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12927 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12928 @end ifclear
12929 specifies the command used to recompile the whole application.
12931 @item run_cmd=COMMAND
12932 [default: @code{"$@{main@}"}]
12933 specifies the command used to run the application.
12935 @item debug_cmd=COMMAND
12936 [default: @code{"gdb $@{main@}"}]
12937 specifies the command used to debug the application
12939 @end table
12941 @noindent
12942 @command{gnatxref} and @command{gnatfind} only take into account the
12943 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12945 @node Regular Expressions in gnatfind and gnatxref
12946 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12948 @noindent
12949 As specified in the section about @command{gnatfind}, the pattern can be a
12950 regular expression. Actually, there are to set of regular expressions
12951 which are recognized by the program:
12953 @table @code
12954 @item globbing patterns
12955 These are the most usual regular expression. They are the same that you
12956 generally used in a Unix shell command line, or in a DOS session.
12958 Here is a more formal grammar:
12959 @smallexample
12960 @group
12961 @iftex
12962 @leftskip=.5cm
12963 @end iftex
12964 regexp ::= term
12965 term   ::= elmt            -- matches elmt
12966 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12967 term   ::= *               -- any string of 0 or more characters
12968 term   ::= ?               -- matches any character
12969 term   ::= [char @{char@}]   -- matches any character listed
12970 term   ::= [char - char]   -- matches any character in range
12971 @end group
12972 @end smallexample
12974 @item full regular expression
12975 The second set of regular expressions is much more powerful. This is the
12976 type of regular expressions recognized by utilities such a @file{grep}.
12978 The following is the form of a regular expression, expressed in Ada
12979 reference manual style BNF is as follows
12981 @smallexample
12982 @iftex
12983 @leftskip=.5cm
12984 @end iftex
12985 @group
12986 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12988 term ::= item @{item@}       -- concatenation (item then item)
12990 item ::= elmt              -- match elmt
12991 item ::= elmt *            -- zero or more elmt's
12992 item ::= elmt +            -- one or more elmt's
12993 item ::= elmt ?            -- matches elmt or nothing
12994 @end group
12995 @group
12996 elmt ::= nschar            -- matches given character
12997 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12998 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12999 elmt ::= [char - char]     -- matches chars in given range
13000 elmt ::= \ char            -- matches given character
13001 elmt ::= .                 -- matches any single character
13002 elmt ::= ( regexp )        -- parens used for grouping
13004 char ::= any character, including special characters
13005 nschar ::= any character except ()[].*+?^^^
13006 @end group
13007 @end smallexample
13009 Following are a few examples:
13011 @table @samp
13012 @item abcde|fghi
13013 will match any of the two strings @samp{abcde} and @samp{fghi},
13015 @item abc*d
13016 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13017 @samp{abcccd}, and so on,
13019 @item [a-z]+
13020 will match any string which has only lowercase characters in it (and at
13021 least one character.
13023 @end table
13024 @end table
13026 @node Examples of gnatxref Usage
13027 @section Examples of @code{gnatxref} Usage
13029 @subsection General Usage
13031 @noindent
13032 For the following examples, we will consider the following units:
13034 @smallexample @c ada
13035 @group
13036 @cartouche
13037 main.ads:
13038 1: with Bar;
13039 2: package Main is
13040 3:     procedure Foo (B : in Integer);
13041 4:     C : Integer;
13042 5: private
13043 6:     D : Integer;
13044 7: end Main;
13046 main.adb:
13047 1: package body Main is
13048 2:     procedure Foo (B : in Integer) is
13049 3:     begin
13050 4:        C := B;
13051 5:        D := B;
13052 6:        Bar.Print (B);
13053 7:        Bar.Print (C);
13054 8:     end Foo;
13055 9: end Main;
13057 bar.ads:
13058 1: package Bar is
13059 2:     procedure Print (B : Integer);
13060 3: end bar;
13061 @end cartouche
13062 @end group
13063 @end smallexample
13065 @table @code
13067 @noindent
13068 The first thing to do is to recompile your application (for instance, in
13069 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13070 the cross-referencing information.
13071 You can then issue any of the following commands:
13073 @item gnatxref main.adb
13074 @code{gnatxref} generates cross-reference information for main.adb
13075 and every unit 'with'ed by main.adb.
13077 The output would be:
13078 @smallexample
13079 @iftex
13080 @leftskip=0cm
13081 @end iftex
13082 B                                                      Type: Integer
13083   Decl: bar.ads           2:22
13084 B                                                      Type: Integer
13085   Decl: main.ads          3:20
13086   Body: main.adb          2:20
13087   Ref:  main.adb          4:13     5:13     6:19
13088 Bar                                                    Type: Unit
13089   Decl: bar.ads           1:9
13090   Ref:  main.adb          6:8      7:8
13091        main.ads           1:6
13092 C                                                      Type: Integer
13093   Decl: main.ads          4:5
13094   Modi: main.adb          4:8
13095   Ref:  main.adb          7:19
13096 D                                                      Type: Integer
13097   Decl: main.ads          6:5
13098   Modi: main.adb          5:8
13099 Foo                                                    Type: Unit
13100   Decl: main.ads          3:15
13101   Body: main.adb          2:15
13102 Main                                                    Type: Unit
13103   Decl: main.ads          2:9
13104   Body: main.adb          1:14
13105 Print                                                   Type: Unit
13106   Decl: bar.ads           2:15
13107   Ref:  main.adb          6:12     7:12
13108 @end smallexample
13110 @noindent
13111 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13112 its body is in main.adb, line 1, column 14 and is not referenced any where.
13114 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13115 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13117 @item gnatxref package1.adb package2.ads
13118 @code{gnatxref} will generates cross-reference information for
13119 package1.adb, package2.ads and any other package 'with'ed by any
13120 of these.
13122 @end table
13124 @ifclear vms
13125 @subsection Using gnatxref with vi
13127 @code{gnatxref} can generate a tags file output, which can be used
13128 directly from @command{vi}. Note that the standard version of @command{vi}
13129 will not work properly with overloaded symbols. Consider using another
13130 free implementation of @command{vi}, such as @command{vim}.
13132 @smallexample
13133 $ gnatxref -v gnatfind.adb > tags
13134 @end smallexample
13136 @noindent
13137 will generate the tags file for @code{gnatfind} itself (if the sources
13138 are in the search path!).
13140 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13141 (replacing @var{entity} by whatever you are looking for), and vi will
13142 display a new file with the corresponding declaration of entity.
13143 @end ifclear
13145 @node Examples of gnatfind Usage
13146 @section Examples of @code{gnatfind} Usage
13148 @table @code
13150 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13151 Find declarations for all entities xyz referenced at least once in
13152 main.adb. The references are search in every library file in the search
13153 path.
13155 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13156 switch is set)
13158 The output will look like:
13159 @smallexample
13160 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13161 ^directory/^[directory]^main.adb:24:10: xyz <= body
13162 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13163 @end smallexample
13165 @noindent
13166 that is to say, one of the entities xyz found in main.adb is declared at
13167 line 12 of main.ads (and its body is in main.adb), and another one is
13168 declared at line 45 of foo.ads
13170 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13171 This is the same command as the previous one, instead @code{gnatfind} will
13172 display the content of the Ada source file lines.
13174 The output will look like:
13176 @smallexample
13177 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13178    procedure xyz;
13179 ^directory/^[directory]^main.adb:24:10: xyz <= body
13180    procedure xyz is
13181 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13182    xyz : Integer;
13183 @end smallexample
13185 @noindent
13186 This can make it easier to find exactly the location your are looking
13187 for.
13189 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13190 Find references to all entities containing an x that are
13191 referenced on line 123 of main.ads.
13192 The references will be searched only in main.ads and foo.adb.
13194 @item gnatfind main.ads:123
13195 Find declarations and bodies for all entities that are referenced on
13196 line 123 of main.ads.
13198 This is the same as @code{gnatfind "*":main.adb:123}.
13200 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13201 Find the declaration for the entity referenced at column 45 in
13202 line 123 of file main.adb in directory mydir. Note that it
13203 is usual to omit the identifier name when the column is given,
13204 since the column position identifies a unique reference.
13206 The column has to be the beginning of the identifier, and should not
13207 point to any character in the middle of the identifier.
13209 @end table
13211 @c *********************************
13212 @node The GNAT Pretty-Printer gnatpp
13213 @chapter The GNAT Pretty-Printer @command{gnatpp}
13214 @findex gnatpp
13215 @cindex Pretty-Printer
13217 @noindent
13218 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13219 for source reformatting / pretty-printing.
13220 It takes an Ada source file as input and generates a reformatted
13221 version as output.
13222 You can specify various style directives via switches; e.g.,
13223 identifier case conventions, rules of indentation, and comment layout.
13225 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13226 tree for the input source and thus requires the input to be syntactically and
13227 semantically legal.
13228 If this condition is not met, @command{gnatpp} will terminate with an
13229 error message; no output file will be generated.
13231 @command{gnatpp} cannot process sources that contain
13232 preprocessing directives.
13234 If the compilation unit
13235 contained in the input source depends semantically upon units located
13236 outside the current directory, you have to provide the source search path
13237 when invoking @command{gnatpp}, if these units are contained in files with
13238 names that do not follow the GNAT file naming rules, you have to provide
13239 the configuration file describing the corresponding naming scheme;
13240 see the description of the @command{gnatpp}
13241 switches below. Another possibility is to use a project file and to
13242 call @command{gnatpp} through the @command{gnat} driver
13243 (see @ref{The GNAT Driver and Project Files}).
13245 The @command{gnatpp} command has the form
13247 @smallexample
13248 @c $ gnatpp @ovar{switches} @var{filename}
13249 @c Expanding @ovar macro inline (explanation in macro def comments)
13250 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13251 @end smallexample
13253 @noindent
13254 where
13255 @itemize @bullet
13256 @item
13257 @var{switches} is an optional sequence of switches defining such properties as
13258 the formatting rules, the source search path, and the destination for the
13259 output source file
13261 @item
13262 @var{filename} is the name (including the extension) of the source file to
13263 reformat; ``wildcards'' or several file names on the same gnatpp command are
13264 allowed.  The file name may contain path information; it does not have to
13265 follow the GNAT file naming rules
13267 @item
13268 @samp{@var{gcc_switches}} is a list of switches for
13269 @command{gcc}. They will be passed on to all compiler invocations made by
13270 @command{gnatelim} to generate the ASIS trees. Here you can provide
13271 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13272 use the @option{-gnatec} switch to set the configuration file,
13273 use the @option{-gnat05} switch if sources should be compiled in
13274 Ada 2005 mode  etc.
13275 @end itemize
13277 @menu
13278 * Switches for gnatpp::
13279 * Formatting Rules::
13280 @end menu
13282 @node Switches for gnatpp
13283 @section Switches for @command{gnatpp}
13285 @noindent
13286 The following subsections describe the various switches accepted by
13287 @command{gnatpp}, organized by category.
13289 @ifclear vms
13290 You specify a switch by supplying a name and generally also a value.
13291 In many cases the values for a switch with a given name are incompatible with
13292 each other
13293 (for example the switch that controls the casing of a reserved word may have
13294 exactly one value: upper case, lower case, or
13295 mixed case) and thus exactly one such switch can be in effect for an
13296 invocation of @command{gnatpp}.
13297 If more than one is supplied, the last one is used.
13298 However, some values for the same switch are mutually compatible.
13299 You may supply several such switches to @command{gnatpp}, but then
13300 each must be specified in full, with both the name and the value.
13301 Abbreviated forms (the name appearing once, followed by each value) are
13302 not permitted.
13303 For example, to set
13304 the alignment of the assignment delimiter both in declarations and in
13305 assignment statements, you must write @option{-A2A3}
13306 (or @option{-A2 -A3}), but not @option{-A23}.
13307 @end ifclear
13309 @ifset vms
13310 In many cases the set of options for a given qualifier are incompatible with
13311 each other (for example the qualifier that controls the casing of a reserved
13312 word may have exactly one option, which specifies either upper case, lower
13313 case, or mixed case), and thus exactly one such option can be in effect for
13314 an invocation of @command{gnatpp}.
13315 If more than one is supplied, the last one is used.
13316 However, some qualifiers have options that are mutually compatible,
13317 and then you may then supply several such options when invoking
13318 @command{gnatpp}.
13319 @end ifset
13321 In most cases, it is obvious whether or not the
13322 ^values for a switch with a given name^options for a given qualifier^
13323 are compatible with each other.
13324 When the semantics might not be evident, the summaries below explicitly
13325 indicate the effect.
13327 @menu
13328 * Alignment Control::
13329 * Casing Control::
13330 * Construct Layout Control::
13331 * General Text Layout Control::
13332 * Other Formatting Options::
13333 * Setting the Source Search Path::
13334 * Output File Control::
13335 * Other gnatpp Switches::
13336 @end menu
13338 @node Alignment Control
13339 @subsection Alignment Control
13340 @cindex Alignment control in @command{gnatpp}
13342 @noindent
13343 Programs can be easier to read if certain constructs are vertically aligned.
13344 By default all alignments are set ON.
13345 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13346 OFF, and then use one or more of the other
13347 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13348 to activate alignment for specific constructs.
13350 @table @option
13351 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13353 @ifset vms
13354 @item /ALIGN=ON
13355 Set all alignments to ON
13356 @end ifset
13358 @item ^-A0^/ALIGN=OFF^
13359 Set all alignments to OFF
13361 @item ^-A1^/ALIGN=COLONS^
13362 Align @code{:} in declarations
13364 @item ^-A2^/ALIGN=DECLARATIONS^
13365 Align @code{:=} in initializations in declarations
13367 @item ^-A3^/ALIGN=STATEMENTS^
13368 Align @code{:=} in assignment statements
13370 @item ^-A4^/ALIGN=ARROWS^
13371 Align @code{=>} in associations
13373 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13374 Align @code{at} keywords in the component clauses in record
13375 representation clauses
13376 @end table
13378 @noindent
13379 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13380 is allowed.
13382 @node Casing Control
13383 @subsection Casing Control
13384 @cindex Casing control in @command{gnatpp}
13386 @noindent
13387 @command{gnatpp} allows you to specify the casing for reserved words,
13388 pragma names, attribute designators and identifiers.
13389 For identifiers you may define a
13390 general rule for name casing but also override this rule
13391 via a set of dictionary files.
13393 Three types of casing are supported: lower case, upper case, and mixed case.
13394 Lower and upper case are self-explanatory (but since some letters in
13395 Latin1 and other GNAT-supported character sets
13396 exist only in lower-case form, an upper case conversion will have no
13397 effect on them.)
13398 ``Mixed case'' means that the first letter, and also each letter immediately
13399 following an underscore, are converted to their uppercase forms;
13400 all the other letters are converted to their lowercase forms.
13402 @table @option
13403 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13404 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13405 Attribute designators are lower case
13407 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13408 Attribute designators are upper case
13410 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13411 Attribute designators are mixed case (this is the default)
13413 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13414 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13415 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13416 lower case (this is the default)
13418 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13419 Keywords are upper case
13421 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13422 @item ^-nD^/NAME_CASING=AS_DECLARED^
13423 Name casing for defining occurrences are as they appear in the source file
13424 (this is the default)
13426 @item ^-nU^/NAME_CASING=UPPER_CASE^
13427 Names are in upper case
13429 @item ^-nL^/NAME_CASING=LOWER_CASE^
13430 Names are in lower case
13432 @item ^-nM^/NAME_CASING=MIXED_CASE^
13433 Names are in mixed case
13435 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13436 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13437 Enumeration literal casing for defining occurrences are as they appear in the
13438 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13440 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13441 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13442 setting.
13444 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13445 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13446 setting.
13448 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13449 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13450 setting.
13452 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13453 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13454 Names introduced by type and subtype declarations are always
13455 cased as they appear in the declaration in the source file.
13456 Overrides ^-n^/NAME_CASING^ casing setting.
13458 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13459 Names introduced by type and subtype declarations are always in
13460 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13462 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13463 Names introduced by type and subtype declarations are always in
13464 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13466 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13467 Names introduced by type and subtype declarations are always in
13468 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13470 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
13471 Names introduced by number declarations are always in
13472 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13474 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
13475 Names introduced by number declarations are always in
13476 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13478 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
13479 Names introduced by number declarations are always in
13480 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13482 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13483 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13484 Pragma names are lower case
13486 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13487 Pragma names are upper case
13489 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13490 Pragma names are mixed case (this is the default)
13492 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13493 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13494 Use @var{file} as a @emph{dictionary file} that defines
13495 the casing for a set of specified names,
13496 thereby overriding the effect on these names by
13497 any explicit or implicit
13498 ^-n^/NAME_CASING^ switch.
13499 To supply more than one dictionary file,
13500 use ^several @option{-D} switches^a list of files as options^.
13502 @noindent
13503 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13504 to define the casing for the Ada predefined names and
13505 the names declared in the GNAT libraries.
13507 @item ^-D-^/SPECIFIC_CASING^
13508 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13509 Do not use the default dictionary file;
13510 instead, use the casing
13511 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13512 dictionary file(s)
13513 @end table
13515 @noindent
13516 The structure of a dictionary file, and details on the conventions
13517 used in the default dictionary file, are defined in @ref{Name Casing}.
13519 The @option{^-D-^/SPECIFIC_CASING^} and
13520 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13521 compatible.
13523 @node Construct Layout Control
13524 @subsection Construct Layout Control
13525 @cindex Layout control in @command{gnatpp}
13527 @noindent
13528 This group of @command{gnatpp} switches controls the layout of comments and
13529 complex syntactic constructs.  See @ref{Formatting Comments} for details
13530 on their effect.
13532 @table @option
13533 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13534 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13535 All the comments remain unchanged
13537 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13538 GNAT-style comment line indentation (this is the default).
13540 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13541 Reference-manual comment line indentation.
13543 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13544 GNAT-style comment beginning
13546 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13547 Reformat comment blocks
13549 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13550 Keep unchanged special form comments
13552 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13553 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13554 GNAT-style layout (this is the default)
13556 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13557 Compact layout
13559 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13560 Uncompact layout
13562 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13563 @item ^-N^/NOTABS^
13564 All the VT characters are removed from the comment text. All the HT characters
13565 are expanded with the sequences of space characters to get to the next tab
13566 stops.
13568 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13569 @item ^--no-separate-is^/NO_SEPARATE_IS^
13570 Do not place the keyword @code{is} on a separate line in a subprogram body in
13571 case if the spec occupies more than one line.
13573 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13574 @item ^--separate-label^/SEPARATE_LABEL^
13575 Place statement label(s) on a separate line, with the following statement
13576 on the next line.
13578 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13579 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13580 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13581 keyword @code{then} in IF statements on a separate line.
13583 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13584 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13585 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13586 keyword @code{then} in IF statements on a separate line. This option is
13587 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13589 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13590 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13591 Start each USE clause in a context clause from a separate line.
13593 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13594 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13595 Use a separate line for a loop or block statement name, but do not use an extra
13596 indentation level for the statement itself.
13598 @end table
13600 @ifclear vms
13601 @noindent
13602 The @option{-c1} and @option{-c2} switches are incompatible.
13603 The @option{-c3} and @option{-c4} switches are compatible with each other and
13604 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13605 the other comment formatting switches.
13607 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13608 @end ifclear
13610 @ifset vms
13611 @noindent
13612 For the @option{/COMMENTS_LAYOUT} qualifier:
13613 @itemize @bullet
13614 @item
13615 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13616 @item
13617 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13618 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13619 @end itemize
13621 @noindent
13622 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13623 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13624 @end ifset
13626 @node General Text Layout Control
13627 @subsection General Text Layout Control
13629 @noindent
13630 These switches allow control over line length and indentation.
13632 @table @option
13633 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13634 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13635 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13637 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13638 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13639 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13641 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13642 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13643 Indentation level for continuation lines (relative to the line being
13644 continued), @var{nnn} from 1@dots{}9.
13645 The default
13646 value is one less than the (normal) indentation level, unless the
13647 indentation is set to 1 (in which case the default value for continuation
13648 line indentation is also 1)
13649 @end table
13651 @node Other Formatting Options
13652 @subsection Other Formatting Options
13654 @noindent
13655 These switches control the inclusion of missing end/exit labels, and
13656 the indentation level in @b{case} statements.
13658 @table @option
13659 @item ^-e^/NO_MISSED_LABELS^
13660 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13661 Do not insert missing end/exit labels. An end label is the name of
13662 a construct that may optionally be repeated at the end of the
13663 construct's declaration;
13664 e.g., the names of packages, subprograms, and tasks.
13665 An exit label is the name of a loop that may appear as target
13666 of an exit statement within the loop.
13667 By default, @command{gnatpp} inserts these end/exit labels when
13668 they are absent from the original source. This option suppresses such
13669 insertion, so that the formatted source reflects the original.
13671 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13672 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13673 Insert a Form Feed character after a pragma Page.
13675 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13676 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13677 Do not use an additional indentation level for @b{case} alternatives
13678 and variants if there are @var{nnn} or more (the default
13679 value is 10).
13680 If @var{nnn} is 0, an additional indentation level is
13681 used for @b{case} alternatives and variants regardless of their number.
13683 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
13684 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
13685 If the number of parameter associations is greater than @var{nnn} and if at
13686 least one association uses named notation, start each association from
13687 a new line. If @var{nnn} is 0, no check for the number of associations
13688 is made, this is the default.
13690 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
13691 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
13692 If the number of parameter specifications is greater than @var{nnn}
13693 (or equal to @var{nnn} in case of a function), start each specification from
13694 a new line. The default for @var{nnn} is 3.
13695 @end table
13697 @node Setting the Source Search Path
13698 @subsection Setting the Source Search Path
13700 @noindent
13701 To define the search path for the input source file, @command{gnatpp}
13702 uses the same switches as the GNAT compiler, with the same effects.
13704 @table @option
13705 @item ^-I^/SEARCH=^@var{dir}
13706 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13707 The same as the corresponding gcc switch
13709 @item ^-I-^/NOCURRENT_DIRECTORY^
13710 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13711 The same as the corresponding gcc switch
13713 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13714 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13715 The same as the corresponding gcc switch
13717 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13718 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13719 The same as the corresponding gcc switch
13721 @end table
13723 @node Output File Control
13724 @subsection Output File Control
13726 @noindent
13727 By default the output is sent to the file whose name is obtained by appending
13728 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13729 (if the file with this name already exists, it is unconditionally overwritten).
13730 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13731 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13732 as output file.
13733 The output may be redirected by the following switches:
13735 @table @option
13736 @item ^-pipe^/STANDARD_OUTPUT^
13737 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13738 Send the output to @code{Standard_Output}
13740 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13741 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13742 Write the output into @var{output_file}.
13743 If @var{output_file} already exists, @command{gnatpp} terminates without
13744 reading or processing the input file.
13746 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13747 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13748 Write the output into @var{output_file}, overwriting the existing file
13749 (if one is present).
13751 @item ^-r^/REPLACE^
13752 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13753 Replace the input source file with the reformatted output, and copy the
13754 original input source into the file whose name is obtained by appending the
13755 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13756 If a file with this name already exists, @command{gnatpp} terminates without
13757 reading or processing the input file.
13759 @item ^-rf^/OVERRIDING_REPLACE^
13760 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13761 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13762 already exists, it is overwritten.
13764 @item ^-rnb^/REPLACE_NO_BACKUP^
13765 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13766 Replace the input source file with the reformatted output without
13767 creating any backup copy of the input source.
13769 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13770 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13771 Specifies the format of the reformatted output file. The @var{xxx}
13772 ^string specified with the switch^option^ may be either
13773 @itemize @bullet
13774 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13775 @item ``@option{^crlf^CRLF^}''
13776 the same as @option{^crlf^CRLF^}
13777 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13778 @item ``@option{^lf^LF^}''
13779 the same as @option{^unix^UNIX^}
13780 @end itemize
13782 @item ^-W^/RESULT_ENCODING=^@var{e}
13783 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13784 Specify the wide character encoding method used to write the code in the
13785 result file
13786 @var{e} is one of the following:
13788 @itemize @bullet
13790 @item ^h^HEX^
13791 Hex encoding
13793 @item ^u^UPPER^
13794 Upper half encoding
13796 @item ^s^SHIFT_JIS^
13797 Shift/JIS encoding
13799 @item ^e^EUC^
13800 EUC encoding
13802 @item ^8^UTF8^
13803 UTF-8 encoding
13805 @item ^b^BRACKETS^
13806 Brackets encoding (default value)
13807 @end itemize
13809 @end table
13811 @noindent
13812 Options @option{^-pipe^/STANDARD_OUTPUT^},
13813 @option{^-o^/OUTPUT^} and
13814 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13815 contains only one file to reformat.
13816 Option
13817 @option{^--eol^/END_OF_LINE^}
13819 @option{^-W^/RESULT_ENCODING^}
13820 cannot be used together
13821 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13823 @node Other gnatpp Switches
13824 @subsection Other @code{gnatpp} Switches
13826 @noindent
13827 The additional @command{gnatpp} switches are defined in this subsection.
13829 @table @option
13830 @item ^-files @var{filename}^/FILES=@var{filename}^
13831 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13832 Take the argument source files from the specified file. This file should be an
13833 ordinary text file containing file names separated by spaces or
13834 line breaks. You can use this switch more than once in the same call to
13835 @command{gnatpp}. You also can combine this switch with an explicit list of
13836 files.
13838 @item ^-v^/VERBOSE^
13839 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13840 Verbose mode;
13841 @command{gnatpp} generates version information and then
13842 a trace of the actions it takes to produce or obtain the ASIS tree.
13844 @item ^-w^/WARNINGS^
13845 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13846 Warning mode;
13847 @command{gnatpp} generates a warning whenever it cannot provide
13848 a required layout in the result source.
13849 @end table
13851 @node Formatting Rules
13852 @section Formatting Rules
13854 @noindent
13855 The following subsections show how @command{gnatpp} treats ``white space'',
13856 comments, program layout, and name casing.
13857 They provide the detailed descriptions of the switches shown above.
13859 @menu
13860 * White Space and Empty Lines::
13861 * Formatting Comments::
13862 * Construct Layout::
13863 * Name Casing::
13864 @end menu
13866 @node White Space and Empty Lines
13867 @subsection White Space and Empty Lines
13869 @noindent
13870 @command{gnatpp} does not have an option to control space characters.
13871 It will add or remove spaces according to the style illustrated by the
13872 examples in the @cite{Ada Reference Manual}.
13874 The only format effectors
13875 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13876 that will appear in the output file are platform-specific line breaks,
13877 and also format effectors within (but not at the end of) comments.
13878 In particular, each horizontal tab character that is not inside
13879 a comment will be treated as a space and thus will appear in the
13880 output file as zero or more spaces depending on
13881 the reformatting of the line in which it appears.
13882 The only exception is a Form Feed character, which is inserted after a
13883 pragma @code{Page} when @option{-ff} is set.
13885 The output file will contain no lines with trailing ``white space'' (spaces,
13886 format effectors).
13888 Empty lines in the original source are preserved
13889 only if they separate declarations or statements.
13890 In such contexts, a
13891 sequence of two or more empty lines is replaced by exactly one empty line.
13892 Note that a blank line will be removed if it separates two ``comment blocks''
13893 (a comment block is a sequence of whole-line comments).
13894 In order to preserve a visual separation between comment blocks, use an
13895 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13896 Likewise, if for some reason you wish to have a sequence of empty lines,
13897 use a sequence of empty comments instead.
13899 @node Formatting Comments
13900 @subsection Formatting Comments
13902 @noindent
13903 Comments in Ada code are of two kinds:
13904 @itemize @bullet
13905 @item
13906 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13907 ``white space'') on a line
13909 @item
13910 an @emph{end-of-line comment}, which follows some other Ada lexical element
13911 on the same line.
13912 @end itemize
13914 @noindent
13915 The indentation of a whole-line comment is that of either
13916 the preceding or following line in
13917 the formatted source, depending on switch settings as will be described below.
13919 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13920 between the end of the preceding Ada lexical element and the beginning
13921 of the comment as appear in the original source,
13922 unless either the comment has to be split to
13923 satisfy the line length limitation, or else the next line contains a
13924 whole line comment that is considered a continuation of this end-of-line
13925 comment (because it starts at the same position).
13926 In the latter two
13927 cases, the start of the end-of-line comment is moved right to the nearest
13928 multiple of the indentation level.
13929 This may result in a ``line overflow'' (the right-shifted comment extending
13930 beyond the maximum line length), in which case the comment is split as
13931 described below.
13933 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13934 (GNAT-style comment line indentation)
13935 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13936 (reference-manual comment line indentation).
13937 With reference-manual style, a whole-line comment is indented as if it
13938 were a declaration or statement at the same place
13939 (i.e., according to the indentation of the preceding line(s)).
13940 With GNAT style, a whole-line comment that is immediately followed by an
13941 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13942 word @b{begin}, is indented based on the construct that follows it.
13944 For example:
13945 @smallexample @c ada
13946 @cartouche
13947 if A then
13948     null;
13949        -- some comment
13950 else
13951    null;
13952 end if;
13953 @end cartouche
13954 @end smallexample
13956 @noindent
13957 Reference-manual indentation produces:
13959 @smallexample @c ada
13960 @cartouche
13961 if A then
13962    null;
13963    --  some comment
13964 else
13965    null;
13966 end if;
13967 @end cartouche
13968 @end smallexample
13970 @noindent
13971 while GNAT-style indentation produces:
13973 @smallexample @c ada
13974 @cartouche
13975 if A then
13976    null;
13977 --  some comment
13978 else
13979    null;
13980 end if;
13981 @end cartouche
13982 @end smallexample
13984 @noindent
13985 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13986 (GNAT style comment beginning) has the following
13987 effect:
13989 @itemize @bullet
13990 @item
13991 For each whole-line comment that does not end with two hyphens,
13992 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13993 to ensure that there are at least two spaces between these hyphens and the
13994 first non-blank character of the comment.
13995 @end itemize
13997 @noindent
13998 For an end-of-line comment, if in the original source the next line is a
13999 whole-line comment that starts at the same position
14000 as the end-of-line comment,
14001 then the whole-line comment (and all whole-line comments
14002 that follow it and that start at the same position)
14003 will start at this position in the output file.
14005 @noindent
14006 That is, if in the original source we have:
14008 @smallexample @c ada
14009 @cartouche
14010 begin
14011 A := B + C;            --  B must be in the range Low1..High1
14012                        --  C must be in the range Low2..High2
14013              --B+C will be in the range Low1+Low2..High1+High2
14014 X := X + 1;
14015 @end cartouche
14016 @end smallexample
14018 @noindent
14019 Then in the formatted source we get
14021 @smallexample @c ada
14022 @cartouche
14023 begin
14024    A := B + C;            --  B must be in the range Low1..High1
14025                           --  C must be in the range Low2..High2
14026    --  B+C will be in the range Low1+Low2..High1+High2
14027    X := X + 1;
14028 @end cartouche
14029 @end smallexample
14031 @noindent
14032 A comment that exceeds the line length limit will be split.
14033 Unless switch
14034 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14035 the line belongs to a reformattable block, splitting the line generates a
14036 @command{gnatpp} warning.
14037 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14038 comments may be reformatted in typical
14039 word processor style (that is, moving words between lines and putting as
14040 many words in a line as possible).
14042 @noindent
14043 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14044 that has a special format (that is, a character that is neither a letter nor digit
14045 not white space nor line break immediately following the leading @code{--} of
14046 the comment) should be without any change moved from the argument source
14047 into reformatted source. This switch allows to preserve comments that are used
14048 as a special marks in the code (e.g.@: SPARK annotation).
14050 @node Construct Layout
14051 @subsection Construct Layout
14053 @noindent
14054 In several cases the suggested layout in the Ada Reference Manual includes
14055 an extra level of indentation that many programmers prefer to avoid. The
14056 affected cases include:
14058 @itemize @bullet
14060 @item Record type declaration (RM 3.8)
14062 @item Record representation clause (RM 13.5.1)
14064 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14066 @item Block statement in case if a block has a statement identifier (RM 5.6)
14067 @end itemize
14069 @noindent
14070 In compact mode (when GNAT style layout or compact layout is set),
14071 the pretty printer uses one level of indentation instead
14072 of two. This is achieved in the record definition and record representation
14073 clause cases by putting the @code{record} keyword on the same line as the
14074 start of the declaration or representation clause, and in the block and loop
14075 case by putting the block or loop header on the same line as the statement
14076 identifier.
14078 @noindent
14079 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14080 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14081 layout on the one hand, and uncompact layout
14082 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14083 can be illustrated by the following examples:
14085 @iftex
14086 @cartouche
14087 @multitable @columnfractions .5 .5
14088 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14090 @item
14091 @smallexample @c ada
14092 type q is record
14093    a : integer;
14094    b : integer;
14095 end record;
14096 @end smallexample
14097 @tab
14098 @smallexample @c ada
14099 type q is
14100    record
14101       a : integer;
14102       b : integer;
14103    end record;
14104 @end smallexample
14106 @item
14107 @smallexample @c ada
14108 for q use record
14109    a at 0 range  0 .. 31;
14110    b at 4 range  0 .. 31;
14111 end record;
14112 @end smallexample
14113 @tab
14114 @smallexample @c ada
14115 for q use
14116    record
14117       a at 0 range  0 .. 31;
14118       b at 4 range  0 .. 31;
14119    end record;
14120 @end smallexample
14122 @item
14123 @smallexample @c ada
14124 Block : declare
14125    A : Integer := 3;
14126 begin
14127    Proc (A, A);
14128 end Block;
14129 @end smallexample
14130 @tab
14131 @smallexample @c ada
14132 Block :
14133    declare
14134       A : Integer := 3;
14135    begin
14136       Proc (A, A);
14137    end Block;
14138 @end smallexample
14140 @item
14141 @smallexample @c ada
14142 Clear : for J in 1 .. 10 loop
14143    A (J) := 0;
14144 end loop Clear;
14145 @end smallexample
14146 @tab
14147 @smallexample @c ada
14148 Clear :
14149    for J in 1 .. 10 loop
14150       A (J) := 0;
14151    end loop Clear;
14152 @end smallexample
14153 @end multitable
14154 @end cartouche
14155 @end iftex
14157 @ifnottex
14158 @smallexample
14159 @cartouche
14160 GNAT style, compact layout              Uncompact layout
14162 type q is record                        type q is
14163    a : integer;                            record
14164    b : integer;                               a : integer;
14165 end record;                                   b : integer;
14166                                            end record;
14168 for q use record                        for q use
14169    a at 0 range  0 .. 31;                  record
14170    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
14171 end record;                                   b at 4 range  0 .. 31;
14172                                            end record;
14174 Block : declare                         Block :
14175    A : Integer := 3;                       declare
14176 begin                                         A : Integer := 3;
14177    Proc (A, A);                            begin
14178 end Block;                                    Proc (A, A);
14179                                            end Block;
14181 Clear : for J in 1 .. 10 loop           Clear :
14182    A (J) := 0;                             for J in 1 .. 10 loop
14183 end loop Clear;                               A (J) := 0;
14184                                            end loop Clear;
14185 @end cartouche
14186 @end smallexample
14187 @end ifnottex
14189 @noindent
14190 A further difference between GNAT style layout and compact layout is that
14191 GNAT style layout inserts empty lines as separation for
14192 compound statements, return statements and bodies.
14194 Note that the layout specified by
14195 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14196 for named block and loop statements overrides the layout defined by these
14197 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14198 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14199 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14201 @node Name Casing
14202 @subsection Name Casing
14204 @noindent
14205 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14206 the same casing as the corresponding defining identifier.
14208 You control the casing for defining occurrences via the
14209 @option{^-n^/NAME_CASING^} switch.
14210 @ifclear vms
14211 With @option{-nD} (``as declared'', which is the default),
14212 @end ifclear
14213 @ifset vms
14214 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14215 @end ifset
14216 defining occurrences appear exactly as in the source file
14217 where they are declared.
14218 The other ^values for this switch^options for this qualifier^ ---
14219 @option{^-nU^UPPER_CASE^},
14220 @option{^-nL^LOWER_CASE^},
14221 @option{^-nM^MIXED_CASE^} ---
14222 result in
14223 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14224 If @command{gnatpp} changes the casing of a defining
14225 occurrence, it analogously changes the casing of all the
14226 usage occurrences of this name.
14228 If the defining occurrence of a name is not in the source compilation unit
14229 currently being processed by @command{gnatpp}, the casing of each reference to
14230 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14231 switch (subject to the dictionary file mechanism described below).
14232 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14233 had affected the
14234 casing for the defining occurrence of the name.
14236 Some names may need to be spelled with casing conventions that are not
14237 covered by the upper-, lower-, and mixed-case transformations.
14238 You can arrange correct casing by placing such names in a
14239 @emph{dictionary file},
14240 and then supplying a @option{^-D^/DICTIONARY^} switch.
14241 The casing of names from dictionary files overrides
14242 any @option{^-n^/NAME_CASING^} switch.
14244 To handle the casing of Ada predefined names and the names from GNAT libraries,
14245 @command{gnatpp} assumes a default dictionary file.
14246 The name of each predefined entity is spelled with the same casing as is used
14247 for the entity in the @cite{Ada Reference Manual}.
14248 The name of each entity in the GNAT libraries is spelled with the same casing
14249 as is used in the declaration of that entity.
14251 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14252 default dictionary file.
14253 Instead, the casing for predefined and GNAT-defined names will be established
14254 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14255 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14256 will appear as just shown,
14257 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14258 To ensure that even such names are rendered in uppercase,
14259 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14260 (or else, less conveniently, place these names in upper case in a dictionary
14261 file).
14263 A dictionary file is
14264 a plain text file; each line in this file can be either a blank line
14265 (containing only space characters and ASCII.HT characters), an Ada comment
14266 line, or the specification of exactly one @emph{casing schema}.
14268 A casing schema is a string that has the following syntax:
14270 @smallexample
14271 @cartouche
14272   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14274   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14275 @end cartouche
14276 @end smallexample
14278 @noindent
14279 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14280 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14282 The casing schema string can be followed by white space and/or an Ada-style
14283 comment; any amount of white space is allowed before the string.
14285 If a dictionary file is passed as
14286 @ifclear vms
14287 the value of a @option{-D@var{file}} switch
14288 @end ifclear
14289 @ifset vms
14290 an option to the @option{/DICTIONARY} qualifier
14291 @end ifset
14292 then for every
14293 simple name and every identifier, @command{gnatpp} checks if the dictionary
14294 defines the casing for the name or for some of its parts (the term ``subword''
14295 is used below to denote the part of a name which is delimited by ``_'' or by
14296 the beginning or end of the word and which does not contain any ``_'' inside):
14298 @itemize @bullet
14299 @item
14300 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14301 the casing defined by the dictionary; no subwords are checked for this word
14303 @item
14304 for every subword @command{gnatpp} checks if the dictionary contains the
14305 corresponding string of the form @code{*@var{simple_identifier}*},
14306 and if it does, the casing of this @var{simple_identifier} is used
14307 for this subword
14309 @item
14310 if the whole name does not contain any ``_'' inside, and if for this name
14311 the dictionary contains two entries - one of the form @var{identifier},
14312 and another - of the form *@var{simple_identifier}*, then the first one
14313 is applied to define the casing of this name
14315 @item
14316 if more than one dictionary file is passed as @command{gnatpp} switches, each
14317 dictionary adds new casing exceptions and overrides all the existing casing
14318 exceptions set by the previous dictionaries
14320 @item
14321 when @command{gnatpp} checks if the word or subword is in the dictionary,
14322 this check is not case sensitive
14323 @end itemize
14325 @noindent
14326 For example, suppose we have the following source to reformat:
14328 @smallexample @c ada
14329 @cartouche
14330 procedure test is
14331    name1 : integer := 1;
14332    name4_name3_name2 : integer := 2;
14333    name2_name3_name4 : Boolean;
14334    name1_var : Float;
14335 begin
14336    name2_name3_name4 := name4_name3_name2 > name1;
14337 end;
14338 @end cartouche
14339 @end smallexample
14341 @noindent
14342 And suppose we have two dictionaries:
14344 @smallexample
14345 @cartouche
14346 @i{dict1:}
14347    NAME1
14348    *NaMe3*
14349    *Name1*
14350 @end cartouche
14352 @cartouche
14353 @i{dict2:}
14354   *NAME3*
14355 @end cartouche
14356 @end smallexample
14358 @noindent
14359 If @command{gnatpp} is called with the following switches:
14361 @smallexample
14362 @ifclear vms
14363 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14364 @end ifclear
14365 @ifset vms
14366 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14367 @end ifset
14368 @end smallexample
14370 @noindent
14371 then we will get the following name casing in the @command{gnatpp} output:
14373 @smallexample @c ada
14374 @cartouche
14375 procedure Test is
14376    NAME1             : Integer := 1;
14377    Name4_NAME3_Name2 : Integer := 2;
14378    Name2_NAME3_Name4 : Boolean;
14379    Name1_Var         : Float;
14380 begin
14381    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14382 end Test;
14383 @end cartouche
14384 @end smallexample
14386 @c *********************************
14387 @node The GNAT Metric Tool gnatmetric
14388 @chapter The GNAT Metric Tool @command{gnatmetric}
14389 @findex gnatmetric
14390 @cindex Metric tool
14392 @noindent
14393 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14394 for computing various program metrics.
14395 It takes an Ada source file as input and generates a file containing the
14396 metrics data as output. Various switches control which
14397 metrics are computed and output.
14399 @command{gnatmetric} generates and uses the ASIS
14400 tree for the input source and thus requires the input to be syntactically and
14401 semantically legal.
14402 If this condition is not met, @command{gnatmetric} will generate
14403 an error message; no metric information for this file will be
14404 computed and reported.
14406 If the compilation unit contained in the input source depends semantically
14407 upon units in files located outside the current directory, you have to provide
14408 the source search path when invoking @command{gnatmetric}.
14409 If it depends semantically upon units that are contained
14410 in files with names that do not follow the GNAT file naming rules, you have to
14411 provide the configuration file describing the corresponding naming scheme (see
14412 the description of the @command{gnatmetric} switches below.)
14413 Alternatively, you may use a project file and invoke @command{gnatmetric}
14414 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14416 The @command{gnatmetric} command has the form
14418 @smallexample
14419 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14420 @c Expanding @ovar macro inline (explanation in macro def comments)
14421 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14422 @end smallexample
14424 @noindent
14425 where
14426 @itemize @bullet
14427 @item
14428 @var{switches} specify the metrics to compute and define the destination for
14429 the output
14431 @item
14432 Each @var{filename} is the name (including the extension) of a source
14433 file to process. ``Wildcards'' are allowed, and
14434 the file name may contain path information.
14435 If no @var{filename} is supplied, then the @var{switches} list must contain
14436 at least one
14437 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14438 Including both a @option{-files} switch and one or more
14439 @var{filename} arguments is permitted.
14441 @item
14442 @samp{@var{gcc_switches}} is a list of switches for
14443 @command{gcc}. They will be passed on to all compiler invocations made by
14444 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14445 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14446 and use the @option{-gnatec} switch to set the configuration file,
14447 use the @option{-gnat05} switch if sources should be compiled in
14448 Ada 2005 mode etc.
14449 @end itemize
14451 @menu
14452 * Switches for gnatmetric::
14453 @end menu
14455 @node Switches for gnatmetric
14456 @section Switches for @command{gnatmetric}
14458 @noindent
14459 The following subsections describe the various switches accepted by
14460 @command{gnatmetric}, organized by category.
14462 @menu
14463 * Output Files Control::
14464 * Disable Metrics For Local Units::
14465 * Specifying a set of metrics to compute::
14466 * Other gnatmetric Switches::
14467 * Generate project-wide metrics::
14468 @end menu
14470 @node Output Files Control
14471 @subsection Output File Control
14472 @cindex Output file control in @command{gnatmetric}
14474 @noindent
14475 @command{gnatmetric} has two output formats. It can generate a
14476 textual (human-readable) form, and also XML. By default only textual
14477 output is generated.
14479 When generating the output in textual form, @command{gnatmetric} creates
14480 for each Ada source file a corresponding text file
14481 containing the computed metrics, except for the case when the set of metrics
14482 specified by gnatmetric parameters consists only of metrics that are computed
14483 for the whole set of analyzed sources, but not for each Ada source.
14484 By default, this file is placed in the same directory as where the source
14485 file is located, and its name is obtained
14486 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14487 input file.
14489 All the output information generated in XML format is placed in a single
14490 file. By default this file is placed in the current directory and has the
14491 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14493 Some of the computed metrics are summed over the units passed to
14494 @command{gnatmetric}; for example, the total number of lines of code.
14495 By default this information is sent to @file{stdout}, but a file
14496 can be specified with the @option{-og} switch.
14498 The following switches control the @command{gnatmetric} output:
14500 @table @option
14501 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14502 @item ^-x^/XML^
14503 Generate the XML output
14505 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14506 @item ^-xs^/XSD^
14507 Generate the XML output and the XML schema file that describes the structure
14508 of the XML metric report, this schema is assigned to the XML file. The schema
14509 file has the same name as the XML output file with @file{.xml} suffix replaced
14510 with @file{.xsd}
14512 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14513 @item ^-nt^/NO_TEXT^
14514 Do not generate the output in text form (implies @option{^-x^/XML^})
14516 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14517 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14518 Put text files with detailed metrics into @var{output_dir}
14520 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14521 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14522 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14523 in the name of the output file.
14525 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14526 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14527 Put global metrics into @var{file_name}
14529 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14530 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14531 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14533 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14534 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14535 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14536 output includes the name(s) of the Ada source file(s) from which the metrics
14537 are computed.  By default each name includes the absolute path. The
14538 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14539 to exclude all directory information from the file names that are output.)
14541 @end table
14543 @node Disable Metrics For Local Units
14544 @subsection Disable Metrics For Local Units
14545 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14547 @noindent
14548 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14549 one compilation
14550 unit per one source file. It computes line metrics for the whole source
14551 file, and it also computes syntax
14552 and complexity metrics for the file's outermost unit.
14554 By default, @command{gnatmetric} will also compute all metrics for certain
14555 kinds of locally declared program units:
14557 @itemize @bullet
14558 @item
14559 subprogram (and generic subprogram) bodies;
14561 @item
14562 package (and generic package) specs and bodies;
14564 @item
14565 task object and type specifications and bodies;
14567 @item
14568 protected object and type specifications and bodies.
14569 @end itemize
14571 @noindent
14572 These kinds of entities will be referred to as
14573 @emph{eligible local program units}, or simply @emph{eligible local units},
14574 @cindex Eligible local unit (for @command{gnatmetric})
14575 in the discussion below.
14577 Note that a subprogram declaration, generic instantiation,
14578 or renaming declaration only receives metrics
14579 computation when it appear as the outermost entity
14580 in a source file.
14582 Suppression of metrics computation for eligible local units can be
14583 obtained via the following switch:
14585 @table @option
14586 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14587 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14588 Do not compute detailed metrics for eligible local program units
14590 @end table
14592 @node Specifying a set of metrics to compute
14593 @subsection Specifying a set of metrics to compute
14595 @noindent
14596 By default all the metrics are computed and reported. The switches
14597 described in this subsection allow you to control, on an individual
14598 basis, whether metrics are computed and
14599 reported. If at least one positive metric
14600 switch is specified (that is, a switch that defines that a given
14601 metric or set of metrics is to be computed), then only
14602 explicitly specified metrics are reported.
14604 @menu
14605 * Line Metrics Control::
14606 * Syntax Metrics Control::
14607 * Complexity Metrics Control::
14608 * Coupling Metrics Control::
14609 @end menu
14611 @node Line Metrics Control
14612 @subsubsection Line Metrics Control
14613 @cindex Line metrics control in @command{gnatmetric}
14615 @noindent
14616 For any (legal) source file, and for each of its
14617 eligible local program units, @command{gnatmetric} computes the following
14618 metrics:
14620 @itemize @bullet
14621 @item
14622 the total number of lines;
14624 @item
14625 the total number of code lines (i.e., non-blank lines that are not comments)
14627 @item
14628 the number of comment lines
14630 @item
14631 the number of code lines containing end-of-line comments;
14633 @item
14634 the comment percentage: the ratio between the number of lines that contain
14635 comments and the number of all non-blank lines, expressed as a percentage;
14637 @item
14638 the number of empty lines and lines containing only space characters and/or
14639 format effectors (blank lines)
14641 @item
14642 the average number of code lines in subprogram bodies, task bodies, entry
14643 bodies and statement sequences in package bodies (this metric is only computed
14644 across the whole set of the analyzed units)
14646 @end itemize
14648 @noindent
14649 @command{gnatmetric} sums the values of the line metrics for all the
14650 files being processed and then generates the cumulative results. The tool
14651 also computes for all the files being processed the average number of code
14652 lines in bodies.
14654 You can use the following switches to select the specific line metrics
14655 to be computed and reported.
14657 @table @option
14658 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14660 @ifclear vms
14661 @cindex @option{--no-lines@var{x}}
14662 @end ifclear
14664 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14665 Report all the line metrics
14667 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14668 Do not report any of line metrics
14670 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14671 Report the number of all lines
14673 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14674 Do not report the number of all lines
14676 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14677 Report the number of code lines
14679 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14680 Do not report the number of code lines
14682 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14683 Report the number of comment lines
14685 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14686 Do not report the number of comment lines
14688 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14689 Report the number of code lines containing
14690 end-of-line comments
14692 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14693 Do not report the number of code lines containing
14694 end-of-line comments
14696 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14697 Report the comment percentage in the program text
14699 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14700 Do not report the comment percentage in the program text
14702 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14703 Report the number of blank lines
14705 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14706 Do not report the number of blank lines
14708 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14709 Report the average number of code lines in subprogram bodies, task bodies,
14710 entry bodies and statement sequences in package bodies. The metric is computed
14711 and reported for the whole set of processed Ada sources only.
14713 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14714 Do not report the average number of code lines in subprogram bodies,
14715 task bodies, entry bodies and statement sequences in package bodies.
14717 @end table
14719 @node Syntax Metrics Control
14720 @subsubsection Syntax Metrics Control
14721 @cindex Syntax metrics control in @command{gnatmetric}
14723 @noindent
14724 @command{gnatmetric} computes various syntactic metrics for the
14725 outermost unit and for each eligible local unit:
14727 @table @emph
14728 @item LSLOC (``Logical Source Lines Of Code'')
14729 The total number of declarations and the total number of statements. Note
14730 that the definition of declarations is the one given in the reference
14731 manual:
14733 @noindent
14734 ``Each of the following is defined to be a declaration: any basic_declaration;
14735 an enumeration_literal_specification; a discriminant_specification;
14736 a component_declaration; a loop_parameter_specification; a
14737 parameter_specification; a subprogram_body; an entry_declaration;
14738 an entry_index_specification; a choice_parameter_specification;
14739 a generic_formal_parameter_declaration.''
14741 This means for example that each enumeration literal adds one to the count,
14742 as well as each subprogram parameter.
14744 Thus the results from this metric will be significantly greater than might
14745 be expected from a naive view of counting semicolons.
14747 @item Maximal static nesting level of inner program units
14748 According to
14749 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14750 package, a task unit, a protected unit, a
14751 protected entry, a generic unit, or an explicitly declared subprogram other
14752 than an enumeration literal.''
14754 @item Maximal nesting level of composite syntactic constructs
14755 This corresponds to the notion of the
14756 maximum nesting level in the GNAT built-in style checks
14757 (@pxref{Style Checking})
14758 @end table
14760 @noindent
14761 For the outermost unit in the file, @command{gnatmetric} additionally computes
14762 the following metrics:
14764 @table @emph
14765 @item Public subprograms
14766 This metric is computed for package specs. It is the
14767 number of subprograms and generic subprograms declared in the visible
14768 part (including the visible part of nested packages, protected objects, and
14769 protected types).
14771 @item All subprograms
14772 This metric is computed for bodies and subunits. The
14773 metric is equal to a total number of subprogram bodies in the compilation
14774 unit.
14775 Neither generic instantiations nor renamings-as-a-body nor body stubs
14776 are counted. Any subprogram body is counted, independently of its nesting
14777 level and enclosing constructs. Generic bodies and bodies of protected
14778 subprograms are counted in the same way as ``usual'' subprogram bodies.
14780 @item Public types
14781 This metric is computed for package specs and
14782 generic package declarations. It is the total number of types
14783 that can be referenced from outside this compilation unit, plus the
14784 number of types from all the visible parts of all the visible generic
14785 packages. Generic formal types are not counted.  Only types, not subtypes,
14786 are included.
14788 @noindent
14789 Along with the total number of public types, the following
14790 types are counted and reported separately:
14792 @itemize @bullet
14793 @item
14794 Abstract types
14796 @item
14797 Root tagged types (abstract, non-abstract, private, non-private). Type
14798 extensions are @emph{not} counted
14800 @item
14801 Private types (including private extensions)
14803 @item
14804 Task types
14806 @item
14807 Protected types
14809 @end itemize
14811 @item All types
14812 This metric is computed for any compilation unit. It is equal to the total
14813 number of the declarations of different types given in the compilation unit.
14814 The private and the corresponding full type declaration are counted as one
14815 type declaration. Incomplete type declarations and generic formal types
14816 are not counted.
14817 No distinction is made among different kinds of types (abstract,
14818 private etc.); the total number of types is computed and reported.
14820 @end table
14822 @noindent
14823 By default, all the syntax metrics are computed and reported. You can use the
14824 following switches to select specific syntax metrics.
14826 @table @option
14828 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14830 @ifclear vms
14831 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14832 @end ifclear
14834 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14835 Report all the syntax metrics
14837 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14838 Do not report any of syntax metrics
14840 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14841 Report the total number of declarations
14843 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14844 Do not report the total number of declarations
14846 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14847 Report the total number of statements
14849 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14850 Do not report the total number of statements
14852 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14853 Report the number of public subprograms in a compilation unit
14855 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14856 Do not report the number of public subprograms in a compilation unit
14858 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14859 Report the number of all the subprograms in a compilation unit
14861 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14862 Do not report the number of all the subprograms in a compilation unit
14864 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14865 Report the number of public types in a compilation unit
14867 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14868 Do not report the number of public types in a compilation unit
14870 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14871 Report the number of all the types in a compilation unit
14873 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14874 Do not report the number of all the types in a compilation unit
14876 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14877 Report the maximal program unit nesting level
14879 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14880 Do not report the maximal program unit nesting level
14882 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14883 Report the maximal construct nesting level
14885 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14886 Do not report the maximal construct nesting level
14888 @end table
14890 @node Complexity Metrics Control
14891 @subsubsection Complexity Metrics Control
14892 @cindex Complexity metrics control in @command{gnatmetric}
14894 @noindent
14895 For a program unit that is an executable body (a subprogram body (including
14896 generic bodies), task body, entry body or a package body containing
14897 its own statement sequence) @command{gnatmetric} computes the following
14898 complexity metrics:
14900 @itemize @bullet
14901 @item
14902 McCabe cyclomatic complexity;
14904 @item
14905 McCabe essential complexity;
14907 @item
14908 maximal loop nesting level;
14910 @item
14911 extra exit points (for subprograms);
14912 @end itemize
14914 @noindent
14915 The McCabe cyclomatic complexity metric is defined
14916 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14918 According to McCabe, both control statements and short-circuit control forms
14919 should be taken into account when computing cyclomatic complexity.
14920 For Ada 2012 we have also take into account conditional expressions
14921 and quantified expressions. For each body, we compute three metric values:
14923 @itemize @bullet
14924 @item
14925 the complexity introduced by control
14926 statements only, without taking into account short-circuit forms,
14928 @item
14929 the complexity introduced by short-circuit control forms only, and
14931 @item
14932 the total
14933 cyclomatic complexity, which is the sum of these two values.
14934 @end itemize
14936 @noindent
14938 The cyclomatic complexity is also computed for Ada 2012 expression functions.
14939 An expression function cannot have statements as its components, so only one
14940 metric value is computed as a cyclomatic complexity of an expression function.
14942 The origin of cyclomatic complexity metric is the need to estimate the number
14943 of independent paths in the control flow graph that in turn gives the number
14944 of tests needed to satisfy paths coverage testing completeness criterion.
14945 Considered from the testing point of view, a static Ada @code{loop} (that is,
14946 the @code{loop} statement having static subtype in loop parameter
14947 specification) does not add to cyclomatic complexity. By providing
14948 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14949 may specify that such loops should not be counted when computing the
14950 cyclomatic complexity metric
14952 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14953 counted for the code that is reduced by excluding all the pure structural Ada
14954 control statements. An compound statement is considered as a non-structural
14955 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14956 or if it contains a @code{goto} statement that transfers the control outside
14957 the operator. A selective accept statement with @code{terminate} alternative
14958 is considered as non-structural statement. When computing this metric,
14959 @code{exit} statements are treated in the same way as @code{goto}
14960 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14962 The Ada essential complexity metric defined here is intended to quantify
14963 the extent to which the software is unstructured. It is adapted from
14964 the McCabe essential complexity metric defined in
14965 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
14966 suitable for typical Ada usage. For example, short circuit forms
14967 are not penalized as unstructured in the Ada essential complexity metric.
14969 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14970 the code in the exception handlers and in all the nested program units. The
14971 code of assertions and predicates (that is, subprogram preconditions and
14972 postconditions, subtype predicates and type invariants) is also skipped.
14974 By default, all the complexity metrics are computed and reported.
14975 For more fine-grained control you can use
14976 the following switches:
14978 @table @option
14979 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14981 @ifclear vms
14982 @cindex @option{--no-complexity@var{x}}
14983 @end ifclear
14985 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14986 Report all the complexity metrics
14988 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14989 Do not report any of complexity metrics
14991 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14992 Report the McCabe Cyclomatic Complexity
14994 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14995 Do not report the McCabe Cyclomatic Complexity
14997 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14998 Report the Essential Complexity
15000 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
15001 Do not report the Essential Complexity
15003 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
15004 Report maximal loop nesting level
15006 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
15007 Do not report maximal loop nesting level
15009 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
15010 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15011 task bodies, entry bodies and statement sequences in package bodies.
15012 The metric is computed and reported for whole set of processed Ada sources
15013 only.
15015 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
15016 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15017 bodies, task bodies, entry bodies and statement sequences in package bodies
15019 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
15020 @item ^-ne^/NO_EXITS_AS_GOTOS^
15021 Do not consider @code{exit} statements as @code{goto}s when
15022 computing Essential Complexity
15024 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
15025 @item ^--no-static-loop^/NO_STATIC_LOOP^
15026 Do not consider static loops when computing cyclomatic complexity
15028 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
15029 Report the extra exit points for subprogram bodies. As an exit point, this
15030 metric counts @code{return} statements and raise statements in case when the
15031 raised exception is not handled in the same body. In case of a function this
15032 metric subtracts 1 from the number of exit points, because a function body
15033 must contain at least one @code{return} statement.
15035 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
15036 Do not report the extra exit points for subprogram bodies
15037 @end table
15040 @node Coupling Metrics Control
15041 @subsubsection Coupling Metrics Control
15042 @cindex Coupling metrics control in @command{gnatmetric}
15044 @noindent
15045 @cindex Coupling metrics (in in @command{gnatmetric})
15046 Coupling metrics measure the dependencies between a given entity and other
15047 entities the program consists of. The goal of these metrics is to estimate the
15048 stability of the whole program considered as the collection of entities
15049 (modules, classes etc.).
15051 Gnatmetric computes the following coupling metrics:
15053 @itemize @bullet
15055 @item
15056 @emph{object-oriented coupling} - for classes in traditional object-oriented
15057 sense;
15059 @item
15060 @emph{unit coupling} - for all the program units making up a program;
15062 @item
15063 @emph{control coupling} - this metric counts dependencies between a unit and
15064 only those units that define subprograms;
15065 @end itemize
15067 @noindent
15068 Two kinds of coupling metrics are computed:
15070 @table @asis
15071 @item fan-out coupling (efferent coupling)
15072 @cindex fan-out coupling
15073 @cindex efferent coupling
15074 the number of entities the given entity depends upon. It
15075 estimates in what extent the given entity depends on the changes in
15076 ``external world''
15078 @item fan-in coupling (afferent coupling)
15079 @cindex fan-in coupling
15080 @cindex afferent coupling
15081 the number of entities that depend on a given entity.
15082 It estimates in what extent the ``external world'' depends on the changes in a
15083 given entity
15084 @end table
15086 @noindent
15088 Object-oriented coupling metrics are metrics that measure the dependencies
15089 between a given class (or a group of classes) and the other classes in the
15090 program. In this subsection the term ``class'' is used in its traditional
15091 object-oriented programming sense (an instantiable module that contains data
15092 and/or method members). A @emph{category} (of classes) is a group of closely
15093 related classes that are reused and/or modified together.
15095 A class @code{K}'s fan-out coupling is the number of classes
15096 that @code{K} depends upon.
15097 A category's fan-out coupling is the number of classes outside the
15098 category that the classes inside the category depend upon.
15100 A class @code{K}'s fan-in coupling is the number of classes
15101 that depend upon @code{K}.
15102 A category's fan-in coupling is the number of classes outside the
15103 category that depend on classes belonging to the category.
15105 Ada's implementation of the object-oriented paradigm does not use the
15106 traditional class notion, so the definition of the coupling
15107 metrics for Ada maps the class and class category notions
15108 onto Ada constructs.
15110 For the coupling metrics, several kinds of modules -- a library package,
15111 a library generic package, and a library generic package instantiation --
15112 that define a tagged type or an interface type are
15113 considered to be a class. A category consists of a library package (or
15114 a library generic package) that defines a tagged or an interface type,
15115 together with all its descendant (generic) packages that define tagged
15116 or interface types. That is a
15117 category is an Ada hierarchy of library-level program units. So class coupling
15118 in case of Ada is called as tagged coupling, and category coupling - as
15119 hierarchy coupling.
15121 For any package counted as a class, its body and subunits (if any) are
15122 considered together with its spec when counting the dependencies, and coupling
15123 metrics are reported for spec units only. For dependencies between classes,
15124 the Ada semantic dependencies are considered. For object-oriented coupling
15125 metrics, only dependencies on units that are considered as classes, are
15126 considered.
15128 For unit and control coupling also not compilation units but program units are
15129 counted. That is, for a package, its spec, its body and its subunits (if any)
15130 are considered as making up one unit, and the dependencies that are counted
15131 are the dependencies of all these compilation units collected together as
15132 the dependencies as a (whole) unit. And metrics are reported for spec
15133 compilation units only (or for a subprogram body unit in case if there is no
15134 separate spec for the given subprogram).
15136 For unit coupling, dependencies between all kinds of program units are
15137 considered. For control coupling, for each unit the dependencies of this unit
15138 upon units that define subprograms are counted, so control fan-out coupling
15139 is reported for all units, but control fan-in coupling - only for the units
15140 that define subprograms.
15142 The following simple example illustrates the difference between unit coupling
15143 and control coupling metrics:
15145 @smallexample @c ada
15146 package Lib_1 is
15147     function F_1 (I : Integer) return Integer;
15148 end Lib_1;
15150 package Lib_2 is
15151     type T_2 is new Integer;
15152 end Lib_2;
15154 package body Lib_1 is
15155     function F_1 (I : Integer) return Integer is
15156     begin
15157        return I + 1;
15158     end F_1;
15159 end Lib_1;
15161 with Lib_2; use Lib_2;
15162 package Pack is
15163     Var : T_2;
15164     function Fun (I : Integer) return Integer;
15165 end Pack;
15167 with Lib_1; use Lib_1;
15168 package body Pack is
15169     function Fun (I : Integer) return Integer is
15170     begin
15171        return F_1 (I);
15172     end Fun;
15173 end Pack;
15174 @end smallexample
15176 @noindent
15177 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
15178 units, the result will be:
15180 @smallexample
15181 Coupling metrics:
15182 =================
15183     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15184        control fan-out coupling  : 0
15185        control fan-in coupling   : 1
15186        unit fan-out coupling     : 0
15187        unit fan-in coupling      : 1
15189     Unit Pack (C:\customers\662\L406-007\pack.ads)
15190        control fan-out coupling  : 1
15191        control fan-in coupling   : 0
15192        unit fan-out coupling     : 2
15193        unit fan-in coupling      : 0
15195     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15196        control fan-out coupling  : 0
15197        unit fan-out coupling     : 0
15198        unit fan-in coupling      : 1
15199 @end smallexample
15201 @noindent
15202 The result does not contain values for object-oriented
15203 coupling because none of the argument unit contains a tagged type and
15204 therefore none of these units can be treated as a class.
15206 @code{Pack} (considered as a program unit, that is spec+body) depends on two
15207 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
15208 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
15209 well as control fan-in coupling. Only one of the units @code{Pack} depends
15210 upon defines a subprogram, so its control fan-out coupling is 1.
15212 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
15213 not define a subprogram, so control fan-in metric cannot be applied to it,
15214 and there is one unit that depends on it (@code{Pack}), so it has
15215 unit fan-in coupling equals to 1.
15217 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15218 So it has control fan-in coupling equals to 1 (because there is a unit
15219 depending on it).
15221 When computing coupling metrics, @command{gnatmetric} counts only
15222 dependencies between units that are arguments of the @command{gnatmetric}
15223 call. Coupling metrics are program-wide (or project-wide) metrics, so to
15224 get a valid result, you should call @command{gnatmetric} for
15225 the whole set of sources that make up your program. It can be done
15226 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
15227 option (see @ref{The GNAT Driver and Project Files} for details).
15229 By default, all the coupling metrics are disabled. You can use the following
15230 switches to specify the coupling metrics to be computed and reported:
15232 @table @option
15234 @ifclear vms
15235 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15236 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15237 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15238 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15239 @end ifclear
15241 @ifset vms
15242 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
15243 @end ifset
15245 @item ^--coupling-all^/COUPLING_METRICS=ALL^
15246 Report all the coupling metrics
15248 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
15249 Report tagged (class) fan-out coupling
15251 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
15252 Report tagged (class) fan-in coupling
15254 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
15255 Report hierarchy (category) fan-out coupling
15257 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
15258 Report hierarchy (category) fan-in coupling
15260 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
15261 Report unit fan-out coupling
15263 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
15264 Report unit fan-in coupling
15266 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
15267 Report control fan-out coupling
15269 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
15270 Report control fan-in coupling
15271 @end table
15273 @node Other gnatmetric Switches
15274 @subsection Other @code{gnatmetric} Switches
15276 @noindent
15277 Additional @command{gnatmetric} switches are as follows:
15279 @table @option
15280 @item ^-files @var{filename}^/FILES=@var{filename}^
15281 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15282 Take the argument source files from the specified file. This file should be an
15283 ordinary text file containing file names separated by spaces or
15284 line breaks. You can use this switch more than once in the same call to
15285 @command{gnatmetric}. You also can combine this switch with
15286 an explicit list of files.
15288 @item ^-v^/VERBOSE^
15289 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15290 Verbose mode;
15291 @command{gnatmetric} generates version information and then
15292 a trace of sources being processed.
15294 @item ^-q^/QUIET^
15295 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15296 Quiet mode.
15297 @end table
15299 @node Generate project-wide metrics
15300 @subsection Generate project-wide metrics
15302 In order to compute metrics on all units of a given project, you can use
15303 the @command{gnat} driver along with the @option{-P} option:
15304 @smallexample
15305    gnat metric -Pproj
15306 @end smallexample
15308 @noindent
15309 If the project @code{proj} depends upon other projects, you can compute
15310 the metrics on the project closure using the @option{-U} option:
15311 @smallexample
15312    gnat metric -Pproj -U
15313 @end smallexample
15315 @noindent
15316 Finally, if not all the units are relevant to a particular main
15317 program in the project closure, you can generate metrics for the set
15318 of units needed to create a given main program (unit closure) using
15319 the @option{-U} option followed by the name of the main unit:
15320 @smallexample
15321    gnat metric -Pproj -U main
15322 @end smallexample
15325 @c ***********************************
15326 @node File Name Krunching Using gnatkr
15327 @chapter File Name Krunching Using @code{gnatkr}
15328 @findex gnatkr
15330 @noindent
15331 This chapter discusses the method used by the compiler to shorten
15332 the default file names chosen for Ada units so that they do not
15333 exceed the maximum length permitted. It also describes the
15334 @code{gnatkr} utility that can be used to determine the result of
15335 applying this shortening.
15336 @menu
15337 * About gnatkr::
15338 * Using gnatkr::
15339 * Krunching Method::
15340 * Examples of gnatkr Usage::
15341 @end menu
15343 @node About gnatkr
15344 @section About @code{gnatkr}
15346 @noindent
15347 The default file naming rule in GNAT
15348 is that the file name must be derived from
15349 the unit name. The exact default rule is as follows:
15350 @itemize @bullet
15351 @item
15352 Take the unit name and replace all dots by hyphens.
15353 @item
15354 If such a replacement occurs in the
15355 second character position of a name, and the first character is
15356 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15357 then replace the dot by the character
15358 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15359 instead of a minus.
15360 @end itemize
15361 The reason for this exception is to avoid clashes
15362 with the standard names for children of System, Ada, Interfaces,
15363 and GNAT, which use the prefixes
15364 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15365 respectively.
15367 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15368 switch of the compiler activates a ``krunching''
15369 circuit that limits file names to nn characters (where nn is a decimal
15370 integer). For example, using OpenVMS,
15371 where the maximum file name length is
15372 39, the value of nn is usually set to 39, but if you want to generate
15373 a set of files that would be usable if ported to a system with some
15374 different maximum file length, then a different value can be specified.
15375 The default value of 39 for OpenVMS need not be specified.
15377 The @code{gnatkr} utility can be used to determine the krunched name for
15378 a given file, when krunched to a specified maximum length.
15380 @node Using gnatkr
15381 @section Using @code{gnatkr}
15383 @noindent
15384 The @code{gnatkr} command has the form
15386 @ifclear vms
15387 @smallexample
15388 @c $ gnatkr @var{name} @ovar{length}
15389 @c Expanding @ovar macro inline (explanation in macro def comments)
15390 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15391 @end smallexample
15392 @end ifclear
15394 @ifset vms
15395 @smallexample
15396 $ gnatkr @var{name} /COUNT=nn
15397 @end smallexample
15398 @end ifset
15400 @noindent
15401 @var{name} is the uncrunched file name, derived from the name of the unit
15402 in the standard manner described in the previous section (i.e., in particular
15403 all dots are replaced by hyphens). The file name may or may not have an
15404 extension (defined as a suffix of the form period followed by arbitrary
15405 characters other than period). If an extension is present then it will
15406 be preserved in the output. For example, when krunching @file{hellofile.ads}
15407 to eight characters, the result will be hellofil.ads.
15409 Note: for compatibility with previous versions of @code{gnatkr} dots may
15410 appear in the name instead of hyphens, but the last dot will always be
15411 taken as the start of an extension. So if @code{gnatkr} is given an argument
15412 such as @file{Hello.World.adb} it will be treated exactly as if the first
15413 period had been a hyphen, and for example krunching to eight characters
15414 gives the result @file{hellworl.adb}.
15416 Note that the result is always all lower case (except on OpenVMS where it is
15417 all upper case). Characters of the other case are folded as required.
15419 @var{length} represents the length of the krunched name. The default
15420 when no argument is given is ^8^39^ characters. A length of zero stands for
15421 unlimited, in other words do not chop except for system files where the
15422 implied crunching length is always eight characters.
15424 @noindent
15425 The output is the krunched name. The output has an extension only if the
15426 original argument was a file name with an extension.
15428 @node Krunching Method
15429 @section Krunching Method
15431 @noindent
15432 The initial file name is determined by the name of the unit that the file
15433 contains. The name is formed by taking the full expanded name of the
15434 unit and replacing the separating dots with hyphens and
15435 using ^lowercase^uppercase^
15436 for all letters, except that a hyphen in the second character position is
15437 replaced by a ^tilde^dollar sign^ if the first character is
15438 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15439 The extension is @code{.ads} for a
15440 spec and @code{.adb} for a body.
15441 Krunching does not affect the extension, but the file name is shortened to
15442 the specified length by following these rules:
15444 @itemize @bullet
15445 @item
15446 The name is divided into segments separated by hyphens, tildes or
15447 underscores and all hyphens, tildes, and underscores are
15448 eliminated. If this leaves the name short enough, we are done.
15450 @item
15451 If the name is too long, the longest segment is located (left-most
15452 if there are two of equal length), and shortened by dropping
15453 its last character. This is repeated until the name is short enough.
15455 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15456 to fit the name into 8 characters as required by some operating systems.
15458 @smallexample
15459 our-strings-wide_fixed 22
15460 our strings wide fixed 19
15461 our string  wide fixed 18
15462 our strin   wide fixed 17
15463 our stri    wide fixed 16
15464 our stri    wide fixe  15
15465 our str     wide fixe  14
15466 our str     wid  fixe  13
15467 our str     wid  fix   12
15468 ou  str     wid  fix   11
15469 ou  st      wid  fix   10
15470 ou  st      wi   fix   9
15471 ou  st      wi   fi    8
15472 Final file name: oustwifi.adb
15473 @end smallexample
15475 @item
15476 The file names for all predefined units are always krunched to eight
15477 characters. The krunching of these predefined units uses the following
15478 special prefix replacements:
15480 @table @file
15481 @item ada-
15482 replaced by @file{^a^A^-}
15484 @item gnat-
15485 replaced by @file{^g^G^-}
15487 @item interfaces-
15488 replaced by @file{^i^I^-}
15490 @item system-
15491 replaced by @file{^s^S^-}
15492 @end table
15494 These system files have a hyphen in the second character position. That
15495 is why normal user files replace such a character with a
15496 ^tilde^dollar sign^, to
15497 avoid confusion with system file names.
15499 As an example of this special rule, consider
15500 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15502 @smallexample
15503 ada-strings-wide_fixed 22
15504 a-  strings wide fixed 18
15505 a-  string  wide fixed 17
15506 a-  strin   wide fixed 16
15507 a-  stri    wide fixed 15
15508 a-  stri    wide fixe  14
15509 a-  str     wide fixe  13
15510 a-  str     wid  fixe  12
15511 a-  str     wid  fix   11
15512 a-  st      wid  fix   10
15513 a-  st      wi   fix   9
15514 a-  st      wi   fi    8
15515 Final file name: a-stwifi.adb
15516 @end smallexample
15517 @end itemize
15519 Of course no file shortening algorithm can guarantee uniqueness over all
15520 possible unit names, and if file name krunching is used then it is your
15521 responsibility to ensure that no name clashes occur. The utility
15522 program @code{gnatkr} is supplied for conveniently determining the
15523 krunched name of a file.
15525 @node Examples of gnatkr Usage
15526 @section Examples of @code{gnatkr} Usage
15528 @smallexample
15529 @iftex
15530 @leftskip=0cm
15531 @end iftex
15532 @ifclear vms
15533 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15534 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15535 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15536 $ gnatkr grandparent-parent-child     --> grparchi
15537 @end ifclear
15538 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15539 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15540 @end smallexample
15542 @node Preprocessing Using gnatprep
15543 @chapter Preprocessing Using @code{gnatprep}
15544 @findex gnatprep
15546 @noindent
15547 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15548 preprocessing.
15549 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15550 special GNAT features.
15551 For further discussion of conditional compilation in general, see
15552 @ref{Conditional Compilation}.
15554 @menu
15555 * Preprocessing Symbols::
15556 * Using gnatprep::
15557 * Switches for gnatprep::
15558 * Form of Definitions File::
15559 * Form of Input Text for gnatprep::
15560 @end menu
15562 @node Preprocessing Symbols
15563 @section Preprocessing Symbols
15565 @noindent
15566 Preprocessing symbols are defined in definition files and referred to in
15567 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15568 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15569 all characters need to be in the ASCII set (no accented letters).
15571 @node Using gnatprep
15572 @section Using @code{gnatprep}
15574 @noindent
15575 To call @code{gnatprep} use
15577 @smallexample
15578 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15579 @c Expanding @ovar macro inline (explanation in macro def comments)
15580 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15581 @end smallexample
15583 @noindent
15584 where
15585 @table @var
15586 @item switches
15587 is an optional sequence of switches as described in the next section.
15589 @item infile
15590 is the full name of the input file, which is an Ada source
15591 file containing preprocessor directives.
15593 @item outfile
15594 is the full name of the output file, which is an Ada source
15595 in standard Ada form. When used with GNAT, this file name will
15596 normally have an ads or adb suffix.
15598 @item deffile
15599 is the full name of a text file containing definitions of
15600 preprocessing symbols to be referenced by the preprocessor. This argument is
15601 optional, and can be replaced by the use of the @option{-D} switch.
15603 @end table
15605 @node Switches for gnatprep
15606 @section Switches for @code{gnatprep}
15608 @table @option
15609 @c !sort!
15611 @item ^-b^/BLANK_LINES^
15612 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15613 Causes both preprocessor lines and the lines deleted by
15614 preprocessing to be replaced by blank lines in the output source file,
15615 preserving line numbers in the output file.
15617 @item ^-c^/COMMENTS^
15618 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15619 Causes both preprocessor lines and the lines deleted
15620 by preprocessing to be retained in the output source as comments marked
15621 with the special string @code{"--! "}. This option will result in line numbers
15622 being preserved in the output file.
15624 @item ^-C^/REPLACE_IN_COMMENTS^
15625 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15626 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15627 If this option is specified, then comments are scanned and any $symbol
15628 substitutions performed as in program text. This is particularly useful
15629 when structured comments are used (e.g., when writing programs in the
15630 SPARK dialect of Ada). Note that this switch is not available when
15631 doing integrated preprocessing (it would be useless in this context
15632 since comments are ignored by the compiler in any case).
15634 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15635 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15636 Defines a new preprocessing symbol, associated with value. If no value is given
15637 on the command line, then symbol is considered to be @code{True}. This switch
15638 can be used in place of a definition file.
15640 @ifset vms
15641 @item /REMOVE
15642 @cindex @option{/REMOVE} (@command{gnatprep})
15643 This is the default setting which causes lines deleted by preprocessing
15644 to be entirely removed from the output file.
15645 @end ifset
15647 @item ^-r^/REFERENCE^
15648 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15649 Causes a @code{Source_Reference} pragma to be generated that
15650 references the original input file, so that error messages will use
15651 the file name of this original file. The use of this switch implies
15652 that preprocessor lines are not to be removed from the file, so its
15653 use will force @option{^-b^/BLANK_LINES^} mode if
15654 @option{^-c^/COMMENTS^}
15655 has not been specified explicitly.
15657 Note that if the file to be preprocessed contains multiple units, then
15658 it will be necessary to @code{gnatchop} the output file from
15659 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15660 in the preprocessed file, it will be respected by
15661 @code{gnatchop ^-r^/REFERENCE^}
15662 so that the final chopped files will correctly refer to the original
15663 input source file for @code{gnatprep}.
15665 @item ^-s^/SYMBOLS^
15666 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15667 Causes a sorted list of symbol names and values to be
15668 listed on the standard output file.
15670 @item ^-u^/UNDEFINED^
15671 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15672 Causes undefined symbols to be treated as having the value FALSE in the context
15673 of a preprocessor test. In the absence of this option, an undefined symbol in
15674 a @code{#if} or @code{#elsif} test will be treated as an error.
15676 @end table
15678 @ifclear vms
15679 @noindent
15680 Note: if neither @option{-b} nor @option{-c} is present,
15681 then preprocessor lines and
15682 deleted lines are completely removed from the output, unless -r is
15683 specified, in which case -b is assumed.
15684 @end ifclear
15686 @node Form of Definitions File
15687 @section Form of Definitions File
15689 @noindent
15690 The definitions file contains lines of the form
15692 @smallexample
15693 symbol := value
15694 @end smallexample
15696 @noindent
15697 where symbol is a preprocessing symbol, and value is one of the following:
15699 @itemize @bullet
15700 @item
15701 Empty, corresponding to a null substitution
15702 @item
15703 A string literal using normal Ada syntax
15704 @item
15705 Any sequence of characters from the set
15706 (letters, digits, period, underline).
15707 @end itemize
15709 @noindent
15710 Comment lines may also appear in the definitions file, starting with
15711 the usual @code{--},
15712 and comments may be added to the definitions lines.
15714 @node Form of Input Text for gnatprep
15715 @section Form of Input Text for @code{gnatprep}
15717 @noindent
15718 The input text may contain preprocessor conditional inclusion lines,
15719 as well as general symbol substitution sequences.
15721 The preprocessor conditional inclusion commands have the form
15723 @smallexample
15724 @group
15725 @cartouche
15726 #if @i{expression} @r{[}then@r{]}
15727    lines
15728 #elsif @i{expression} @r{[}then@r{]}
15729    lines
15730 #elsif @i{expression} @r{[}then@r{]}
15731    lines
15732 @dots{}
15733 #else
15734    lines
15735 #end if;
15736 @end cartouche
15737 @end group
15738 @end smallexample
15740 @noindent
15741 In this example, @i{expression} is defined by the following grammar:
15742 @smallexample
15743 @i{expression} ::=  <symbol>
15744 @i{expression} ::=  <symbol> = "<value>"
15745 @i{expression} ::=  <symbol> = <symbol>
15746 @i{expression} ::=  <symbol> 'Defined
15747 @i{expression} ::=  not @i{expression}
15748 @i{expression} ::=  @i{expression} and @i{expression}
15749 @i{expression} ::=  @i{expression} or @i{expression}
15750 @i{expression} ::=  @i{expression} and then @i{expression}
15751 @i{expression} ::=  @i{expression} or else @i{expression}
15752 @i{expression} ::=  ( @i{expression} )
15753 @end smallexample
15755 The following restriction exists: it is not allowed to have "and" or "or"
15756 following "not" in the same expression without parentheses. For example, this
15757 is not allowed:
15759 @smallexample
15760    not X or Y
15761 @end smallexample
15763 This should be one of the following:
15765 @smallexample
15766    (not X) or Y
15767    not (X or Y)
15768 @end smallexample
15770 @noindent
15771 For the first test (@i{expression} ::= <symbol>) the symbol must have
15772 either the value true or false, that is to say the right-hand of the
15773 symbol definition must be one of the (case-insensitive) literals
15774 @code{True} or @code{False}. If the value is true, then the
15775 corresponding lines are included, and if the value is false, they are
15776 excluded.
15778 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15779 the symbol has been defined in the definition file or by a @option{-D}
15780 switch on the command line. Otherwise, the test is false.
15782 The equality tests are case insensitive, as are all the preprocessor lines.
15784 If the symbol referenced is not defined in the symbol definitions file,
15785 then the effect depends on whether or not switch @option{-u}
15786 is specified. If so, then the symbol is treated as if it had the value
15787 false and the test fails. If this switch is not specified, then
15788 it is an error to reference an undefined symbol. It is also an error to
15789 reference a symbol that is defined with a value other than @code{True}
15790 or @code{False}.
15792 The use of the @code{not} operator inverts the sense of this logical test.
15793 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15794 operators, without parentheses. For example, "if not X or Y then" is not
15795 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15797 The @code{then} keyword is optional as shown
15799 The @code{#} must be the first non-blank character on a line, but
15800 otherwise the format is free form. Spaces or tabs may appear between
15801 the @code{#} and the keyword. The keywords and the symbols are case
15802 insensitive as in normal Ada code. Comments may be used on a
15803 preprocessor line, but other than that, no other tokens may appear on a
15804 preprocessor line. Any number of @code{elsif} clauses can be present,
15805 including none at all. The @code{else} is optional, as in Ada.
15807 The @code{#} marking the start of a preprocessor line must be the first
15808 non-blank character on the line, i.e., it must be preceded only by
15809 spaces or horizontal tabs.
15811 Symbol substitution outside of preprocessor lines is obtained by using
15812 the sequence
15814 @smallexample
15815 $symbol
15816 @end smallexample
15818 @noindent
15819 anywhere within a source line, except in a comment or within a
15820 string literal. The identifier
15821 following the @code{$} must match one of the symbols defined in the symbol
15822 definition file, and the result is to substitute the value of the
15823 symbol in place of @code{$symbol} in the output file.
15825 Note that although the substitution of strings within a string literal
15826 is not possible, it is possible to have a symbol whose defined value is
15827 a string literal. So instead of setting XYZ to @code{hello} and writing:
15829 @smallexample
15830 Header : String := "$XYZ";
15831 @end smallexample
15833 @noindent
15834 you should set XYZ to @code{"hello"} and write:
15836 @smallexample
15837 Header : String := $XYZ;
15838 @end smallexample
15840 @noindent
15841 and then the substitution will occur as desired.
15843 @node The GNAT Library Browser gnatls
15844 @chapter The GNAT Library Browser @code{gnatls}
15845 @findex gnatls
15846 @cindex Library browser
15848 @noindent
15849 @code{gnatls} is a tool that outputs information about compiled
15850 units. It gives the relationship between objects, unit names and source
15851 files. It can also be used to check the source dependencies of a unit
15852 as well as various characteristics.
15854 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15855 driver (see @ref{The GNAT Driver and Project Files}).
15857 @menu
15858 * Running gnatls::
15859 * Switches for gnatls::
15860 * Examples of gnatls Usage::
15861 @end menu
15863 @node Running gnatls
15864 @section Running @code{gnatls}
15866 @noindent
15867 The @code{gnatls} command has the form
15869 @smallexample
15870 $ gnatls switches @var{object_or_ali_file}
15871 @end smallexample
15873 @noindent
15874 The main argument is the list of object or @file{ali} files
15875 (@pxref{The Ada Library Information Files})
15876 for which information is requested.
15878 In normal mode, without additional option, @code{gnatls} produces a
15879 four-column listing. Each line represents information for a specific
15880 object. The first column gives the full path of the object, the second
15881 column gives the name of the principal unit in this object, the third
15882 column gives the status of the source and the fourth column gives the
15883 full path of the source representing this unit.
15884 Here is a simple example of use:
15886 @smallexample
15887 $ gnatls *.o
15888 ^./^[]^demo1.o            demo1            DIF demo1.adb
15889 ^./^[]^demo2.o            demo2             OK demo2.adb
15890 ^./^[]^hello.o            h1                OK hello.adb
15891 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15892 ^./^[]^instr.o            instr             OK instr.adb
15893 ^./^[]^tef.o              tef              DIF tef.adb
15894 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15895 ^./^[]^tgef.o             tgef             DIF tgef.adb
15896 @end smallexample
15898 @noindent
15899 The first line can be interpreted as follows: the main unit which is
15900 contained in
15901 object file @file{demo1.o} is demo1, whose main source is in
15902 @file{demo1.adb}. Furthermore, the version of the source used for the
15903 compilation of demo1 has been modified (DIF). Each source file has a status
15904 qualifier which can be:
15906 @table @code
15907 @item OK (unchanged)
15908 The version of the source file used for the compilation of the
15909 specified unit corresponds exactly to the actual source file.
15911 @item MOK (slightly modified)
15912 The version of the source file used for the compilation of the
15913 specified unit differs from the actual source file but not enough to
15914 require recompilation. If you use gnatmake with the qualifier
15915 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15916 MOK will not be recompiled.
15918 @item DIF (modified)
15919 No version of the source found on the path corresponds to the source
15920 used to build this object.
15922 @item ??? (file not found)
15923 No source file was found for this unit.
15925 @item HID (hidden,  unchanged version not first on PATH)
15926 The version of the source that corresponds exactly to the source used
15927 for compilation has been found on the path but it is hidden by another
15928 version of the same source that has been modified.
15930 @end table
15932 @node Switches for gnatls
15933 @section Switches for @code{gnatls}
15935 @noindent
15936 @code{gnatls} recognizes the following switches:
15938 @table @option
15939 @c !sort!
15940 @cindex @option{--version} @command{gnatls}
15941 Display Copyright and version, then exit disregarding all other options.
15943 @item --help
15944 @cindex @option{--help} @command{gnatls}
15945 If @option{--version} was not used, display usage, then exit disregarding
15946 all other options.
15948 @item ^-a^/ALL_UNITS^
15949 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15950 Consider all units, including those of the predefined Ada library.
15951 Especially useful with @option{^-d^/DEPENDENCIES^}.
15953 @item ^-d^/DEPENDENCIES^
15954 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15955 List sources from which specified units depend on.
15957 @item ^-h^/OUTPUT=OPTIONS^
15958 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15959 Output the list of options.
15961 @item ^-o^/OUTPUT=OBJECTS^
15962 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15963 Only output information about object files.
15965 @item ^-s^/OUTPUT=SOURCES^
15966 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15967 Only output information about source files.
15969 @item ^-u^/OUTPUT=UNITS^
15970 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15971 Only output information about compilation units.
15973 @item ^-files^/FILES^=@var{file}
15974 @cindex @option{^-files^/FILES^} (@code{gnatls})
15975 Take as arguments the files listed in text file @var{file}.
15976 Text file @var{file} may contain empty lines that are ignored.
15977 Each nonempty line should contain the name of an existing file.
15978 Several such switches may be specified simultaneously.
15980 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15981 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15982 @itemx ^-I^/SEARCH=^@var{dir}
15983 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15984 @itemx -nostdinc
15985 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15986 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15987 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15988 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15989 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15990 flags (@pxref{Switches for gnatmake}).
15992 @item --RTS=@var{rts-path}
15993 @cindex @option{--RTS} (@code{gnatls})
15994 Specifies the default location of the runtime library. Same meaning as the
15995 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15997 @item ^-v^/OUTPUT=VERBOSE^
15998 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15999 Verbose mode. Output the complete source, object and project paths. Do not use
16000 the default column layout but instead use long format giving as much as
16001 information possible on each requested units, including special
16002 characteristics such as:
16004 @table @code
16005 @item  Preelaborable
16006 The unit is preelaborable in the Ada sense.
16008 @item No_Elab_Code
16009 No elaboration code has been produced by the compiler for this unit.
16011 @item Pure
16012 The unit is pure in the Ada sense.
16014 @item Elaborate_Body
16015 The unit contains a pragma Elaborate_Body.
16017 @item Remote_Types
16018 The unit contains a pragma Remote_Types.
16020 @item Shared_Passive
16021 The unit contains a pragma Shared_Passive.
16023 @item Predefined
16024 This unit is part of the predefined environment and cannot be modified
16025 by the user.
16027 @item Remote_Call_Interface
16028 The unit contains a pragma Remote_Call_Interface.
16030 @end table
16032 @end table
16034 @node Examples of gnatls Usage
16035 @section Example of @code{gnatls} Usage
16036 @ifclear vms
16038 @noindent
16039 Example of using the verbose switch. Note how the source and
16040 object paths are affected by the -I switch.
16042 @smallexample
16043 $ gnatls -v -I.. demo1.o
16045 GNATLS 5.03w (20041123-34)
16046 Copyright 1997-2004 Free Software Foundation, Inc.
16048 Source Search Path:
16049    <Current_Directory>
16050    ../
16051    /home/comar/local/adainclude/
16053 Object Search Path:
16054    <Current_Directory>
16055    ../
16056    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16058 Project Search Path:
16059    <Current_Directory>
16060    /home/comar/local/lib/gnat/
16062 ./demo1.o
16063    Unit =>
16064      Name   => demo1
16065      Kind   => subprogram body
16066      Flags  => No_Elab_Code
16067      Source => demo1.adb    modified
16068 @end smallexample
16070 @noindent
16071 The following is an example of use of the dependency list.
16072 Note the use of the -s switch
16073 which gives a straight list of source files. This can be useful for
16074 building specialized scripts.
16076 @smallexample
16077 $ gnatls -d demo2.o
16078 ./demo2.o   demo2        OK demo2.adb
16079                          OK gen_list.ads
16080                          OK gen_list.adb
16081                          OK instr.ads
16082                          OK instr-child.ads
16084 $ gnatls -d -s -a demo1.o
16085 demo1.adb
16086 /home/comar/local/adainclude/ada.ads
16087 /home/comar/local/adainclude/a-finali.ads
16088 /home/comar/local/adainclude/a-filico.ads
16089 /home/comar/local/adainclude/a-stream.ads
16090 /home/comar/local/adainclude/a-tags.ads
16091 gen_list.ads
16092 gen_list.adb
16093 /home/comar/local/adainclude/gnat.ads
16094 /home/comar/local/adainclude/g-io.ads
16095 instr.ads
16096 /home/comar/local/adainclude/system.ads
16097 /home/comar/local/adainclude/s-exctab.ads
16098 /home/comar/local/adainclude/s-finimp.ads
16099 /home/comar/local/adainclude/s-finroo.ads
16100 /home/comar/local/adainclude/s-secsta.ads
16101 /home/comar/local/adainclude/s-stalib.ads
16102 /home/comar/local/adainclude/s-stoele.ads
16103 /home/comar/local/adainclude/s-stratt.ads
16104 /home/comar/local/adainclude/s-tasoli.ads
16105 /home/comar/local/adainclude/s-unstyp.ads
16106 /home/comar/local/adainclude/unchconv.ads
16107 @end smallexample
16108 @end ifclear
16110 @ifset vms
16111 @smallexample
16112 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16114 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16115 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16116 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16117 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16118 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16119 demo1.adb
16120 gen_list.ads
16121 gen_list.adb
16122 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16123 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16124 instr.ads
16125 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16126 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16127 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16128 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16129 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16130 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16131 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16132 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16133 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16134 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16135 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16136 @end smallexample
16137 @end ifset
16139 @node Cleaning Up Using gnatclean
16140 @chapter Cleaning Up Using @code{gnatclean}
16141 @findex gnatclean
16142 @cindex Cleaning tool
16144 @noindent
16145 @code{gnatclean} is a tool that allows the deletion of files produced by the
16146 compiler, binder and linker, including ALI files, object files, tree files,
16147 expanded source files, library files, interface copy source files, binder
16148 generated files and executable files.
16150 @menu
16151 * Running gnatclean::
16152 * Switches for gnatclean::
16153 @c * Examples of gnatclean Usage::
16154 @end menu
16156 @node Running gnatclean
16157 @section Running @code{gnatclean}
16159 @noindent
16160 The @code{gnatclean} command has the form:
16162 @smallexample
16163 $ gnatclean switches @var{names}
16164 @end smallexample
16166 @noindent
16167 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16168 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16169 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16171 @noindent
16172 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16173 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16174 the linker. In informative-only mode, specified by switch
16175 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16176 normal mode is listed, but no file is actually deleted.
16178 @node Switches for gnatclean
16179 @section Switches for @code{gnatclean}
16181 @noindent
16182 @code{gnatclean} recognizes the following switches:
16184 @table @option
16185 @c !sort!
16186 @cindex @option{--version} @command{gnatclean}
16187 Display Copyright and version, then exit disregarding all other options.
16189 @item --help
16190 @cindex @option{--help} @command{gnatclean}
16191 If @option{--version} was not used, display usage, then exit disregarding
16192 all other options.
16194 @item ^--subdirs^/SUBDIRS^=subdir
16195 Actual object directory of each project file is the subdirectory subdir of the
16196 object directory specified or defaulted in the project file.
16198 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
16199 By default, shared library projects are not allowed to import static library
16200 projects. When this switch is used on the command line, this restriction is
16201 relaxed.
16203 @item ^-c^/COMPILER_FILES_ONLY^
16204 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16205 Only attempt to delete the files produced by the compiler, not those produced
16206 by the binder or the linker. The files that are not to be deleted are library
16207 files, interface copy files, binder generated files and executable files.
16209 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16210 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16211 Indicate that ALI and object files should normally be found in directory
16212 @var{dir}.
16214 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16215 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16216 When using project files, if some errors or warnings are detected during
16217 parsing and verbose mode is not in effect (no use of switch
16218 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16219 file, rather than its simple file name.
16221 @item ^-h^/HELP^
16222 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16223 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16225 @item ^-n^/NODELETE^
16226 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16227 Informative-only mode. Do not delete any files. Output the list of the files
16228 that would have been deleted if this switch was not specified.
16230 @item ^-P^/PROJECT_FILE=^@var{project}
16231 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16232 Use project file @var{project}. Only one such switch can be used.
16233 When cleaning a project file, the files produced by the compilation of the
16234 immediate sources or inherited sources of the project files are to be
16235 deleted. This is not depending on the presence or not of executable names
16236 on the command line.
16238 @item ^-q^/QUIET^
16239 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16240 Quiet output. If there are no errors, do not output anything, except in
16241 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16242 (switch ^-n^/NODELETE^).
16244 @item ^-r^/RECURSIVE^
16245 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16246 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16247 clean all imported and extended project files, recursively. If this switch
16248 is not specified, only the files related to the main project file are to be
16249 deleted. This switch has no effect if no project file is specified.
16251 @item ^-v^/VERBOSE^
16252 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16253 Verbose mode.
16255 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16256 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16257 Indicates the verbosity of the parsing of GNAT project files.
16258 @xref{Switches Related to Project Files}.
16260 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16261 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16262 Indicates that external variable @var{name} has the value @var{value}.
16263 The Project Manager will use this value for occurrences of
16264 @code{external(name)} when parsing the project file.
16265 @xref{Switches Related to Project Files}.
16267 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16268 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16269 When searching for ALI and object files, look in directory
16270 @var{dir}.
16272 @item ^-I^/SEARCH=^@var{dir}
16273 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16274 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16276 @item ^-I-^/NOCURRENT_DIRECTORY^
16277 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16278 @cindex Source files, suppressing search
16279 Do not look for ALI or object files in the directory
16280 where @code{gnatclean} was invoked.
16282 @end table
16284 @c @node Examples of gnatclean Usage
16285 @c @section Examples of @code{gnatclean} Usage
16287 @ifclear vms
16288 @node GNAT and Libraries
16289 @chapter GNAT and Libraries
16290 @cindex Library, building, installing, using
16292 @noindent
16293 This chapter describes how to build and use libraries with GNAT, and also shows
16294 how to recompile the GNAT run-time library. You should be familiar with the
16295 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16296 chapter.
16298 @menu
16299 * Introduction to Libraries in GNAT::
16300 * General Ada Libraries::
16301 * Stand-alone Ada Libraries::
16302 * Rebuilding the GNAT Run-Time Library::
16303 @end menu
16305 @node Introduction to Libraries in GNAT
16306 @section Introduction to Libraries in GNAT
16308 @noindent
16309 A library is, conceptually, a collection of objects which does not have its
16310 own main thread of execution, but rather provides certain services to the
16311 applications that use it. A library can be either statically linked with the
16312 application, in which case its code is directly included in the application,
16313 or, on platforms that support it, be dynamically linked, in which case
16314 its code is shared by all applications making use of this library.
16316 GNAT supports both types of libraries.
16317 In the static case, the compiled code can be provided in different ways. The
16318 simplest approach is to provide directly the set of objects resulting from
16319 compilation of the library source files. Alternatively, you can group the
16320 objects into an archive using whatever commands are provided by the operating
16321 system. For the latter case, the objects are grouped into a shared library.
16323 In the GNAT environment, a library has three types of components:
16324 @itemize @bullet
16325 @item
16326 Source files.
16327 @item
16328 @file{ALI} files.
16329 @xref{The Ada Library Information Files}.
16330 @item
16331 Object files, an archive or a shared library.
16332 @end itemize
16334 @noindent
16335 A GNAT library may expose all its source files, which is useful for
16336 documentation purposes. Alternatively, it may expose only the units needed by
16337 an external user to make use of the library. That is to say, the specs
16338 reflecting the library services along with all the units needed to compile
16339 those specs, which can include generic bodies or any body implementing an
16340 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16341 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16343 All compilation units comprising an application, including those in a library,
16344 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16345 computes the elaboration order from the @file{ALI} files and this is why they
16346 constitute a mandatory part of GNAT libraries.
16347 @emph{Stand-alone libraries} are the exception to this rule because a specific
16348 library elaboration routine is produced independently of the application(s)
16349 using the library.
16351 @node General Ada Libraries
16352 @section General Ada Libraries
16354 @menu
16355 * Building a library::
16356 * Installing a library::
16357 * Using a library::
16358 @end menu
16360 @node Building a library
16361 @subsection Building a library
16363 @noindent
16364 The easiest way to build a library is to use the Project Manager,
16365 which supports a special type of project called a @emph{Library Project}
16366 (@pxref{Library Projects}).
16368 A project is considered a library project, when two project-level attributes
16369 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16370 control different aspects of library configuration, additional optional
16371 project-level attributes can be specified:
16372 @table @code
16373 @item Library_Kind
16374 This attribute controls whether the library is to be static or dynamic
16376 @item Library_Version
16377 This attribute specifies the library version; this value is used
16378 during dynamic linking of shared libraries to determine if the currently
16379 installed versions of the binaries are compatible.
16381 @item Library_Options
16382 @item Library_GCC
16383 These attributes specify additional low-level options to be used during
16384 library generation, and redefine the actual application used to generate
16385 library.
16386 @end table
16388 @noindent
16389 The GNAT Project Manager takes full care of the library maintenance task,
16390 including recompilation of the source files for which objects do not exist
16391 or are not up to date, assembly of the library archive, and installation of
16392 the library (i.e., copying associated source, object and @file{ALI} files
16393 to the specified location).
16395 Here is a simple library project file:
16396 @smallexample @c ada
16397 project My_Lib is
16398    for Source_Dirs use ("src1", "src2");
16399    for Object_Dir use "obj";
16400    for Library_Name use "mylib";
16401    for Library_Dir use "lib";
16402    for Library_Kind use "dynamic";
16403 end My_lib;
16404 @end smallexample
16406 @noindent
16407 and the compilation command to build and install the library:
16409 @smallexample @c ada
16410   $ gnatmake -Pmy_lib
16411 @end smallexample
16413 @noindent
16414 It is not entirely trivial to perform manually all the steps required to
16415 produce a library. We recommend that you use the GNAT Project Manager
16416 for this task. In special cases where this is not desired, the necessary
16417 steps are discussed below.
16419 There are various possibilities for compiling the units that make up the
16420 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16421 with a conventional script. For simple libraries, it is also possible to create
16422 a dummy main program which depends upon all the packages that comprise the
16423 interface of the library. This dummy main program can then be given to
16424 @command{gnatmake}, which will ensure that all necessary objects are built.
16426 After this task is accomplished, you should follow the standard procedure
16427 of the underlying operating system to produce the static or shared library.
16429 Here is an example of such a dummy program:
16430 @smallexample @c ada
16431 @group
16432 with My_Lib.Service1;
16433 with My_Lib.Service2;
16434 with My_Lib.Service3;
16435 procedure My_Lib_Dummy is
16436 begin
16437    null;
16438 end;
16439 @end group
16440 @end smallexample
16442 @noindent
16443 Here are the generic commands that will build an archive or a shared library.
16445 @smallexample
16446 # compiling the library
16447 $ gnatmake -c my_lib_dummy.adb
16449 # we don't need the dummy object itself
16450 $ rm my_lib_dummy.o my_lib_dummy.ali
16452 # create an archive with the remaining objects
16453 $ ar rc libmy_lib.a *.o
16454 # some systems may require "ranlib" to be run as well
16456 # or create a shared library
16457 $ gcc -shared -o libmy_lib.so *.o
16458 # some systems may require the code to have been compiled with -fPIC
16460 # remove the object files that are now in the library
16461 $ rm *.o
16463 # Make the ALI files read-only so that gnatmake will not try to
16464 # regenerate the objects that are in the library
16465 $ chmod -w *.ali
16466 @end smallexample
16468 @noindent
16469 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16470 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16471 be accessed by the directive @option{-l@var{xxx}} at link time.
16473 @node Installing a library
16474 @subsection Installing a library
16475 @cindex @code{ADA_PROJECT_PATH}
16476 @cindex @code{GPR_PROJECT_PATH}
16478 @noindent
16479 If you use project files, library installation is part of the library build
16480 process (@pxref{Installing a library with project files}).
16482 When project files are not an option, it is also possible, but not recommended,
16483 to install the library so that the sources needed to use the library are on the
16484 Ada source path and the ALI files & libraries be on the Ada Object path (see
16485 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16486 administrator can place general-purpose libraries in the default compiler
16487 paths, by specifying the libraries' location in the configuration files
16488 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16489 must be located in the GNAT installation tree at the same place as the gcc spec
16490 file. The location of the gcc spec file can be determined as follows:
16491 @smallexample
16492 $ gcc -v
16493 @end smallexample
16495 @noindent
16496 The configuration files mentioned above have a simple format: each line
16497 must contain one unique directory name.
16498 Those names are added to the corresponding path
16499 in their order of appearance in the file. The names can be either absolute
16500 or relative; in the latter case, they are relative to where theses files
16501 are located.
16503 The files @file{ada_source_path} and @file{ada_object_path} might not be
16504 present in a
16505 GNAT installation, in which case, GNAT will look for its run-time library in
16506 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16507 objects and @file{ALI} files). When the files exist, the compiler does not
16508 look in @file{adainclude} and @file{adalib}, and thus the
16509 @file{ada_source_path} file
16510 must contain the location for the GNAT run-time sources (which can simply
16511 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16512 contain the location for the GNAT run-time objects (which can simply
16513 be @file{adalib}).
16515 You can also specify a new default path to the run-time library at compilation
16516 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16517 the run-time library you want your program to be compiled with. This switch is
16518 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16519 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16521 It is possible to install a library before or after the standard GNAT
16522 library, by reordering the lines in the configuration files. In general, a
16523 library must be installed before the GNAT library if it redefines
16524 any part of it.
16526 @node Using a library
16527 @subsection Using a library
16529 @noindent Once again, the project facility greatly simplifies the use of
16530 libraries. In this context, using a library is just a matter of adding a
16531 @code{with} clause in the user project. For instance, to make use of the
16532 library @code{My_Lib} shown in examples in earlier sections, you can
16533 write:
16535 @smallexample @c projectfile
16536 with "my_lib";
16537 project My_Proj is
16538   @dots{}
16539 end My_Proj;
16540 @end smallexample
16542 Even if you have a third-party, non-Ada library, you can still use GNAT's
16543 Project Manager facility to provide a wrapper for it. For example, the
16544 following project, when @code{with}ed by your main project, will link with the
16545 third-party library @file{liba.a}:
16547 @smallexample @c projectfile
16548 @group
16549 project Liba is
16550    for Externally_Built use "true";
16551    for Source_Files use ();
16552    for Library_Dir use "lib";
16553    for Library_Name use "a";
16554    for Library_Kind use "static";
16555 end Liba;
16556 @end group
16557 @end smallexample
16558 This is an alternative to the use of @code{pragma Linker_Options}. It is
16559 especially interesting in the context of systems with several interdependent
16560 static libraries where finding a proper linker order is not easy and best be
16561 left to the tools having visibility over project dependence information.
16563 @noindent
16564 In order to use an Ada library manually, you need to make sure that this
16565 library is on both your source and object path
16566 (see @ref{Search Paths and the Run-Time Library (RTL)}
16567 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16568 in an archive or a shared library, you need to specify the desired
16569 library at link time.
16571 For example, you can use the library @file{mylib} installed in
16572 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16574 @smallexample
16575 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16576   -largs -lmy_lib
16577 @end smallexample
16579 @noindent
16580 This can be expressed more simply:
16581 @smallexample
16582 $ gnatmake my_appl
16583 @end smallexample
16584 @noindent
16585 when the following conditions are met:
16586 @itemize @bullet
16587 @item
16588 @file{/dir/my_lib_src} has been added by the user to the environment
16589 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16590 @file{ada_source_path}
16591 @item
16592 @file{/dir/my_lib_obj} has been added by the user to the environment
16593 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16594 @file{ada_object_path}
16595 @item
16596 a pragma @code{Linker_Options} has been added to one of the sources.
16597 For example:
16599 @smallexample @c ada
16600 pragma Linker_Options ("-lmy_lib");
16601 @end smallexample
16602 @end itemize
16604 @node Stand-alone Ada Libraries
16605 @section Stand-alone Ada Libraries
16606 @cindex Stand-alone library, building, using
16608 @menu
16609 * Introduction to Stand-alone Libraries::
16610 * Building a Stand-alone Library::
16611 * Creating a Stand-alone Library to be used in a non-Ada context::
16612 * Restrictions in Stand-alone Libraries::
16613 @end menu
16615 @node Introduction to Stand-alone Libraries
16616 @subsection Introduction to Stand-alone Libraries
16618 @noindent
16619 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16620 necessary code to
16621 elaborate the Ada units that are included in the library. In contrast with
16622 an ordinary library, which consists of all sources, objects and @file{ALI}
16623 files of the
16624 library, a SAL may specify a restricted subset of compilation units
16625 to serve as a library interface. In this case, the fully
16626 self-sufficient set of files will normally consist of an objects
16627 archive, the sources of interface units' specs, and the @file{ALI}
16628 files of interface units.
16629 If an interface spec contains a generic unit or an inlined subprogram,
16630 the body's
16631 source must also be provided; if the units that must be provided in the source
16632 form depend on other units, the source and @file{ALI} files of those must
16633 also be provided.
16635 The main purpose of a SAL is to minimize the recompilation overhead of client
16636 applications when a new version of the library is installed. Specifically,
16637 if the interface sources have not changed, client applications do not need to
16638 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16639 version, controlled by @code{Library_Version} attribute, is not changed,
16640 then the clients do not need to be relinked.
16642 SALs also allow the library providers to minimize the amount of library source
16643 text exposed to the clients.  Such ``information hiding'' might be useful or
16644 necessary for various reasons.
16646 Stand-alone libraries are also well suited to be used in an executable whose
16647 main routine is not written in Ada.
16649 @node Building a Stand-alone Library
16650 @subsection Building a Stand-alone Library
16652 @noindent
16653 GNAT's Project facility provides a simple way of building and installing
16654 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16655 To be a Stand-alone Library Project, in addition to the two attributes
16656 that make a project a Library Project (@code{Library_Name} and
16657 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16658 @code{Library_Interface} must be defined.  For example:
16660 @smallexample @c projectfile
16661 @group
16662    for Library_Dir use "lib_dir";
16663    for Library_Name use "dummy";
16664    for Library_Interface use ("int1", "int1.child");
16665 @end group
16666 @end smallexample
16668 @noindent
16669 Attribute @code{Library_Interface} has a non-empty string list value,
16670 each string in the list designating a unit contained in an immediate source
16671 of the project file.
16673 When a Stand-alone Library is built, first the binder is invoked to build
16674 a package whose name depends on the library name
16675 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16676 This binder-generated package includes initialization and
16677 finalization procedures whose
16678 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16679 in the example
16680 above). The object corresponding to this package is included in the library.
16682 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16683 calling of these procedures if a static SAL is built, or if a shared SAL
16684 is built
16685 with the project-level attribute @code{Library_Auto_Init} set to
16686 @code{"false"}.
16688 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16689 (those that are listed in attribute @code{Library_Interface}) are copied to
16690 the Library Directory. As a consequence, only the Interface Units may be
16691 imported from Ada units outside of the library. If other units are imported,
16692 the binding phase will fail.
16694 @noindent
16695 It is also possible to build an encapsulated library where not only
16696 the code to elaborate and finalize the library is embedded but also
16697 ensuring that the library is linked only against static
16698 libraries. So an encapsulated library only depends on system
16699 libraries, all other code, including the GNAT runtime, is embedded. To
16700 build an encapsulated library the attribute
16701 @code{Library_Standalone} must be set to @code{encapsulated}:
16703 @smallexample @c projectfile
16704 @group
16705    for Library_Dir use "lib_dir";
16706    for Library_Name use "dummy";
16707    for Library_Interface use ("int1", "int1.child");
16708    for Library_Standalone use "encapsulated";
16709 @end group
16710 @end smallexample
16712 @noindent
16713 The default value for this attribute is @code{standard} in which case
16714 a stand-alone library is built.
16716 The attribute @code{Library_Src_Dir} may be specified for a
16717 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16718 single string value. Its value must be the path (absolute or relative to the
16719 project directory) of an existing directory. This directory cannot be the
16720 object directory or one of the source directories, but it can be the same as
16721 the library directory. The sources of the Interface
16722 Units of the library that are needed by an Ada client of the library will be
16723 copied to the designated directory, called the Interface Copy directory.
16724 These sources include the specs of the Interface Units, but they may also
16725 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16726 are used, or when there is a generic unit in the spec. Before the sources
16727 are copied to the Interface Copy directory, an attempt is made to delete all
16728 files in the Interface Copy directory.
16730 Building stand-alone libraries by hand is somewhat tedious, but for those
16731 occasions when it is necessary here are the steps that you need to perform:
16732 @itemize @bullet
16733 @item
16734 Compile all library sources.
16736 @item
16737 Invoke the binder with the switch @option{-n} (No Ada main program),
16738 with all the @file{ALI} files of the interfaces, and
16739 with the switch @option{-L} to give specific names to the @code{init}
16740 and @code{final} procedures.  For example:
16741 @smallexample
16742   gnatbind -n int1.ali int2.ali -Lsal1
16743 @end smallexample
16745 @item
16746 Compile the binder generated file:
16747 @smallexample
16748   gcc -c b~int2.adb
16749 @end smallexample
16751 @item
16752 Link the dynamic library with all the necessary object files,
16753 indicating to the linker the names of the @code{init} (and possibly
16754 @code{final}) procedures for automatic initialization (and finalization).
16755 The built library should be placed in a directory different from
16756 the object directory.
16758 @item
16759 Copy the @code{ALI} files of the interface to the library directory,
16760 add in this copy an indication that it is an interface to a SAL
16761 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16762 with letter ``P'') and make the modified copy of the @file{ALI} file
16763 read-only.
16764 @end itemize
16766 @noindent
16767 Using SALs is not different from using other libraries
16768 (see @ref{Using a library}).
16770 @node Creating a Stand-alone Library to be used in a non-Ada context
16771 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16773 @noindent
16774 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16775 a non-Ada context.
16777 The only extra step required is to ensure that library interface subprograms
16778 are compatible with the main program, by means of @code{pragma Export}
16779 or @code{pragma Convention}.
16781 Here is an example of simple library interface for use with C main program:
16783 @smallexample @c ada
16784 package My_Package is
16786    procedure Do_Something;
16787    pragma Export (C, Do_Something, "do_something");
16789    procedure Do_Something_Else;
16790    pragma Export (C, Do_Something_Else, "do_something_else");
16792 end My_Package;
16793 @end smallexample
16795 @noindent
16796 On the foreign language side, you must provide a ``foreign'' view of the
16797 library interface; remember that it should contain elaboration routines in
16798 addition to interface subprograms.
16800 The example below shows the content of @code{mylib_interface.h} (note
16801 that there is no rule for the naming of this file, any name can be used)
16802 @smallexample
16803 /* the library elaboration procedure */
16804 extern void mylibinit (void);
16806 /* the library finalization procedure */
16807 extern void mylibfinal (void);
16809 /* the interface exported by the library */
16810 extern void do_something (void);
16811 extern void do_something_else (void);
16812 @end smallexample
16814 @noindent
16815 Libraries built as explained above can be used from any program, provided
16816 that the elaboration procedures (named @code{mylibinit} in the previous
16817 example) are called before the library services are used. Any number of
16818 libraries can be used simultaneously, as long as the elaboration
16819 procedure of each library is called.
16821 Below is an example of a C program that uses the @code{mylib} library.
16823 @smallexample
16824 #include "mylib_interface.h"
16827 main (void)
16829    /* First, elaborate the library before using it */
16830    mylibinit ();
16832    /* Main program, using the library exported entities */
16833    do_something ();
16834    do_something_else ();
16836    /* Library finalization at the end of the program */
16837    mylibfinal ();
16838    return 0;
16840 @end smallexample
16842 @noindent
16843 Note that invoking any library finalization procedure generated by
16844 @code{gnatbind} shuts down the Ada run-time environment.
16845 Consequently, the
16846 finalization of all Ada libraries must be performed at the end of the program.
16847 No call to these libraries or to the Ada run-time library should be made
16848 after the finalization phase.
16850 @node Restrictions in Stand-alone Libraries
16851 @subsection Restrictions in Stand-alone Libraries
16853 @noindent
16854 The pragmas listed below should be used with caution inside libraries,
16855 as they can create incompatibilities with other Ada libraries:
16856 @itemize @bullet
16857 @item pragma @code{Locking_Policy}
16858 @item pragma @code{Queuing_Policy}
16859 @item pragma @code{Task_Dispatching_Policy}
16860 @item pragma @code{Unreserve_All_Interrupts}
16861 @end itemize
16863 @noindent
16864 When using a library that contains such pragmas, the user must make sure
16865 that all libraries use the same pragmas with the same values. Otherwise,
16866 @code{Program_Error} will
16867 be raised during the elaboration of the conflicting
16868 libraries. The usage of these pragmas and its consequences for the user
16869 should therefore be well documented.
16871 Similarly, the traceback in the exception occurrence mechanism should be
16872 enabled or disabled in a consistent manner across all libraries.
16873 Otherwise, Program_Error will be raised during the elaboration of the
16874 conflicting libraries.
16876 If the @code{Version} or @code{Body_Version}
16877 attributes are used inside a library, then you need to
16878 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16879 libraries, so that version identifiers can be properly computed.
16880 In practice these attributes are rarely used, so this is unlikely
16881 to be a consideration.
16883 @node  Rebuilding the GNAT Run-Time Library
16884 @section Rebuilding the GNAT Run-Time Library
16885 @cindex GNAT Run-Time Library, rebuilding
16886 @cindex Building the GNAT Run-Time Library
16887 @cindex Rebuilding the GNAT Run-Time Library
16888 @cindex Run-Time Library, rebuilding
16890 @noindent
16891 It may be useful to recompile the GNAT library in various contexts, the
16892 most important one being the use of partition-wide configuration pragmas
16893 such as @code{Normalize_Scalars}. A special Makefile called
16894 @code{Makefile.adalib} is provided to that effect and can be found in
16895 the directory containing the GNAT library. The location of this
16896 directory depends on the way the GNAT environment has been installed and can
16897 be determined by means of the command:
16899 @smallexample
16900 $ gnatls -v
16901 @end smallexample
16903 @noindent
16904 The last entry in the object search path usually contains the
16905 gnat library. This Makefile contains its own documentation and in
16906 particular the set of instructions needed to rebuild a new library and
16907 to use it.
16909 @node Using the GNU make Utility
16910 @chapter Using the GNU @code{make} Utility
16911 @findex make
16913 @noindent
16914 This chapter offers some examples of makefiles that solve specific
16915 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16916 make, make, GNU @code{make}}), nor does it try to replace the
16917 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16919 All the examples in this section are specific to the GNU version of
16920 make. Although @command{make} is a standard utility, and the basic language
16921 is the same, these examples use some advanced features found only in
16922 @code{GNU make}.
16924 @menu
16925 * Using gnatmake in a Makefile::
16926 * Automatically Creating a List of Directories::
16927 * Generating the Command Line Switches::
16928 * Overcoming Command Line Length Limits::
16929 @end menu
16931 @node Using gnatmake in a Makefile
16932 @section Using gnatmake in a Makefile
16933 @findex makefile
16934 @cindex GNU make
16936 @noindent
16937 Complex project organizations can be handled in a very powerful way by
16938 using GNU make combined with gnatmake. For instance, here is a Makefile
16939 which allows you to build each subsystem of a big project into a separate
16940 shared library. Such a makefile allows you to significantly reduce the link
16941 time of very big applications while maintaining full coherence at
16942 each step of the build process.
16944 The list of dependencies are handled automatically by
16945 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16946 the appropriate directories.
16948 Note that you should also read the example on how to automatically
16949 create the list of directories
16950 (@pxref{Automatically Creating a List of Directories})
16951 which might help you in case your project has a lot of subdirectories.
16953 @smallexample
16954 @iftex
16955 @leftskip=0cm
16956 @font@heightrm=cmr8
16957 @heightrm
16958 @end iftex
16959 ## This Makefile is intended to be used with the following directory
16960 ## configuration:
16961 ##  - The sources are split into a series of csc (computer software components)
16962 ##    Each of these csc is put in its own directory.
16963 ##    Their name are referenced by the directory names.
16964 ##    They will be compiled into shared library (although this would also work
16965 ##    with static libraries
16966 ##  - The main program (and possibly other packages that do not belong to any
16967 ##    csc is put in the top level directory (where the Makefile is).
16968 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16969 ##                    \_ second_csc (sources) __ lib (will contain the library)
16970 ##                    \_ @dots{}
16971 ## Although this Makefile is build for shared library, it is easy to modify
16972 ## to build partial link objects instead (modify the lines with -shared and
16973 ## gnatlink below)
16975 ## With this makefile, you can change any file in the system or add any new
16976 ## file, and everything will be recompiled correctly (only the relevant shared
16977 ## objects will be recompiled, and the main program will be re-linked).
16979 # The list of computer software component for your project. This might be
16980 # generated automatically.
16981 CSC_LIST=aa bb cc
16983 # Name of the main program (no extension)
16984 MAIN=main
16986 # If we need to build objects with -fPIC, uncomment the following line
16987 #NEED_FPIC=-fPIC
16989 # The following variable should give the directory containing libgnat.so
16990 # You can get this directory through 'gnatls -v'. This is usually the last
16991 # directory in the Object_Path.
16992 GLIB=@dots{}
16994 # The directories for the libraries
16995 # (This macro expands the list of CSC to the list of shared libraries, you
16996 # could simply use the expanded form:
16997 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16998 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17000 $@{MAIN@}: objects $@{LIB_DIR@}
17001     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17002     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17004 objects::
17005     # recompile the sources
17006     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17008 # Note: In a future version of GNAT, the following commands will be simplified
17009 # by a new tool, gnatmlib
17010 $@{LIB_DIR@}:
17011     mkdir -p $@{dir $@@ @}
17012     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17013     cd $@{dir $@@ @} && cp -f ../*.ali .
17015 # The dependencies for the modules
17016 # Note that we have to force the expansion of *.o, since in some cases
17017 # make won't be able to do it itself.
17018 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17019 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17020 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17022 # Make sure all of the shared libraries are in the path before starting the
17023 # program
17024 run::
17025     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17027 clean::
17028     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17029     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17030     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17031     $@{RM@} *.o *.ali $@{MAIN@}
17032 @end smallexample
17034 @node Automatically Creating a List of Directories
17035 @section Automatically Creating a List of Directories
17037 @noindent
17038 In most makefiles, you will have to specify a list of directories, and
17039 store it in a variable. For small projects, it is often easier to
17040 specify each of them by hand, since you then have full control over what
17041 is the proper order for these directories, which ones should be
17042 included.
17044 However, in larger projects, which might involve hundreds of
17045 subdirectories, it might be more convenient to generate this list
17046 automatically.
17048 The example below presents two methods. The first one, although less
17049 general, gives you more control over the list. It involves wildcard
17050 characters, that are automatically expanded by @command{make}. Its
17051 shortcoming is that you need to explicitly specify some of the
17052 organization of your project, such as for instance the directory tree
17053 depth, whether some directories are found in a separate tree, @enddots{}
17055 The second method is the most general one. It requires an external
17056 program, called @command{find}, which is standard on all Unix systems. All
17057 the directories found under a given root directory will be added to the
17058 list.
17060 @smallexample
17061 @iftex
17062 @leftskip=0cm
17063 @font@heightrm=cmr8
17064 @heightrm
17065 @end iftex
17066 # The examples below are based on the following directory hierarchy:
17067 # All the directories can contain any number of files
17068 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17069 #                       ->  ab
17070 #                       ->  ac
17071 #                ->  b  ->  ba  ->  baa
17072 #                       ->  bb
17073 #                       ->  bc
17074 # This Makefile creates a variable called DIRS, that can be reused any time
17075 # you need this list (see the other examples in this section)
17077 # The root of your project's directory hierarchy
17078 ROOT_DIRECTORY=.
17080 ####
17081 # First method: specify explicitly the list of directories
17082 # This allows you to specify any subset of all the directories you need.
17083 ####
17085 DIRS := a/aa/ a/ab/ b/ba/
17087 ####
17088 # Second method: use wildcards
17089 # Note that the argument(s) to wildcard below should end with a '/'.
17090 # Since wildcards also return file names, we have to filter them out
17091 # to avoid duplicate directory names.
17092 # We thus use make's @code{dir} and @code{sort} functions.
17093 # It sets DIRs to the following value (note that the directories aaa and baa
17094 # are not given, unless you change the arguments to wildcard).
17095 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17096 ####
17098 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17099                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17101 ####
17102 # Third method: use an external program
17103 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17104 # This is the most complete command: it sets DIRs to the following value:
17105 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17106 ####
17108 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17110 @end smallexample
17112 @node Generating the Command Line Switches
17113 @section Generating the Command Line Switches
17115 @noindent
17116 Once you have created the list of directories as explained in the
17117 previous section (@pxref{Automatically Creating a List of Directories}),
17118 you can easily generate the command line arguments to pass to gnatmake.
17120 For the sake of completeness, this example assumes that the source path
17121 is not the same as the object path, and that you have two separate lists
17122 of directories.
17124 @smallexample
17125 # see "Automatically creating a list of directories" to create
17126 # these variables
17127 SOURCE_DIRS=
17128 OBJECT_DIRS=
17130 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17131 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17133 all:
17134         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17135 @end smallexample
17137 @node Overcoming Command Line Length Limits
17138 @section Overcoming Command Line Length Limits
17140 @noindent
17141 One problem that might be encountered on big projects is that many
17142 operating systems limit the length of the command line. It is thus hard to give
17143 gnatmake the list of source and object directories.
17145 This example shows how you can set up environment variables, which will
17146 make @command{gnatmake} behave exactly as if the directories had been
17147 specified on the command line, but have a much higher length limit (or
17148 even none on most systems).
17150 It assumes that you have created a list of directories in your Makefile,
17151 using one of the methods presented in
17152 @ref{Automatically Creating a List of Directories}.
17153 For the sake of completeness, we assume that the object
17154 path (where the ALI files are found) is different from the sources patch.
17156 Note a small trick in the Makefile below: for efficiency reasons, we
17157 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17158 expanded immediately by @code{make}. This way we overcome the standard
17159 make behavior which is to expand the variables only when they are
17160 actually used.
17162 On Windows, if you are using the standard Windows command shell, you must
17163 replace colons with semicolons in the assignments to these variables.
17165 @smallexample
17166 @iftex
17167 @leftskip=0cm
17168 @font@heightrm=cmr8
17169 @heightrm
17170 @end iftex
17171 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17172 # This is the same thing as putting the -I arguments on the command line.
17173 # (the equivalent of using -aI on the command line would be to define
17174 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17175 # You can of course have different values for these variables.
17177 # Note also that we need to keep the previous values of these variables, since
17178 # they might have been set before running 'make' to specify where the GNAT
17179 # library is installed.
17181 # see "Automatically creating a list of directories" to create these
17182 # variables
17183 SOURCE_DIRS=
17184 OBJECT_DIRS=
17186 empty:=
17187 space:=$@{empty@} $@{empty@}
17188 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17189 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17190 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17191 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17192 export ADA_INCLUDE_PATH
17193 export ADA_OBJECTS_PATH
17195 all:
17196         gnatmake main_unit
17197 @end smallexample
17198 @end ifclear
17200 @node Memory Management Issues
17201 @chapter Memory Management Issues
17203 @noindent
17204 This chapter describes some useful memory pools provided in the GNAT library
17205 and in particular the GNAT Debug Pool facility, which can be used to detect
17206 incorrect uses of access values (including ``dangling references'').
17207 @ifclear vms
17208 It also describes the @command{gnatmem} tool, which can be used to track down
17209 ``memory leaks''.
17210 @end ifclear
17212 @menu
17213 * Some Useful Memory Pools::
17214 * The GNAT Debug Pool Facility::
17215 @ifclear vms
17216 * The gnatmem Tool::
17217 @end ifclear
17218 @end menu
17220 @node Some Useful Memory Pools
17221 @section Some Useful Memory Pools
17222 @findex Memory Pool
17223 @cindex storage, pool
17225 @noindent
17226 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17227 storage pool. Allocations use the standard system call @code{malloc} while
17228 deallocations use the standard system call @code{free}. No reclamation is
17229 performed when the pool goes out of scope. For performance reasons, the
17230 standard default Ada allocators/deallocators do not use any explicit storage
17231 pools but if they did, they could use this storage pool without any change in
17232 behavior. That is why this storage pool is used  when the user
17233 manages to make the default implicit allocator explicit as in this example:
17234 @smallexample @c ada
17235    type T1 is access Something;
17236     -- no Storage pool is defined for T2
17237    type T2 is access Something_Else;
17238    for T2'Storage_Pool use T1'Storage_Pool;
17239    -- the above is equivalent to
17240    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17241 @end smallexample
17243 @noindent
17244 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17245 pool. The allocation strategy is similar to @code{Pool_Local}'s
17246 except that the all
17247 storage allocated with this pool is reclaimed when the pool object goes out of
17248 scope. This pool provides a explicit mechanism similar to the implicit one
17249 provided by several Ada 83 compilers for allocations performed through a local
17250 access type and whose purpose was to reclaim memory when exiting the
17251 scope of a given local access. As an example, the following program does not
17252 leak memory even though it does not perform explicit deallocation:
17254 @smallexample @c ada
17255 with System.Pool_Local;
17256 procedure Pooloc1 is
17257    procedure Internal is
17258       type A is access Integer;
17259       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17260       for A'Storage_Pool use X;
17261       v : A;
17262    begin
17263       for I in  1 .. 50 loop
17264          v := new Integer;
17265       end loop;
17266    end Internal;
17267 begin
17268    for I in  1 .. 100 loop
17269       Internal;
17270    end loop;
17271 end Pooloc1;
17272 @end smallexample
17274 @noindent
17275 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17276 @code{Storage_Size} is specified for an access type.
17277 The whole storage for the pool is
17278 allocated at once, usually on the stack at the point where the access type is
17279 elaborated. It is automatically reclaimed when exiting the scope where the
17280 access type is defined. This package is not intended to be used directly by the
17281 user and it is implicitly used for each such declaration:
17283 @smallexample @c ada
17284    type T1 is access Something;
17285    for T1'Storage_Size use 10_000;
17286 @end smallexample
17288 @node The GNAT Debug Pool Facility
17289 @section The GNAT Debug Pool Facility
17290 @findex Debug Pool
17291 @cindex storage, pool, memory corruption
17293 @noindent
17294 The use of unchecked deallocation and unchecked conversion can easily
17295 lead to incorrect memory references. The problems generated by such
17296 references are usually difficult to tackle because the symptoms can be
17297 very remote from the origin of the problem. In such cases, it is
17298 very helpful to detect the problem as early as possible. This is the
17299 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17301 In order to use the GNAT specific debugging pool, the user must
17302 associate a debug pool object with each of the access types that may be
17303 related to suspected memory problems. See Ada Reference Manual 13.11.
17304 @smallexample @c ada
17305 type Ptr is access Some_Type;
17306 Pool : GNAT.Debug_Pools.Debug_Pool;
17307 for Ptr'Storage_Pool use Pool;
17308 @end smallexample
17310 @noindent
17311 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17312 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17313 allow the user to redefine allocation and deallocation strategies. They
17314 also provide a checkpoint for each dereference, through the use of
17315 the primitive operation @code{Dereference} which is implicitly called at
17316 each dereference of an access value.
17318 Once an access type has been associated with a debug pool, operations on
17319 values of the type may raise four distinct exceptions,
17320 which correspond to four potential kinds of memory corruption:
17321 @itemize @bullet
17322 @item
17323 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17324 @item
17325 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17326 @item
17327 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17328 @item
17329 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17330 @end itemize
17332 @noindent
17333 For types associated with a Debug_Pool, dynamic allocation is performed using
17334 the standard GNAT allocation routine. References to all allocated chunks of
17335 memory are kept in an internal dictionary. Several deallocation strategies are
17336 provided, whereupon the user can choose to release the memory to the system,
17337 keep it allocated for further invalid access checks, or fill it with an easily
17338 recognizable pattern for debug sessions. The memory pattern is the old IBM
17339 hexadecimal convention: @code{16#DEADBEEF#}.
17341 See the documentation in the file g-debpoo.ads for more information on the
17342 various strategies.
17344 Upon each dereference, a check is made that the access value denotes a
17345 properly allocated memory location. Here is a complete example of use of
17346 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17347 @smallexample @c ada
17348 @iftex
17349 @leftskip=0cm
17350 @end iftex
17351 with Gnat.Io; use Gnat.Io;
17352 with Unchecked_Deallocation;
17353 with Unchecked_Conversion;
17354 with GNAT.Debug_Pools;
17355 with System.Storage_Elements;
17356 with Ada.Exceptions; use Ada.Exceptions;
17357 procedure Debug_Pool_Test is
17359    type T is access Integer;
17360    type U is access all T;
17362    P : GNAT.Debug_Pools.Debug_Pool;
17363    for T'Storage_Pool use P;
17365    procedure Free is new Unchecked_Deallocation (Integer, T);
17366    function UC is new Unchecked_Conversion (U, T);
17367    A, B : aliased T;
17369    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17371 begin
17372    Info (P);
17373    A := new Integer;
17374    B := new Integer;
17375    B := A;
17376    Info (P);
17377    Free (A);
17378    begin
17379       Put_Line (Integer'Image(B.all));
17380    exception
17381       when E : others => Put_Line ("raised: " & Exception_Name (E));
17382    end;
17383    begin
17384       Free (B);
17385    exception
17386       when E : others => Put_Line ("raised: " & Exception_Name (E));
17387    end;
17388    B := UC(A'Access);
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    Info (P);
17400 end Debug_Pool_Test;
17401 @end smallexample
17403 @noindent
17404 The debug pool mechanism provides the following precise diagnostics on the
17405 execution of this erroneous program:
17406 @smallexample
17407 Debug Pool info:
17408   Total allocated bytes :  0
17409   Total deallocated bytes :  0
17410   Current Water Mark:  0
17411   High Water Mark:  0
17413 Debug Pool info:
17414   Total allocated bytes :  8
17415   Total deallocated bytes :  0
17416   Current Water Mark:  8
17417   High Water Mark:  8
17419 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17420 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17421 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17422 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17423 Debug Pool info:
17424   Total allocated bytes :  8
17425   Total deallocated bytes :  4
17426   Current Water Mark:  4
17427   High Water Mark:  8
17428 @end smallexample
17430 @ifclear vms
17431 @node The gnatmem Tool
17432 @section The @command{gnatmem} Tool
17433 @findex gnatmem
17435 @noindent
17436 The @code{gnatmem} utility monitors dynamic allocation and
17437 deallocation activity in a program, and displays information about
17438 incorrect deallocations and possible sources of memory leaks.
17439 It is designed to work in association with a static runtime library
17440 only and in this context provides three types of information:
17441 @itemize @bullet
17442 @item
17443 General information concerning memory management, such as the total
17444 number of allocations and deallocations, the amount of allocated
17445 memory and the high water mark, i.e.@: the largest amount of allocated
17446 memory in the course of program execution.
17448 @item
17449 Backtraces for all incorrect deallocations, that is to say deallocations
17450 which do not correspond to a valid allocation.
17452 @item
17453 Information on each allocation that is potentially the origin of a memory
17454 leak.
17455 @end itemize
17457 @menu
17458 * Running gnatmem::
17459 * Switches for gnatmem::
17460 * Example of gnatmem Usage::
17461 @end menu
17463 @node Running gnatmem
17464 @subsection Running @code{gnatmem}
17466 @noindent
17467 @code{gnatmem} makes use of the output created by the special version of
17468 allocation and deallocation routines that record call information. This
17469 allows to obtain accurate dynamic memory usage history at a minimal cost to
17470 the execution speed. Note however, that @code{gnatmem} is not supported on
17471 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17472 Solaris and Windows NT/2000/XP (x86).
17474 @noindent
17475 The @code{gnatmem} command has the form
17477 @smallexample
17478 @c    $ gnatmem @ovar{switches} user_program
17479 @c Expanding @ovar macro inline (explanation in macro def comments)
17480       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17481 @end smallexample
17483 @noindent
17484 The program must have been linked with the instrumented version of the
17485 allocation and deallocation routines. This is done by linking with the
17486 @file{libgmem.a} library. For correct symbolic backtrace information,
17487 the user program should be compiled with debugging options
17488 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17490 @smallexample
17491 $ gnatmake -g my_program -largs -lgmem
17492 @end smallexample
17494 @noindent
17495 As library @file{libgmem.a} contains an alternate body for package
17496 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17497 when an executable is linked with library @file{libgmem.a}. It is then not
17498 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17500 @noindent
17501 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17502 This file contains information about all allocations and deallocations
17503 performed by the program. It is produced by the instrumented allocations and
17504 deallocations routines and will be used by @code{gnatmem}.
17506 In order to produce symbolic backtrace information for allocations and
17507 deallocations performed by the GNAT run-time library, you need to use a
17508 version of that library that has been compiled with the @option{-g} switch
17509 (see @ref{Rebuilding the GNAT Run-Time Library}).
17511 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17512 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17513 @option{-i} switch, gnatmem will assume that this file can be found in the
17514 current directory. For example, after you have executed @file{my_program},
17515 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17517 @smallexample
17518 $ gnatmem my_program
17519 @end smallexample
17521 @noindent
17522 This will produce the output with the following format:
17524 *************** debut cc
17525 @smallexample
17526 $ gnatmem my_program
17528 Global information
17529 ------------------
17530    Total number of allocations        :  45
17531    Total number of deallocations      :   6
17532    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17533    High Water Mark                    :  11.40 Kilobytes
17538 Allocation Root # 2
17539 -------------------
17540  Number of non freed allocations    :  11
17541  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17542  High Water Mark                    :   1.27 Kilobytes
17543  Backtrace                          :
17544    my_program.adb:23 my_program.alloc
17548 @end smallexample
17550 The first block of output gives general information. In this case, the
17551 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17552 Unchecked_Deallocation routine occurred.
17554 @noindent
17555 Subsequent paragraphs display  information on all allocation roots.
17556 An allocation root is a specific point in the execution of the program
17557 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17558 construct. This root is represented by an execution backtrace (or subprogram
17559 call stack). By default the backtrace depth for allocations roots is 1, so
17560 that a root corresponds exactly to a source location. The backtrace can
17561 be made deeper, to make the root more specific.
17563 @node Switches for gnatmem
17564 @subsection Switches for @code{gnatmem}
17566 @noindent
17567 @code{gnatmem} recognizes the following switches:
17569 @table @option
17571 @item -q
17572 @cindex @option{-q} (@code{gnatmem})
17573 Quiet. Gives the minimum output needed to identify the origin of the
17574 memory leaks. Omits statistical information.
17576 @item @var{N}
17577 @cindex @var{N} (@code{gnatmem})
17578 N is an integer literal (usually between 1 and 10) which controls the
17579 depth of the backtraces defining allocation root. The default value for
17580 N is 1. The deeper the backtrace, the more precise the localization of
17581 the root. Note that the total number of roots can depend on this
17582 parameter. This parameter must be specified @emph{before} the name of the
17583 executable to be analyzed, to avoid ambiguity.
17585 @item -b n
17586 @cindex @option{-b} (@code{gnatmem})
17587 This switch has the same effect as just depth parameter.
17589 @item -i @var{file}
17590 @cindex @option{-i} (@code{gnatmem})
17591 Do the @code{gnatmem} processing starting from @file{file}, rather than
17592 @file{gmem.out} in the current directory.
17594 @item -m n
17595 @cindex @option{-m} (@code{gnatmem})
17596 This switch causes @code{gnatmem} to mask the allocation roots that have less
17597 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17598 examine even the roots that didn't result in leaks.
17600 @item -s order
17601 @cindex @option{-s} (@code{gnatmem})
17602 This switch causes @code{gnatmem} to sort the allocation roots according to the
17603 specified order of sort criteria, each identified by a single letter. The
17604 currently supported criteria are @code{n, h, w} standing respectively for
17605 number of unfreed allocations, high watermark, and final watermark
17606 corresponding to a specific root. The default order is @code{nwh}.
17608 @end table
17610 @node Example of gnatmem Usage
17611 @subsection Example of @code{gnatmem} Usage
17613 @noindent
17614 The following example shows the use of @code{gnatmem}
17615 on a simple memory-leaking program.
17616 Suppose that we have the following Ada program:
17618 @smallexample @c ada
17619 @group
17620 @cartouche
17621 with Unchecked_Deallocation;
17622 procedure Test_Gm is
17624    type T is array (1..1000) of Integer;
17625    type Ptr is access T;
17626    procedure Free is new Unchecked_Deallocation (T, Ptr);
17627    A : Ptr;
17629    procedure My_Alloc is
17630    begin
17631       A := new T;
17632    end My_Alloc;
17634    procedure My_DeAlloc is
17635       B : Ptr := A;
17636    begin
17637       Free (B);
17638    end My_DeAlloc;
17640 begin
17641    My_Alloc;
17642    for I in 1 .. 5 loop
17643       for J in I .. 5 loop
17644          My_Alloc;
17645       end loop;
17646       My_Dealloc;
17647    end loop;
17648 end;
17649 @end cartouche
17650 @end group
17651 @end smallexample
17653 @noindent
17654 The program needs to be compiled with debugging option and linked with
17655 @code{gmem} library:
17657 @smallexample
17658 $ gnatmake -g test_gm -largs -lgmem
17659 @end smallexample
17661 @noindent
17662 Then we execute the program as usual:
17664 @smallexample
17665 $ test_gm
17666 @end smallexample
17668 @noindent
17669 Then @code{gnatmem} is invoked simply with
17670 @smallexample
17671 $ gnatmem test_gm
17672 @end smallexample
17674 @noindent
17675 which produces the following output (result may vary on different platforms):
17677 @smallexample
17678 Global information
17679 ------------------
17680    Total number of allocations        :  18
17681    Total number of deallocations      :   5
17682    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17683    High Water Mark                    :  56.90 Kilobytes
17685 Allocation Root # 1
17686 -------------------
17687  Number of non freed allocations    :  11
17688  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17689  High Water Mark                    :  46.88 Kilobytes
17690  Backtrace                          :
17691    test_gm.adb:11 test_gm.my_alloc
17693 Allocation Root # 2
17694 -------------------
17695  Number of non freed allocations    :   1
17696  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17697  High Water Mark                    :  10.02 Kilobytes
17698  Backtrace                          :
17699    s-secsta.adb:81 system.secondary_stack.ss_init
17701 Allocation Root # 3
17702 -------------------
17703  Number of non freed allocations    :   1
17704  Final Water Mark (non freed mem)   :  12 Bytes
17705  High Water Mark                    :  12 Bytes
17706  Backtrace                          :
17707    s-secsta.adb:181 system.secondary_stack.ss_init
17708 @end smallexample
17710 @noindent
17711 Note that the GNAT run time contains itself a certain number of
17712 allocations that have no  corresponding deallocation,
17713 as shown here for root #2 and root
17714 #3. This is a normal behavior when the number of non-freed allocations
17715 is one, it allocates dynamic data structures that the run time needs for
17716 the complete lifetime of the program. Note also that there is only one
17717 allocation root in the user program with a single line back trace:
17718 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17719 program shows that 'My_Alloc' is called at 2 different points in the
17720 source (line 21 and line 24). If those two allocation roots need to be
17721 distinguished, the backtrace depth parameter can be used:
17723 @smallexample
17724 $ gnatmem 3 test_gm
17725 @end smallexample
17727 @noindent
17728 which will give the following output:
17730 @smallexample
17731 Global information
17732 ------------------
17733    Total number of allocations        :  18
17734    Total number of deallocations      :   5
17735    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17736    High Water Mark                    :  56.90 Kilobytes
17738 Allocation Root # 1
17739 -------------------
17740  Number of non freed allocations    :  10
17741  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17742  High Water Mark                    :  42.97 Kilobytes
17743  Backtrace                          :
17744    test_gm.adb:11 test_gm.my_alloc
17745    test_gm.adb:24 test_gm
17746    b_test_gm.c:52 main
17748 Allocation Root # 2
17749 -------------------
17750  Number of non freed allocations    :   1
17751  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17752  High Water Mark                    :  10.02 Kilobytes
17753  Backtrace                          :
17754    s-secsta.adb:81  system.secondary_stack.ss_init
17755    s-secsta.adb:283 <system__secondary_stack___elabb>
17756    b_test_gm.c:33   adainit
17758 Allocation Root # 3
17759 -------------------
17760  Number of non freed allocations    :   1
17761  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17762  High Water Mark                    :   3.91 Kilobytes
17763  Backtrace                          :
17764    test_gm.adb:11 test_gm.my_alloc
17765    test_gm.adb:21 test_gm
17766    b_test_gm.c:52 main
17768 Allocation Root # 4
17769 -------------------
17770  Number of non freed allocations    :   1
17771  Final Water Mark (non freed mem)   :  12 Bytes
17772  High Water Mark                    :  12 Bytes
17773  Backtrace                          :
17774    s-secsta.adb:181 system.secondary_stack.ss_init
17775    s-secsta.adb:283 <system__secondary_stack___elabb>
17776    b_test_gm.c:33   adainit
17777 @end smallexample
17779 @noindent
17780 The allocation root #1 of the first example has been split in 2 roots #1
17781 and #3 thanks to the more precise associated backtrace.
17783 @end ifclear
17785 @node Stack Related Facilities
17786 @chapter Stack Related Facilities
17788 @noindent
17789 This chapter describes some useful tools associated with stack
17790 checking and analysis. In
17791 particular, it deals with dynamic and static stack usage measurements.
17793 @menu
17794 * Stack Overflow Checking::
17795 * Static Stack Usage Analysis::
17796 * Dynamic Stack Usage Analysis::
17797 @end menu
17799 @node Stack Overflow Checking
17800 @section Stack Overflow Checking
17801 @cindex Stack Overflow Checking
17802 @cindex -fstack-check
17804 @noindent
17805 For most operating systems, @command{gcc} does not perform stack overflow
17806 checking by default. This means that if the main environment task or
17807 some other task exceeds the available stack space, then unpredictable
17808 behavior will occur. Most native systems offer some level of protection by
17809 adding a guard page at the end of each task stack. This mechanism is usually
17810 not enough for dealing properly with stack overflow situations because
17811 a large local variable could ``jump'' above the guard page.
17812 Furthermore, when the
17813 guard page is hit, there may not be any space left on the stack for executing
17814 the exception propagation code. Enabling stack checking avoids
17815 such situations.
17817 To activate stack checking, compile all units with the gcc option
17818 @option{-fstack-check}. For example:
17820 @smallexample
17821 gcc -c -fstack-check package1.adb
17822 @end smallexample
17824 @noindent
17825 Units compiled with this option will generate extra instructions to check
17826 that any use of the stack (for procedure calls or for declaring local
17827 variables in declare blocks) does not exceed the available stack space.
17828 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17830 For declared tasks, the stack size is controlled by the size
17831 given in an applicable @code{Storage_Size} pragma or by the value specified
17832 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17833 the default size as defined in the GNAT runtime otherwise.
17835 For the environment task, the stack size depends on
17836 system defaults and is unknown to the compiler. Stack checking
17837 may still work correctly if a fixed
17838 size stack is allocated, but this cannot be guaranteed.
17839 @ifclear vms
17840 To ensure that a clean exception is signalled for stack
17841 overflow, set the environment variable
17842 @env{GNAT_STACK_LIMIT} to indicate the maximum
17843 stack area that can be used, as in:
17844 @cindex GNAT_STACK_LIMIT
17846 @smallexample
17847 SET GNAT_STACK_LIMIT 1600
17848 @end smallexample
17850 @noindent
17851 The limit is given in kilobytes, so the above declaration would
17852 set the stack limit of the environment task to 1.6 megabytes.
17853 Note that the only purpose of this usage is to limit the amount
17854 of stack used by the environment task. If it is necessary to
17855 increase the amount of stack for the environment task, then this
17856 is an operating systems issue, and must be addressed with the
17857 appropriate operating systems commands.
17858 @end ifclear
17859 @ifset vms
17860 To have a fixed size stack in the environment task, the stack must be put
17861 in the P0 address space and its size specified.  Use these switches to
17862 create a p0 image:
17864 @smallexample
17865 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17866 @end smallexample
17868 @noindent
17869 The quotes are required to keep case.  The number after @samp{STACK=} is the
17870 size of the environmental task stack in pagelets (512 bytes).  In this example
17871 the stack size is about 2 megabytes.
17873 @noindent
17874 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17875 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17876 more details about the @option{/p0image} qualifier and the @option{stack}
17877 option.
17879 @noindent
17880 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17881 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17882 stack in kilobytes.  For example:
17884 @smallexample
17885 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17886 @end smallexample
17887 @end ifset
17889 @node Static Stack Usage Analysis
17890 @section Static Stack Usage Analysis
17891 @cindex Static Stack Usage Analysis
17892 @cindex -fstack-usage
17894 @noindent
17895 A unit compiled with @option{-fstack-usage} will generate an extra file
17896 that specifies
17897 the maximum amount of stack used, on a per-function basis.
17898 The file has the same
17899 basename as the target object file with a @file{.su} extension.
17900 Each line of this file is made up of three fields:
17902 @itemize
17903 @item
17904 The name of the function.
17905 @item
17906 A number of bytes.
17907 @item
17908 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17909 @end itemize
17911 The second field corresponds to the size of the known part of the function
17912 frame.
17914 The qualifier @code{static} means that the function frame size
17915 is purely static.
17916 It usually means that all local variables have a static size.
17917 In this case, the second field is a reliable measure of the function stack
17918 utilization.
17920 The qualifier @code{dynamic} means that the function frame size is not static.
17921 It happens mainly when some local variables have a dynamic size. When this
17922 qualifier appears alone, the second field is not a reliable measure
17923 of the function stack analysis. When it is qualified with  @code{bounded}, it
17924 means that the second field is a reliable maximum of the function stack
17925 utilization.
17927 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17928 subprogram whose stack usage might be larger than the specified amount of
17929 bytes.  The wording is in keeping with the qualifier documented above.
17931 @node Dynamic Stack Usage Analysis
17932 @section Dynamic Stack Usage Analysis
17934 @noindent
17935 It is possible to measure the maximum amount of stack used by a task, by
17936 adding a switch to @command{gnatbind}, as:
17938 @smallexample
17939 $ gnatbind -u0 file
17940 @end smallexample
17942 @noindent
17943 With this option, at each task termination, its stack usage is  output on
17944 @file{stderr}.
17945 It is not always convenient to output the stack usage when the program
17946 is still running. Hence, it is possible to delay this output until program
17947 termination. for a given number of tasks specified as the argument of the
17948 @option{-u} option. For instance:
17950 @smallexample
17951 $ gnatbind -u100 file
17952 @end smallexample
17954 @noindent
17955 will buffer the stack usage information of the first 100 tasks to terminate and
17956 output this info at program termination. Results are displayed in four
17957 columns:
17959 @noindent
17960 Index | Task Name | Stack Size | Stack Usage
17962 @noindent
17963 where:
17965 @table @emph
17966 @item Index
17967 is a number associated with each task.
17969 @item Task Name
17970 is the name of the task analyzed.
17972 @item Stack Size
17973 is the maximum size for the stack.
17975 @item Stack Usage
17976 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17977 is not entirely analyzed, and it's not possible to know exactly how
17978 much has actually been used.
17980 @end table
17982 @noindent
17983 The environment task stack, e.g., the stack that contains the main unit, is
17984 only processed when the environment variable GNAT_STACK_LIMIT is set.
17986 @noindent
17987 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17988 stack usage reports at run-time. See its body for the details.
17990 @c *********************************
17991 @c *            GNATCHECK          *
17992 @c *********************************
17993 @node Verifying Properties Using gnatcheck
17994 @chapter Verifying Properties Using @command{gnatcheck}
17995 @findex gnatcheck
17996 @cindex @command{gnatcheck}
17998 @noindent
17999 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18000 of Ada source files according to a given set of semantic rules.
18001 @cindex ASIS
18003 In order to check compliance with a given rule, @command{gnatcheck} has to
18004 semantically analyze the Ada sources.
18005 Therefore, checks can only be performed on
18006 legal Ada units. Moreover, when a unit depends semantically upon units located
18007 outside the current directory, the source search path has to be provided when
18008 calling @command{gnatcheck}, either through a specified project file or
18009 through @command{gnatcheck} switches.
18011 For full details, refer to @cite{GNATcheck Reference Manual} document.
18014 @c *********************************
18015 @node Creating Sample Bodies Using gnatstub
18016 @chapter Creating Sample Bodies Using @command{gnatstub}
18017 @findex gnatstub
18019 @noindent
18020 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18021 for library unit declarations.
18023 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
18024 driver (see @ref{The GNAT Driver and Project Files}).
18026 To create a body stub, @command{gnatstub} has to compile the library
18027 unit declaration. Therefore, bodies can be created only for legal
18028 library units. Moreover, if a library unit depends semantically upon
18029 units located outside the current directory, you have to provide
18030 the source search path when calling @command{gnatstub}, see the description
18031 of @command{gnatstub} switches below.
18033 By default, all the program unit body stubs generated by @code{gnatstub}
18034 raise the predefined @code{Program_Error} exception, which will catch
18035 accidental calls of generated stubs. This behavior can be changed with
18036 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
18038 @menu
18039 * Running gnatstub::
18040 * Switches for gnatstub::
18041 @end menu
18043 @node Running gnatstub
18044 @section Running @command{gnatstub}
18046 @noindent
18047 @command{gnatstub} has a command-line interface of the form:
18049 @smallexample
18050 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
18051 @c Expanding @ovar macro inline (explanation in macro def comments)
18052 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18053 @end smallexample
18055 @noindent
18056 where
18057 @table @var
18058 @item filename
18059 is the name of the source file that contains a library unit declaration
18060 for which a body must be created. The file name may contain the path
18061 information.
18062 The file name does not have to follow the GNAT file name conventions. If the
18063 name
18064 does not follow GNAT file naming conventions, the name of the body file must
18065 be provided
18066 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18067 If the file name follows the GNAT file naming
18068 conventions and the name of the body file is not provided,
18069 @command{gnatstub}
18070 creates the name
18071 of the body file from the argument file name by replacing the @file{.ads}
18072 suffix
18073 with the @file{.adb} suffix.
18075 @item directory
18076 indicates the directory in which the body stub is to be placed (the default
18077 is the
18078 current directory)
18080 @item @samp{@var{gcc_switches}} is a list of switches for
18081 @command{gcc}. They will be passed on to all compiler invocations made by
18082 @command{gnatstub} to generate the ASIS trees. Here you can provide
18083 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18084 use the @option{-gnatec} switch to set the configuration file,
18085 use the @option{-gnat05} switch if sources should be compiled in
18086 Ada 2005 mode etc.
18088 @item switches
18089 is an optional sequence of switches as described in the next section
18090 @end table
18092 @node Switches for gnatstub
18093 @section Switches for @command{gnatstub}
18095 @table @option
18096 @c !sort!
18098 @item ^-f^/FULL^
18099 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18100 If the destination directory already contains a file with the name of the
18101 body file
18102 for the argument spec file, replace it with the generated body stub.
18104 @item ^-hs^/HEADER=SPEC^
18105 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18106 Put the comment header (i.e., all the comments preceding the
18107 compilation unit) from the source of the library unit declaration
18108 into the body stub.
18110 @item ^-hg^/HEADER=GENERAL^
18111 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18112 Put a sample comment header into the body stub.
18114 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
18115 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
18116 Use the content of the file as the comment header for a generated body stub.
18118 @ifclear vms
18119 @item -IDIR
18120 @cindex @option{-IDIR} (@command{gnatstub})
18121 @itemx -I-
18122 @cindex @option{-I-} (@command{gnatstub})
18123 @end ifclear
18124 @ifset vms
18125 @item /NOCURRENT_DIRECTORY
18126 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18127 @end ifset
18128 ^These switches have ^This switch has^ the same meaning as in calls to
18129 @command{gcc}.
18130 ^They define ^It defines ^ the source search path in the call to
18131 @command{gcc} issued
18132 by @command{gnatstub} to compile an argument source file.
18134 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18135 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18136 This switch has the same meaning as in calls to @command{gcc}.
18137 It defines the additional configuration file to be passed to the call to
18138 @command{gcc} issued
18139 by @command{gnatstub} to compile an argument source file.
18141 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18142 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18143 (@var{n} is a non-negative integer). Set the maximum line length in the
18144 body stub to @var{n}; the default is 79. The maximum value that can be
18145 specified is 32767. Note that in the special case of configuration
18146 pragma files, the maximum is always 32767 regardless of whether or
18147 not this switch appears.
18149 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18150 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18151 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18152 the generated body sample to @var{n}.
18153 The default indentation is 3.
18155 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18156 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18157 Order local bodies alphabetically. (By default local bodies are ordered
18158 in the same way as the corresponding local specs in the argument spec file.)
18160 @item ^-i^/INDENTATION=^@var{n}
18161 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18162 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18164 @item ^-k^/TREE_FILE=SAVE^
18165 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18166 Do not remove the tree file (i.e., the snapshot of the compiler internal
18167 structures used by @command{gnatstub}) after creating the body stub.
18169 @item ^-l^/LINE_LENGTH=^@var{n}
18170 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18171 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18173 @item ^--no-exception^/NO_EXCEPTION^
18174 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
18175 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18176 This is not always possible for function stubs.
18178 @item ^--no-local-header^/NO_LOCAL_HEADER^
18179 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
18180 Do not place local comment header with unit name before body stub for a
18181 unit.
18183 @item ^-o ^/BODY=^@var{body-name}
18184 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18185 Body file name.  This should be set if the argument file name does not
18186 follow
18187 the GNAT file naming
18188 conventions. If this switch is omitted the default name for the body will be
18189 obtained
18190 from the argument file name according to the GNAT file naming conventions.
18192 @item ^-q^/QUIET^
18193 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18194 Quiet mode: do not generate a confirmation when a body is
18195 successfully created, and do not generate a message when a body is not
18196 required for an
18197 argument unit.
18199 @item ^-r^/TREE_FILE=REUSE^
18200 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18201 Reuse the tree file (if it exists) instead of creating it.  Instead of
18202 creating the tree file for the library unit declaration, @command{gnatstub}
18203 tries to find it in the current directory and use it for creating
18204 a body. If the tree file is not found, no body is created. This option
18205 also implies @option{^-k^/SAVE^}, whether or not
18206 the latter is set explicitly.
18208 @item ^-t^/TREE_FILE=OVERWRITE^
18209 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18210 Overwrite the existing tree file.  If the current directory already
18211 contains the file which, according to the GNAT file naming rules should
18212 be considered as a tree file for the argument source file,
18213 @command{gnatstub}
18214 will refuse to create the tree file needed to create a sample body
18215 unless this option is set.
18217 @item ^-v^/VERBOSE^
18218 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18219 Verbose mode: generate version information.
18221 @end table
18223 @c *********************************
18224 @node Creating Unit Tests Using gnattest
18225 @chapter Creating Unit Tests Using @command{gnattest}
18226 @findex gnattest
18228 @noindent
18229 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18230 as well as a test driver infrastructure (harness). @command{gnattest} creates
18231 a skeleton for each visible subprogram in the packages under consideration when
18232 they do not exist already.
18234 In order to process source files from a project, @command{gnattest} has to
18235 semantically analyze the sources. Therefore, test skeletons can only be
18236 generated for legal Ada units. If a unit is dependent on other units,
18237 those units should be among the source files of the project or of other projects
18238 imported by this one.
18240 Generated skeletons and harnesses are based on the AUnit testing framework.
18241 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18242 for Java or CppUnit for C++. While it is advised that gnattest users read
18243 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18244 For correct operation of @command{gnattest}, AUnit should be installed and
18245 aunit.gpr must be on the project path. This happens automatically when Aunit
18246 is installed at its default location.
18247 @menu
18248 * Running gnattest::
18249 * Switches for gnattest::
18250 * Project Attributes for gnattest::
18251 * Simple Example::
18252 * Setting Up and Tearing Down the Testing Environment::
18253 * Regenerating Tests::
18254 * Default Test Behavior::
18255 * Testing Primitive Operations of Tagged Types::
18256 * Testing Inheritance::
18257 * Tagged Types Substitutability Testing::
18258 * Testing with Contracts::
18259 * Additional Tests::
18260 @ifclear vms
18261 * Support for other platforms/run-times::
18262 @end ifclear
18263 * Current Limitations::
18264 @end menu
18266 @node Running gnattest
18267 @section Running @command{gnattest}
18269 @noindent
18270 @command{gnattest} has a command-line interface of the form
18272 @smallexample
18273 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
18274 @c Expanding @ovar macro inline (explanation in macro def comments)
18275 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18276 @end smallexample
18278 @noindent
18279 where
18280 @table @var
18282 @item -Pprojname
18283 specifies the project defining the location of source files. When no
18284 file names are provided on the command line, all sources in the project
18285 are used as input. This switch is required.
18287 @item filename
18288 is the name of the source file containing the library unit package declaration
18289 for which a test package will be created. The file name may be given with a
18290 path.
18292 @item @samp{@var{gcc_switches}}
18293 is a list of switches for
18294 @command{gcc}. These switches will be passed on to all compiler invocations
18295 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
18296 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18297 use the @option{-gnatec} switch to set the configuration file,
18298 use the @option{-gnat05} switch if sources should be compiled in
18299 Ada 2005 mode, etc.
18301 @item switches
18302 is an optional sequence of switches as described in the next section.
18304 @end table
18306 @command{gnattest} results can be found in two different places.
18308 @itemize @bullet
18309 @item automatic harness:
18310 the harness code, which is located by default in "gnattest/harness" directory
18311 that is created in the object directory of corresponding project file. All of
18312 this code is generated completely automatically and can be destroyed and
18313 regenerated at will. It is not recommended to modify this code manually, since
18314 it could easily be overridden by mistake. The entry point in the harness code is
18315 the project file named @command{test_driver.gpr}. Tests can be compiled and run
18316 using a command such as:
18318 @smallexample
18319 gnatmake -P<harness-dir>/test_driver
18320 test_runner
18321 @end smallexample
18323 Note that you might need to specify the necessary values of scenario variables
18324 when you are not using the AUnit defaults.
18326 @item actual unit test skeletons:
18327 a test skeleton for each visible subprogram is created in a separate file, if it
18328 doesn't exist already. By default, those separate test files are located in a
18329 "gnattest/tests" directory that is created in the object directory of
18330 corresponding project file. For example, if a source file my_unit.ads in
18331 directory src contains a visible subprogram Proc, then the corresponding unit
18332 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
18333 <code> is a signature encoding used to differentiate test names in case of
18334 overloading.
18336 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
18337 this will cause a name conflict with the generated test package.
18338 @end itemize
18340 @node Switches for gnattest
18341 @section Switches for @command{gnattest}
18343 @table @option
18344 @c !sort!
18346 @item --harness-only
18347 @cindex @option{--harness-only} (@command{gnattest})
18348 When this option is given, @command{gnattest} creates a harness for all
18349 sources, treating them as test packages.
18351 @item --additional-tests=@var{projname}
18352 @cindex @option{--additional-tests} (@command{gnattest})
18353 Sources described in @var{projname} are considered potential additional
18354 manual tests to be added to the test suite.
18356 @item -r
18357 @cindex @option{-r} (@command{gnattest})
18358 Recursively consider all sources from all projects.
18360 @item -X@var{name=value}
18361 @cindex @option{-X} (@command{gnattest})
18362 Indicate that external variable @var{name} has the value @var{value}.
18364 @item -q
18365 @cindex @option{-q} (@command{gnattest})
18366 Suppresses noncritical output messages.
18368 @item -v
18369 @cindex @option{-v} (@command{gnattest})
18370 Verbose mode: generates version information.
18372 @item --validate-type-extensions
18373 @cindex @option{--validate-type-extensions} (@command{gnattest})
18374 Enables substitution check: run all tests from all parents in order
18375 to check substitutability.
18377 @item --skeleton-default=@var{val}
18378 @cindex @option{--skeleton-default} (@command{gnattest})
18379 Specifies the default behavior of generated skeletons. @var{val} can be either
18380 "fail" or "pass", "fail" being the default.
18382 @item --tests-root=@var{dirname}
18383 @cindex @option{--tests-root} (@command{gnattest})
18384 The directory hierarchy of tested sources is recreated in the @var{dirname}
18385 directory, and test packages are placed in corresponding directories.
18386 If the @var{dirname} is a relative path, it is considered relative to the object
18387 directory of the project file. When all sources from all projects are taken
18388 recursively from all projects, directory hierarchies of tested sources are
18389 recreated for each project in their object directories and test packages are
18390 placed accordingly.
18392 @item --subdir=@var{dirname}
18393 @cindex @option{--subdir} (@command{gnattest})
18394 Test packages are placed in subdirectories.
18396 @item --tests-dir=@var{dirname}
18397 @cindex @option{--tests-dir} (@command{gnattest})
18398 All test packages are placed in the @var{dirname} directory.
18399 If the @var{dirname} is a relative path, it is considered relative to the object
18400 directory of the project file. When all sources from all projects are taken
18401 recursively from all projects, @var{dirname} directories are created for each
18402 project in their object directories and test packages are placed accordingly.
18404 @item --harness-dir=@var{dirname}
18405 @cindex @option{--harness-dir} (@command{gnattest})
18406 specifies the directory that will hold the harness packages and project file
18407 for the test driver. If the @var{dirname} is a relative path, it is considered
18408 relative to the object directory of the project file.
18410 @item --separates
18411 @cindex @option{--separates} (@command{gnattest})
18412 Bodies of all test routines are generated as separates. Note that this mode is
18413 kept for compatibility reasons only and it is not advised to use it due to
18414 possible problems with hash in names of test skeletons when using an
18415 inconsistent casing. Separate test skeletons can be incorporated to monolith
18416 test package with improved hash being used by using @option{--transition}
18417 switch.
18420 @item --transition
18421 @cindex @option{--transition} (@command{gnattest})
18422 This allows transition from separate test routines to monolith test packages.
18423 All matching test routines are overwritten with contents of corresponding
18424 separates. Note that if separate test routines had any manually added with
18425 clauses they will be moved to the test package body as is and have to be moved
18426 by hand.
18428 @end table
18430 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
18431 mutually exclusive.
18433 @node Project Attributes for gnattest
18434 @section Project Attributes for @command{gnattest}
18436 @noindent
18438 Most of the command-line options can also be passed to the tool by adding
18439 special attributes to the project file. Those attributes should be put in
18440 package gnattest. Here is the list of attributes:
18442 @itemize @bullet
18444 @item Tests_Root
18445 is used to select the same output mode as with the --tests-root option.
18446 This attribute cannot be used together with Subdir or Tests_Dir.
18448 @item Subdir
18449 is used to select the same output mode as with the --subdir option.
18450 This attribute cannot be used together with Tests_Root or Tests_Dir.
18452 @item Tests_Dir
18453 is used to select the same output mode as with the --tests-dir option.
18454 This attribute cannot be used together with Subdir or Tests_Root.
18456 @item Harness_Dir
18457 is used to specify the directory in which to place harness packages and project
18458 file for the test driver, otherwise specified by --harness-dir.
18460 @item Additional_Tests
18461 is used to specify the project file, otherwise given by
18462 --additional-tests switch.
18464 @item Skeletons_Default
18465 is used to specify the default behaviour of test skeletons, otherwise
18466 specified by --skeleton-default option. The value of this attribute
18467 should be either "pass" or "fail".
18469 @end itemize
18471 Each of those attributes can be overridden from the command line if needed.
18472 Other @command{gnattest} switches can also be passed via the project
18473 file as an attribute list called GNATtest_Switches.
18475 @node Simple Example
18476 @section Simple Example
18478 @noindent
18480 Let's take a very simple example using the first @command{gnattest} example
18481 located in:
18483 @smallexample
18484 <install_prefix>/share/examples/gnattest/simple
18485 @end smallexample
18487 This project contains a simple package containing one subprogram. By running gnattest:
18489 @smallexample
18490 $ gnattest --harness-dir=driver -Psimple.gpr
18491 @end smallexample
18493 a test driver is created in directory "driver". It can be compiled and run:
18495 @smallexample
18496 $ cd driver
18497 $ gprbuild -Ptest_driver
18498 $ test_runner
18499 @end smallexample
18501 One failed test with diagnosis "test not implemented" is reported.
18502 Since no special output option was specified, the test package Simple.Tests
18503 is located in:
18505 @smallexample
18506 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
18507 @end smallexample
18509 For each package containing visible subprograms, a child test package is
18510 generated. It contains one test routine per tested subprogram. Each
18511 declaration of a test subprogram has a comment specifying which tested
18512 subprogram it corresponds to. Bodies of test routines are placed in test package
18513 bodies and are surrounded by special comment sections. Those comment sections
18514 should not be removed or modified in order for gnattest to be able to regenerate
18515 test packages and keep already written tests in place.
18516 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
18517 a single statement: a call to procedure Assert. It has two arguments:
18518 the Boolean expression we want to check and the diagnosis message to display if
18519 the condition is false.
18521 That is where actual testing code should be written after a proper setup.
18522 An actual check can be performed by replacing the Assert call with:
18524 @smallexample @c ada
18525 Assert (Inc (1) = 2, "wrong incrementation");
18526 @end smallexample
18528 After recompiling and running the test driver, one successfully passed test
18529 is reported.
18531 @node Setting Up and Tearing Down the Testing Environment
18532 @section Setting Up and Tearing Down the Testing Environment
18534 @noindent
18536 Besides test routines themselves, each test package has a parent package
18537 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
18538 overwritten by the tool. Set_Up is called before each test routine of the
18539 package and Tear_Down is called after each test routine. Those two procedures
18540 can be used to perform necessary initialization and finalization,
18541 memory allocation, etc. Test type declared in Test_Data package is parent type
18542 for the test type of test package and can have user-defined components whose
18543 values can be set by Set_Up routine and used in test routines afterwards.
18545 @node Regenerating Tests
18546 @section Regenerating Tests
18548 @noindent
18550 Bodies of test routines and test_data packages are never overridden after they
18551 have been created once. As long as the name of the subprogram, full expanded Ada
18552 names, and the order of its parameters is the same, and comment sections are
18553 intact the old test routine will fit in its place and no test skeleton will be
18554 generated for the subprogram.
18556 This can be demonstrated with the previous example. By uncommenting declaration
18557 and body of function Dec in simple.ads and simple.adb, running
18558 @command{gnattest} on the project, and then running the test driver:
18560 @smallexample
18561 gnattest --harness-dir=driver -Psimple.gpr
18562 cd driver
18563 gprbuild -Ptest_driver
18564 test_runner
18565 @end smallexample
18567 the old test is not replaced with a stub, nor is it lost, but a new test
18568 skeleton is created for function Dec.
18570 The only way of regenerating tests skeletons is to remove the previously created
18571 tests together with corresponding comment sections.
18573 @node Default Test Behavior
18574 @section Default Test Behavior
18576 @noindent
18578 The generated test driver can treat unimplemented tests in two ways:
18579 either count them all as failed (this is useful to see which tests are still
18580 left to implement) or as passed (to sort out unimplemented ones from those
18581 actually failing).
18583 The test driver accepts a switch to specify this behavior:
18584 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
18585 @command{gnattest}).
18587 The default behavior of the test driver is set with the same switch
18588 as passed to gnattest when generating the test driver.
18590 Passing it to the driver generated on the first example:
18592 @smallexample
18593 test_runner --skeleton-default=pass
18594 @end smallexample
18596 makes both tests pass, even the unimplemented one.
18598 @node Testing Primitive Operations of Tagged Types
18599 @section Testing Primitive Operations of Tagged Types
18601 @noindent
18603 Creation of test skeletons for primitive operations of tagged types entails
18604 a number of features. Test routines for all primitives of a given tagged type
18605 are placed in a separate child package named according to the tagged type. For
18606 example, if you have tagged type T in package P, all tests for primitives
18607 of T will be in P.T_Test_Data.T_Tests.
18609 Consider running gnattest on the second example (note: actual tests for this
18610 example already exist, so there's no need to worry if the tool reports that
18611 no new stubs were generated):
18613 @smallexample
18614 cd <install_prefix>/share/examples/gnattest/tagged_rec
18615 gnattest --harness-dir=driver -Ptagged_rec.gpr
18616 @end smallexample
18618 Taking a closer look at the test type declared in the test package
18619 Speed1.Controller_Test_Data is necessary. It is declared in:
18621 @smallexample
18622 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
18623 @end smallexample
18625 Test types are direct or indirect descendants of
18626 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18627 subprograms, the user doesn't need to be concerned with them. However,
18628 when generating test packages for primitive operations, there are some things
18629 the user needs to know.
18631 Type Test_Controller has components that allow assignment of various
18632 derivations of type Controller. And if you look at the specification of
18633 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18634 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18635 Thus, test types mirror the hierarchy of tested types.
18637 The Set_Up procedure of Test_Data package corresponding to a test package
18638 of primitive operations of type T assigns to Fixture a reference to an
18639 object of that exact type T. Notice, however, that if the tagged type has
18640 discriminants, the Set_Up only has a commented template for setting
18641 up the fixture, since filling the discriminant with actual value is up
18642 to the user.
18644 The knowledge of the structure of test types allows additional testing
18645 without additional effort. Those possibilities are described below.
18647 @node Testing Inheritance
18648 @section Testing Inheritance
18650 @noindent
18652 Since the test type hierarchy mimics the hierarchy of tested types, the
18653 inheritance of tests takes place. An example of such inheritance can be
18654 seen by running the test driver generated for the second example. As previously
18655 mentioned, actual tests are already written for this example.
18657 @smallexample
18658 cd driver
18659 gprbuild -Ptest_driver
18660 test_runner
18661 @end smallexample
18663 There are 6 passed tests while there are only 5 testable subprograms. The test
18664 routine for function Speed has been inherited and run against objects of the
18665 derived type.
18667 @node Tagged Types Substitutability Testing
18668 @section Tagged Types Substitutability Testing
18670 @noindent
18672 Tagged Types Substitutability Testing is a way of verifying the global type
18673 consistency by testing. Global type consistency is a principle stating that if
18674 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18675 then objects of type T may be replaced with objects of type S (that is,
18676 objects of type S may be substituted for objects of type T), without
18677 altering any of the desirable properties of the program. When the properties
18678 of the program are expressed in the form of subprogram preconditions and
18679 postconditions (let's call them pre and post), the principle is formulated as
18680 relations between the pre and post of primitive operations and the pre and post
18681 of their derived operations. The pre of a derived operation should not be
18682 stronger than the original pre, and the post of the derived operation should
18683 not be weaker than the original post. Those relations ensure that verifying if
18684 a dispatching call is safe can be done just by using the pre and post of the
18685 root operation.
18687 Verifying global type consistency by testing consists of running all the unit
18688 tests associated with the primitives of a given tagged type with objects of its
18689 derived types.
18691 In the example used in the previous section, there was clearly a violation of
18692 type consistency. The overriding primitive Adjust_Speed in package Speed2
18693 removes the functionality of the overridden primitive and thus doesn't respect
18694 the consistency principle.
18695 Gnattest has a special option to run overridden parent tests against objects
18696 of the type which have overriding primitives:
18698 @smallexample
18699 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
18700 cd driver
18701 gprbuild -Ptest_driver
18702 test_runner
18703 @end smallexample
18705 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18706 against objects of the derived type.
18708 Non-overridden tests are already inherited for derived test types, so the
18709 --validate-type-extensions enables the application of overriden tests to objects
18710 of derived types.
18712 @node Testing with Contracts
18713 @section Testing with Contracts
18715 @noindent
18717 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
18718 as well as corresponding aspects.
18719 Test routines are generated, one per each Test_Case associated with a tested
18720 subprogram. Those test routines have special wrappers for tested functions
18721 that have composition of pre- and postcondition of the subprogram with
18722 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18723 either count for Nominal mode or do not count for Robustness mode).
18725 The third example demonstrates how this works:
18727 @smallexample
18728 cd <install_prefix>/share/examples/gnattest/contracts
18729 gnattest --harness-dir=driver -Pcontracts.gpr
18730 @end smallexample
18732 Putting actual checks within the range of the contract does not cause any
18733 error reports. For example, for the test routine which corresponds to
18734 test case 1:
18736 @smallexample @c ada
18737 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18738 @end smallexample
18740 and for the test routine corresponding to test case 2:
18742 @smallexample @c ada
18743 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18744 @end smallexample
18746 are acceptable:
18748 @smallexample
18749 cd driver
18750 gprbuild -Ptest_driver
18751 test_runner
18752 @end smallexample
18754 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18755 a precondition violation for test case one. Also, by using any otherwise
18756 correct but positive pair of numbers in the second test routine, you can also
18757 get a precondition violation. Postconditions are checked and reported
18758 the same way.
18760 @node Additional Tests
18761 @section Additional Tests
18763 @noindent
18764 @command{gnattest} can add user-written tests to the main suite of the test
18765 driver. @command{gnattest} traverses the given packages and searches for test
18766 routines. All procedures with a single in out parameter of a type which is
18767 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18768 specifications are added to the suites and are then executed by the test driver.
18769 (Set_Up and Tear_Down are filtered out.)
18771 An example illustrates two ways of creating test harnesses for user-written
18772 tests. Directory additional_tests contains an AUnit-based test driver written
18773 by hand.
18775 @smallexample
18776 <install_prefix>/share/examples/gnattest/additional_tests/
18777 @end smallexample
18779 To create a test driver for already-written tests, use the --harness-only
18780 option:
18782 @smallexample
18783 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18784   --harness-only
18785 gnatmake -Pharness_only/test_driver.gpr
18786 harness_only/test_runner
18787 @end smallexample
18789 Additional tests can also be executed together with generated tests:
18791 @smallexample
18792 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18793   --harness-dir=mixing
18794 gnatmake -Pmixing/test_driver.gpr
18795 mixing/test_runner
18796 @end smallexample
18798 @ifclear vms
18799 @node Support for other platforms/run-times
18800 @section Support for other platforms/run-times
18802 @noindent
18803 @command{gnattest} can be used to generate the test harness for platforms
18804 and run-time libraries others than the default native target with the
18805 default full run-time. For example, when using a limited run-time library
18806 such as Zero FootPrint (ZFP), a simplified harness is generated.
18808 Two variables are used to tell the underlying AUnit framework how to generate
18809 the test harness: @code{PLATFORM}, which identifies the target, and
18810 @code{RUNTIME}, used to determine the run-time library for which the harness
18811 is generated. Corresponding prefix should also be used when calling
18812 @command{gnattest} for non-native targets. For example, the following options
18813 are used to generate the AUnit test harness for a PowerPC ELF target using
18814 the ZFP run-time library:
18816 @smallexample
18817 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
18818 @end smallexample
18819 @end ifclear
18821 @node Current Limitations
18822 @section Current Limitations
18824 @noindent
18826 The tool currently does not support following features:
18828 @itemize @bullet
18829 @item generic tests for generic packages and package instantiations
18830 @item tests for protected subprograms and entries
18832 @end itemize
18834 @c *********************************
18835 @node Performing Dimensionality Analysis in GNAT
18836 @chapter Performing Dimensionality Analysis in GNAT
18837 @noindent
18838 The GNAT compiler now supports dimensionality checking. The user can
18839 specify physical units for objects, and the compiler will verify that uses
18840 of these objects are compatible with their dimensions, in a fashion that is
18841 familiar to engineering practice. The dimensions of algebraic expressions
18842 (including powers with static exponents) are computed from their consistuents.
18844 This feature depends on Ada 2012 aspect specifications, and is available from
18845 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
18846 the user to define a system of units; the aspect Dimension then allows the user
18847 to declare dimensioned quantities within a given system.
18849 The major advantage of this model is that it does not require the declaration of
18850 multiple operators for all possible combinations of types: it is only necessary
18851 to use the proper subtypes in object declarations.
18853 The simplest way to impose dimensionality checking on a computation is to make
18854 use of the package System.Dim.Mks, which is part of the GNAT library. This
18855 package defines a floating-point type MKS_Type, for which a sequence of
18856 dimension names are specified, together with their conventional abbreviations.
18857 The following should be read together with the full specification of the
18858 package, in file s-dimmks.ads.
18860 @smallexample @c ada
18861    type Mks_Type is new Long_Long_Float
18862      with
18863       Dimension_System => (
18864         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
18865         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
18866         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
18867         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
18868         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
18869         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
18870         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
18871 @end smallexample
18873 @noindent
18874 The package then defines a series of subtypes that correspond to these
18875 conventional units. For example:
18876 @smallexample @c ada
18877    subtype Length is Mks_Type
18878      with
18879       Dimension => (Symbol => 'm',
18880         Meter  => 1,
18881         others => 0);
18882 @end smallexample
18883 @noindent
18884 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
18885 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
18886 the SI system).
18888 The package also defines conventional names for values of each unit, for
18889 example:
18891 @smallexample @c ada
18892    m   : constant Length           := 1.0;
18893    kg  : constant Mass             := 1.0;
18894    s   : constant Time             := 1.0;
18895    A   : constant Electric_Current := 1.0;
18896 @end smallexample
18898 @noindent
18899 as well as useful multiples of these units:
18901 @smallexample @c ada
18902    cm  : constant Length := 1.0E-02;
18903    g   : constant Mass   := 1.0E-03;
18904    min : constant Time   := 60.0;
18905    day : constant TIme   := 60.0 * 24.0 * min;
18906   ...
18907 @end smallexample
18909 @noindent
18910 The user can then define a derived unit by providing the aspect that
18911 specifies its dimensions within the MKS system, as well as the string to
18912 be used for output of a value of that unit:
18914 @smallexample @c ada
18915   subtype Acceleration is Mks_Type
18916     with Dimension => ("m/sec^^^2", Meter => 1, Second => -2, others => 0);
18917 @end smallexample
18919 @noindent
18920 Here is a complete example of use:
18922 @smallexample @c ada
18923 with System.Dim.MKS; use System.Dim.Mks;
18924 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
18925 with Text_IO; use Text_IO;
18926 procedure Free_Fall is
18927   subtype Acceleration is Mks_Type
18928     with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
18929   G : constant acceleration := 9.81 * m / (s ** 2);
18930   T : Time := 10.0*s;
18931   Distance : Length;
18932 begin
18933   Put ("Gravitational constant: ");
18934   Put (G, Aft => 2, Exp => 0); Put_Line ("");
18935   Distance := 0.5 * G * T ** 2;
18936   Put ("distance travelled in 10 seconds of free fall ");
18937   Put (Distance, Aft => 2, Exp => 0);
18938   Put_Line ("");
18939 end Free_Fall;
18940 @end smallexample
18942 @noindent
18943 Execution of this program yields:
18944 @smallexample
18945 Gravitational constant:  9.81 m/sec^^^2
18946 distance travelled in 10 seconds of free fall 490.50 m
18947 @end smallexample
18949 @noindent
18950 However, incorrect assignments such as:
18952 @smallexample @c ada
18953    Distance := 5.0;
18954    Distance := 5.0 * kg:
18955 @end smallexample
18957 @noindent
18958 are rejected with the following diagnoses:
18960 @smallexample
18961    Distance := 5.0;
18962       >>> dimensions mismatch in assignment
18963       >>> left-hand side has dimension [L]
18964       >>> right-hand side is dimensionless
18966    Distance := 5.0 * kg:
18967       >>> dimensions mismatch in assignment
18968       >>> left-hand side has dimension [L]
18969       >>> right-hand side has dimension [M]
18970 @end smallexample
18972 @noindent
18973 The dimensions of an expression are properly displayed, even if there is
18974 no explicit subtype for it. If we add to the program:
18976 @smallexample @c ada
18977       Put ("Final velocity: ");
18978       Put (G * T, Aft =>2, Exp =>0);
18979       Put_Line ("");
18980 @end smallexample
18982 @noindent
18983 then the output includes:
18984 @smallexample
18985      Final velocity: 98.10 m.s**(-1)
18986 @end smallexample
18988 @c *********************************
18989 @node Generating Ada Bindings for C and C++ headers
18990 @chapter Generating Ada Bindings for C and C++ headers
18991 @findex binding
18993 @noindent
18994 GNAT now comes with a binding generator for C and C++ headers which is
18995 intended to do 95% of the tedious work of generating Ada specs from C
18996 or C++ header files.
18998 Note that this capability is not intended to generate 100% correct Ada specs,
18999 and will is some cases require manual adjustments, although it can often
19000 be used out of the box in practice.
19002 Some of the known limitations include:
19004 @itemize @bullet
19005 @item only very simple character constant macros are translated into Ada
19006 constants. Function macros (macros with arguments) are partially translated
19007 as comments, to be completed manually if needed.
19008 @item some extensions (e.g. vector types) are not supported
19009 @item pointers to pointers or complex structures are mapped to System.Address
19010 @item identifiers with identical name (except casing) will generate compilation
19011       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19012 @end itemize
19014 The code generated is using the Ada 2005 syntax, which makes it
19015 easier to interface with other languages than previous versions of Ada.
19017 @menu
19018 * Running the binding generator::
19019 * Generating bindings for C++ headers::
19020 * Switches::
19021 @end menu
19023 @node Running the binding generator
19024 @section Running the binding generator
19026 @noindent
19027 The binding generator is part of the @command{gcc} compiler and can be
19028 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19029 spec files for the header files specified on the command line, and all
19030 header files needed by these files transitively. For example:
19032 @smallexample
19033 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19034 $ gcc -c -gnat05 *.ads
19035 @end smallexample
19037 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19038 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19039 correspond to the files @file{/usr/include/time.h},
19040 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19041 mode these Ada specs.
19043 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19044 and will attempt to generate corresponding Ada comments.
19046 If you want to generate a single Ada file and not the transitive closure, you
19047 can use instead the @option{-fdump-ada-spec-slim} switch.
19049 You can optionally specify a parent unit, of which all generated units will
19050 be children, using @code{-fada-spec-parent=}@var{unit}.
19052 Note that we recommend when possible to use the @command{g++} driver to
19053 generate bindings, even for most C headers, since this will in general
19054 generate better Ada specs. For generating bindings for C++ headers, it is
19055 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
19056 is equivalent in this case. If @command{g++} cannot work on your C headers
19057 because of incompatibilities between C and C++, then you can fallback to
19058 @command{gcc} instead.
19060 For an example of better bindings generated from the C++ front-end,
19061 the name of the parameters (when available) are actually ignored by the C
19062 front-end. Consider the following C header:
19064 @smallexample
19065 extern void foo (int variable);
19066 @end smallexample
19068 with the C front-end, @code{variable} is ignored, and the above is handled as:
19070 @smallexample
19071 extern void foo (int);
19072 @end smallexample
19074 generating a generic:
19076 @smallexample
19077 procedure foo (param1 : int);
19078 @end smallexample
19080 with the C++ front-end, the name is available, and we generate:
19082 @smallexample
19083 procedure foo (variable : int);
19084 @end smallexample
19086 In some cases, the generated bindings will be more complete or more meaningful
19087 when defining some macros, which you can do via the @option{-D} switch. This
19088 is for example the case with @file{Xlib.h} under GNU/Linux:
19090 @smallexample
19091 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
19092 @end smallexample
19094 The above will generate more complete bindings than a straight call without
19095 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
19097 In other cases, it is not possible to parse a header file in a stand-alone
19098 manner, because other include files need to be included first. In this
19099 case, the solution is to create a small header file including the needed
19100 @code{#include} and possible @code{#define} directives. For example, to
19101 generate Ada bindings for @file{readline/readline.h}, you need to first
19102 include @file{stdio.h}, so you can create a file with the following two
19103 lines in e.g. @file{readline1.h}:
19105 @smallexample
19106 #include <stdio.h>
19107 #include <readline/readline.h>
19108 @end smallexample
19110 and then generate Ada bindings from this file:
19112 @smallexample
19113 $ g++ -c -fdump-ada-spec readline1.h
19114 @end smallexample
19116 @node Generating bindings for C++ headers
19117 @section Generating bindings for C++ headers
19119 @noindent
19120 Generating bindings for C++ headers is done using the same options, always
19121 with the @command{g++} compiler.
19123 In this mode, C++ classes will be mapped to Ada tagged types, constructors
19124 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
19125 multiple inheritance of abstract classes will be mapped to Ada interfaces
19126 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
19127 information on interfacing to C++).
19129 For example, given the following C++ header file:
19131 @smallexample
19132 @group
19133 @cartouche
19134 class Carnivore @{
19135 public:
19136    virtual int Number_Of_Teeth () = 0;
19139 class Domestic @{
19140 public:
19141    virtual void Set_Owner (char* Name) = 0;
19144 class Animal @{
19145 public:
19146   int Age_Count;
19147   virtual void Set_Age (int New_Age);
19150 class Dog : Animal, Carnivore, Domestic @{
19151  public:
19152   int  Tooth_Count;
19153   char *Owner;
19155   virtual int  Number_Of_Teeth ();
19156   virtual void Set_Owner (char* Name);
19158   Dog();
19160 @end cartouche
19161 @end group
19162 @end smallexample
19164 The corresponding Ada code is generated:
19166 @smallexample @c ada
19167 @group
19168 @cartouche
19169   package Class_Carnivore is
19170     type Carnivore is limited interface;
19171     pragma Import (CPP, Carnivore);
19173     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
19174   end;
19175   use Class_Carnivore;
19177   package Class_Domestic is
19178     type Domestic is limited interface;
19179     pragma Import (CPP, Domestic);
19181     procedure Set_Owner
19182       (this : access Domestic;
19183        Name : Interfaces.C.Strings.chars_ptr) is abstract;
19184   end;
19185   use Class_Domestic;
19187   package Class_Animal is
19188     type Animal is tagged limited record
19189       Age_Count : aliased int;
19190     end record;
19191     pragma Import (CPP, Animal);
19193     procedure Set_Age (this : access Animal; New_Age : int);
19194     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
19195   end;
19196   use Class_Animal;
19198   package Class_Dog is
19199     type Dog is new Animal and Carnivore and Domestic with record
19200       Tooth_Count : aliased int;
19201       Owner : Interfaces.C.Strings.chars_ptr;
19202     end record;
19203     pragma Import (CPP, Dog);
19205     function Number_Of_Teeth (this : access Dog) return int;
19206     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
19208     procedure Set_Owner
19209       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
19210     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
19212     function New_Dog return Dog;
19213     pragma CPP_Constructor (New_Dog);
19214     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
19215   end;
19216   use Class_Dog;
19217 @end cartouche
19218 @end group
19219 @end smallexample
19221 @node Switches
19222 @section Switches
19224 @table @option
19225 @item -fdump-ada-spec
19226 @cindex @option{-fdump-ada-spec} (@command{gcc})
19227 Generate Ada spec files for the given header files transitively (including
19228 all header files that these headers depend upon).
19230 @item -fdump-ada-spec-slim
19231 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
19232 Generate Ada spec files for the header files specified on the command line
19233 only.
19235 @item -fada-spec-parent=@var{unit}
19236 @cindex -fada-spec-parent (@command{gcc})
19237 Specifies that all files generated by @option{-fdump-ada-spec*} are
19238 to be child units of the specified parent unit.
19240 @item -C
19241 @cindex @option{-C} (@command{gcc})
19242 Extract comments from headers and generate Ada comments in the Ada spec files.
19243 @end table
19245 @node Other Utility Programs
19246 @chapter Other Utility Programs
19248 @noindent
19249 This chapter discusses some other utility programs available in the Ada
19250 environment.
19252 @menu
19253 * Using Other Utility Programs with GNAT::
19254 * The External Symbol Naming Scheme of GNAT::
19255 * Converting Ada Files to html with gnathtml::
19256 * Installing gnathtml::
19257 @ifset vms
19258 * LSE::
19259 * Profiling::
19260 @end ifset
19261 @end menu
19263 @node Using Other Utility Programs with GNAT
19264 @section Using Other Utility Programs with GNAT
19266 @noindent
19267 The object files generated by GNAT are in standard system format and in
19268 particular the debugging information uses this format. This means
19269 programs generated by GNAT can be used with existing utilities that
19270 depend on these formats.
19272 @ifclear vms
19273 In general, any utility program that works with C will also often work with
19274 Ada programs generated by GNAT. This includes software utilities such as
19275 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19276 as Purify.
19277 @end ifclear
19279 @node The External Symbol Naming Scheme of GNAT
19280 @section The External Symbol Naming Scheme of GNAT
19282 @noindent
19283 In order to interpret the output from GNAT, when using tools that are
19284 originally intended for use with other languages, it is useful to
19285 understand the conventions used to generate link names from the Ada
19286 entity names.
19288 All link names are in all lowercase letters. With the exception of library
19289 procedure names, the mechanism used is simply to use the full expanded
19290 Ada name with dots replaced by double underscores. For example, suppose
19291 we have the following package spec:
19293 @smallexample @c ada
19294 @group
19295 @cartouche
19296 package QRS is
19297    MN : Integer;
19298 end QRS;
19299 @end cartouche
19300 @end group
19301 @end smallexample
19303 @noindent
19304 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19305 the corresponding link name is @code{qrs__mn}.
19306 @findex Export
19307 Of course if a @code{pragma Export} is used this may be overridden:
19309 @smallexample @c ada
19310 @group
19311 @cartouche
19312 package Exports is
19313    Var1 : Integer;
19314    pragma Export (Var1, C, External_Name => "var1_name");
19315    Var2 : Integer;
19316    pragma Export (Var2, C, Link_Name => "var2_link_name");
19317 end Exports;
19318 @end cartouche
19319 @end group
19320 @end smallexample
19322 @noindent
19323 In this case, the link name for @var{Var1} is whatever link name the
19324 C compiler would assign for the C function @var{var1_name}. This typically
19325 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19326 system conventions, but other possibilities exist. The link name for
19327 @var{Var2} is @var{var2_link_name}, and this is not operating system
19328 dependent.
19330 @findex _main
19331 One exception occurs for library level procedures. A potential ambiguity
19332 arises between the required name @code{_main} for the C main program,
19333 and the name we would otherwise assign to an Ada library level procedure
19334 called @code{Main} (which might well not be the main program).
19336 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19337 names. So if we have a library level procedure such as
19339 @smallexample @c ada
19340 @group
19341 @cartouche
19342 procedure Hello (S : String);
19343 @end cartouche
19344 @end group
19345 @end smallexample
19347 @noindent
19348 the external name of this procedure will be @var{_ada_hello}.
19351 @node Converting Ada Files to html with gnathtml
19352 @section Converting Ada Files to HTML with @code{gnathtml}
19354 @noindent
19355 This @code{Perl} script allows Ada source files to be browsed using
19356 standard Web browsers. For installation procedure, see the section
19357 @xref{Installing gnathtml}.
19359 Ada reserved keywords are highlighted in a bold font and Ada comments in
19360 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19361 switch to suppress the generation of cross-referencing information, user
19362 defined variables and types will appear in a different color; you will
19363 be able to click on any identifier and go to its declaration.
19365 The command line is as follow:
19366 @smallexample
19367 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
19368 @c Expanding @ovar macro inline (explanation in macro def comments)
19369 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
19370 @end smallexample
19372 @noindent
19373 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19374 an html file for every ada file, and a global file called @file{index.htm}.
19375 This file is an index of every identifier defined in the files.
19377 The available ^switches^options^ are the following ones:
19379 @table @option
19380 @item -83
19381 @cindex @option{-83} (@code{gnathtml})
19382 Only the Ada 83 subset of keywords will be highlighted.
19384 @item -cc @var{color}
19385 @cindex @option{-cc} (@code{gnathtml})
19386 This option allows you to change the color used for comments. The default
19387 value is green. The color argument can be any name accepted by html.
19389 @item -d
19390 @cindex @option{-d} (@code{gnathtml})
19391 If the Ada files depend on some other files (for instance through
19392 @code{with} clauses, the latter files will also be converted to html.
19393 Only the files in the user project will be converted to html, not the files
19394 in the run-time library itself.
19396 @item -D
19397 @cindex @option{-D} (@code{gnathtml})
19398 This command is the same as @option{-d} above, but @command{gnathtml} will
19399 also look for files in the run-time library, and generate html files for them.
19401 @item -ext @var{extension}
19402 @cindex @option{-ext} (@code{gnathtml})
19403 This option allows you to change the extension of the generated HTML files.
19404 If you do not specify an extension, it will default to @file{htm}.
19406 @item -f
19407 @cindex @option{-f} (@code{gnathtml})
19408 By default, gnathtml will generate html links only for global entities
19409 ('with'ed units, global variables and types,@dots{}).  If you specify
19410 @option{-f} on the command line, then links will be generated for local
19411 entities too.
19413 @item -l @var{number}
19414 @cindex @option{-l} (@code{gnathtml})
19415 If this ^switch^option^ is provided and @var{number} is not 0, then
19416 @code{gnathtml} will number the html files every @var{number} line.
19418 @item -I @var{dir}
19419 @cindex @option{-I} (@code{gnathtml})
19420 Specify a directory to search for library files (@file{.ALI} files) and
19421 source files. You can provide several -I switches on the command line,
19422 and the directories will be parsed in the order of the command line.
19424 @item -o @var{dir}
19425 @cindex @option{-o} (@code{gnathtml})
19426 Specify the output directory for html files. By default, gnathtml will
19427 saved the generated html files in a subdirectory named @file{html/}.
19429 @item -p @var{file}
19430 @cindex @option{-p} (@code{gnathtml})
19431 If you are using Emacs and the most recent Emacs Ada mode, which provides
19432 a full Integrated Development Environment for compiling, checking,
19433 running and debugging applications, you may use @file{.gpr} files
19434 to give the directories where Emacs can find sources and object files.
19436 Using this ^switch^option^, you can tell gnathtml to use these files.
19437 This allows you to get an html version of your application, even if it
19438 is spread over multiple directories.
19440 @item -sc @var{color}
19441 @cindex @option{-sc} (@code{gnathtml})
19442 This ^switch^option^ allows you to change the color used for symbol
19443 definitions.
19444 The default value is red. The color argument can be any name accepted by html.
19446 @item -t @var{file}
19447 @cindex @option{-t} (@code{gnathtml})
19448 This ^switch^option^ provides the name of a file. This file contains a list of
19449 file names to be converted, and the effect is exactly as though they had
19450 appeared explicitly on the command line. This
19451 is the recommended way to work around the command line length limit on some
19452 systems.
19454 @end table
19456 @node Installing gnathtml
19457 @section Installing @code{gnathtml}
19459 @noindent
19460 @code{Perl} needs to be installed on your machine to run this script.
19461 @code{Perl} is freely available for almost every architecture and
19462 Operating System via the Internet.
19464 On Unix systems, you  may want to modify  the  first line of  the script
19465 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
19466 is. The syntax of this line is:
19467 @smallexample
19468 #!full_path_name_to_perl
19469 @end smallexample
19471 @noindent
19472 Alternatively, you may run the script using the following command line:
19474 @smallexample
19475 @c $ perl gnathtml.pl @ovar{switches} @var{files}
19476 @c Expanding @ovar macro inline (explanation in macro def comments)
19477 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
19478 @end smallexample
19480 @ifset vms
19481 @node LSE
19482 @section LSE
19483 @findex LSE
19485 @noindent
19486 The GNAT distribution provides an Ada 95 template for the HP Language
19487 Sensitive Editor (LSE), a component of DECset. In order to
19488 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19490 @node Profiling
19491 @section Profiling
19492 @findex PCA
19494 @noindent
19495 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19496 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19497 the collection phase with the /DEBUG qualifier.
19499 @smallexample
19500 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19501 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19502 $ RUN/DEBUG <PROGRAM_NAME>
19503 @end smallexample
19504 @noindent
19505 @end ifset
19507 @ifclear vms
19508 @c ******************************
19509 @node Code Coverage and Profiling
19510 @chapter Code Coverage and Profiling
19511 @cindex Code Coverage
19512 @cindex Profiling
19514 @noindent
19515 This chapter describes how to use @code{gcov} - coverage testing tool - and
19516 @code{gprof} - profiler tool - on your Ada programs.
19518 @menu
19519 * Code Coverage of Ada Programs using gcov::
19520 * Profiling an Ada Program using gprof::
19521 @end menu
19523 @node Code Coverage of Ada Programs using gcov
19524 @section Code Coverage of Ada Programs using gcov
19525 @cindex gcov
19526 @cindex -fprofile-arcs
19527 @cindex -ftest-coverage
19528 @cindex -coverage
19529 @cindex Code Coverage
19531 @noindent
19532 @code{gcov} is a test coverage program: it analyzes the execution of a given
19533 program on selected tests, to help you determine the portions of the program
19534 that are still untested.
19536 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
19537 User's Guide. You can refer to this documentation for a more complete
19538 description.
19540 This chapter provides a quick startup guide, and
19541 details some Gnat-specific features.
19543 @menu
19544 * Quick startup guide::
19545 * Gnat specifics::
19546 @end menu
19548 @node Quick startup guide
19549 @subsection Quick startup guide
19551 In order to perform coverage analysis of a program using @code{gcov}, 3
19552 steps are needed:
19554 @itemize @bullet
19555 @item
19556 Code instrumentation during the compilation process
19557 @item
19558 Execution of the instrumented program
19559 @item
19560 Execution of the @code{gcov} tool to generate the result.
19561 @end itemize
19563 The code instrumentation needed by gcov is created at the object level:
19564 The source code is not modified in any way, because the instrumentation code is
19565 inserted by gcc during the compilation process. To compile your code with code
19566 coverage activated, you need to recompile your whole project using the
19567 switches
19568 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19569 @code{-fprofile-arcs}.
19571 @smallexample
19572 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19573    -largs -fprofile-arcs
19574 @end smallexample
19576 This compilation process will create @file{.gcno} files together with
19577 the usual object files.
19579 Once the program is compiled with coverage instrumentation, you can
19580 run it as many times as needed - on portions of a test suite for
19581 example. The first execution will produce @file{.gcda} files at the
19582 same location as the @file{.gcno} files.  The following executions
19583 will update those files, so that a cumulative result of the covered
19584 portions of the program is generated.
19586 Finally, you need to call the @code{gcov} tool. The different options of
19587 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
19589 This will create annotated source files with a @file{.gcov} extension:
19590 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
19592 @node Gnat specifics
19593 @subsection Gnat specifics
19595 Because Ada semantics, portions of the source code may be shared among
19596 several object files. This is the case for example when generics are
19597 involved, when inlining is active  or when declarations generate  initialisation
19598 calls. In order to take
19599 into account this shared code, you need to call @code{gcov} on all
19600 source files of the tested program at once.
19602 The list of source files might exceed the system's maximum command line
19603 length. In order to bypass this limitation, a new mechanism has been
19604 implemented in @code{gcov}: you can now list all your project's files into a
19605 text file, and provide this file to gcov as a parameter,  preceded by a @@
19606 (e.g. @samp{gcov @@mysrclist.txt}).
19608 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
19609 not supported as there can be unresolved symbols during the final link.
19611 @node Profiling an Ada Program using gprof
19612 @section Profiling an Ada Program using gprof
19613 @cindex gprof
19614 @cindex -pg
19615 @cindex Profiling
19617 @noindent
19618 This section is not meant to be an exhaustive documentation of @code{gprof}.
19619 Full documentation for it can be found in the GNU Profiler User's Guide
19620 documentation that is part of this GNAT distribution.
19622 Profiling a program helps determine the parts of a program that are executed
19623 most often, and are therefore the most time-consuming.
19625 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19626 better handle Ada programs and multitasking.
19627 It is currently supported on the following platforms
19628 @itemize @bullet
19629 @item
19630 linux x86/x86_64
19631 @item
19632 solaris sparc/sparc64/x86
19633 @item
19634 windows x86
19635 @end itemize
19637 @noindent
19638 In order to profile a program using @code{gprof}, 3 steps are needed:
19640 @itemize @bullet
19641 @item
19642 Code instrumentation, requiring a full recompilation of the project with the
19643 proper switches.
19644 @item
19645 Execution of the program under the analysis conditions, i.e. with the desired
19646 input.
19647 @item
19648 Analysis of the results using the @code{gprof} tool.
19649 @end itemize
19651 @noindent
19652 The following sections detail the different steps, and indicate how
19653 to interpret the results:
19654 @menu
19655 * Compilation for profiling::
19656 * Program execution::
19657 * Running gprof::
19658 * Interpretation of profiling results::
19659 @end menu
19661 @node Compilation for profiling
19662 @subsection Compilation for profiling
19663 @cindex -pg
19664 @cindex Profiling
19666 In order to profile a program the first step is to tell the compiler
19667 to generate the necessary profiling information. The compiler switch to be used
19668 is @code{-pg}, which must be added to other compilation switches. This
19669 switch needs to be specified both during compilation and link stages, and can
19670 be specified once when using gnatmake:
19672 @smallexample
19673 gnatmake -f -pg -P my_project
19674 @end smallexample
19676 @noindent
19677 Note that only the objects that were compiled with the @samp{-pg} switch will
19678 be profiled; if you need to profile your whole project, use the @samp{-f}
19679 gnatmake switch to force full recompilation.
19681 @node Program execution
19682 @subsection Program execution
19684 @noindent
19685 Once the program has been compiled for profiling, you can run it as usual.
19687 The only constraint imposed by profiling is that the program must terminate
19688 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19689 properly analyzed.
19691 Once the program completes execution, a data file called @file{gmon.out} is
19692 generated in the directory where the program was launched from. If this file
19693 already exists, it will be overwritten.
19695 @node Running gprof
19696 @subsection Running gprof
19698 @noindent
19699 The @code{gprof} tool is called as follow:
19701 @smallexample
19702 gprof my_prog gmon.out
19703 @end smallexample
19705 @noindent
19706 or simpler:
19708 @smallexample
19709 gprof my_prog
19710 @end smallexample
19712 @noindent
19713 The complete form of the gprof command line is the following:
19715 @smallexample
19716 gprof [^switches^options^] [executable [data-file]]
19717 @end smallexample
19719 @noindent
19720 @code{gprof} supports numerous ^switch^options^. The order of these
19721 ^switch^options^ does not matter. The full list of options can be found in
19722 the GNU Profiler User's Guide documentation that comes with this documentation.
19724 The following is the subset of those switches that is most relevant:
19726 @table @option
19728 @item --demangle[=@var{style}]
19729 @itemx --no-demangle
19730 @cindex @option{--demangle} (@code{gprof})
19731 These options control whether symbol names should be demangled when
19732 printing output.  The default is to demangle C++ symbols.  The
19733 @code{--no-demangle} option may be used to turn off demangling. Different
19734 compilers have different mangling styles.  The optional demangling style
19735 argument can be used to choose an appropriate demangling style for your
19736 compiler, in particular Ada symbols generated by GNAT can be demangled using
19737 @code{--demangle=gnat}.
19739 @item -e @var{function_name}
19740 @cindex @option{-e} (@code{gprof})
19741 The @samp{-e @var{function}} option tells @code{gprof} not to print
19742 information about the function @var{function_name} (and its
19743 children@dots{}) in the call graph.  The function will still be listed
19744 as a child of any functions that call it, but its index number will be
19745 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
19746 given; only one @var{function_name} may be indicated with each @samp{-e}
19747 option.
19749 @item -E @var{function_name}
19750 @cindex @option{-E} (@code{gprof})
19751 The @code{-E @var{function}} option works like the @code{-e} option, but
19752 execution time spent in the function (and children who were not called from
19753 anywhere else), will not be used to compute the percentages-of-time for
19754 the call graph.  More than one @samp{-E} option may be given; only one
19755 @var{function_name} may be indicated with each @samp{-E} option.
19757 @item -f @var{function_name}
19758 @cindex @option{-f} (@code{gprof})
19759 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19760 call graph to the function @var{function_name} and its children (and
19761 their children@dots{}).  More than one @samp{-f} option may be given;
19762 only one @var{function_name} may be indicated with each @samp{-f}
19763 option.
19765 @item -F @var{function_name}
19766 @cindex @option{-F} (@code{gprof})
19767 The @samp{-F @var{function}} option works like the @code{-f} option, but
19768 only time spent in the function and its children (and their
19769 children@dots{}) will be used to determine total-time and
19770 percentages-of-time for the call graph.  More than one @samp{-F} option
19771 may be given; only one @var{function_name} may be indicated with each
19772 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
19774 @end table
19776 @node Interpretation of profiling results
19777 @subsection Interpretation of profiling results
19779 @noindent
19781 The results of the profiling analysis are represented by two arrays: the
19782 'flat profile' and the 'call graph'. Full documentation of those outputs
19783 can be found in the GNU Profiler User's Guide.
19785 The flat profile shows the time spent in each function of the program, and how
19786 many time it has been called. This allows you to locate easily the most
19787 time-consuming functions.
19789 The call graph shows, for each subprogram, the subprograms that call it,
19790 and the subprograms that it calls. It also provides an estimate of the time
19791 spent in each of those callers/called subprograms.
19792 @end ifclear
19794 @c ******************************
19795 @node Running and Debugging Ada Programs
19796 @chapter Running and Debugging Ada Programs
19797 @cindex Debugging
19799 @noindent
19800 This chapter discusses how to debug Ada programs.
19801 @ifset vms
19802 It applies to GNAT on the Alpha OpenVMS platform;
19803 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19804 since HP has implemented Ada support in the OpenVMS debugger on I64.
19805 @end ifset
19807 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19809 @enumerate
19810 @item
19811 The illegality may be a violation of the static semantics of Ada. In
19812 that case GNAT diagnoses the constructs in the program that are illegal.
19813 It is then a straightforward matter for the user to modify those parts of
19814 the program.
19816 @item
19817 The illegality may be a violation of the dynamic semantics of Ada. In
19818 that case the program compiles and executes, but may generate incorrect
19819 results, or may terminate abnormally with some exception.
19821 @item
19822 When presented with a program that contains convoluted errors, GNAT
19823 itself may terminate abnormally without providing full diagnostics on
19824 the incorrect user program.
19825 @end enumerate
19827 @menu
19828 * The GNAT Debugger GDB::
19829 * Running GDB::
19830 * Introduction to GDB Commands::
19831 * Using Ada Expressions::
19832 * Calling User-Defined Subprograms::
19833 * Using the Next Command in a Function::
19834 * Ada Exceptions::
19835 * Ada Tasks::
19836 * Debugging Generic Units::
19837 * Remote Debugging using gdbserver::
19838 * GNAT Abnormal Termination or Failure to Terminate::
19839 * Naming Conventions for GNAT Source Files::
19840 * Getting Internal Debugging Information::
19841 * Stack Traceback::
19842 @end menu
19844 @cindex Debugger
19845 @findex gdb
19847 @node The GNAT Debugger GDB
19848 @section The GNAT Debugger GDB
19850 @noindent
19851 @code{GDB} is a general purpose, platform-independent debugger that
19852 can be used to debug mixed-language programs compiled with @command{gcc},
19853 and in particular is capable of debugging Ada programs compiled with
19854 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19855 complex Ada data structures.
19857 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19858 @ifset vms
19859 located in the GNU:[DOCS] directory,
19860 @end ifset
19861 for full details on the usage of @code{GDB}, including a section on
19862 its usage on programs. This manual should be consulted for full
19863 details. The section that follows is a brief introduction to the
19864 philosophy and use of @code{GDB}.
19866 When GNAT programs are compiled, the compiler optionally writes debugging
19867 information into the generated object file, including information on
19868 line numbers, and on declared types and variables. This information is
19869 separate from the generated code. It makes the object files considerably
19870 larger, but it does not add to the size of the actual executable that
19871 will be loaded into memory, and has no impact on run-time performance. The
19872 generation of debug information is triggered by the use of the
19873 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19874 used to carry out the compilations. It is important to emphasize that
19875 the use of these options does not change the generated code.
19877 The debugging information is written in standard system formats that
19878 are used by many tools, including debuggers and profilers. The format
19879 of the information is typically designed to describe C types and
19880 semantics, but GNAT implements a translation scheme which allows full
19881 details about Ada types and variables to be encoded into these
19882 standard C formats. Details of this encoding scheme may be found in
19883 the file exp_dbug.ads in the GNAT source distribution. However, the
19884 details of this encoding are, in general, of no interest to a user,
19885 since @code{GDB} automatically performs the necessary decoding.
19887 When a program is bound and linked, the debugging information is
19888 collected from the object files, and stored in the executable image of
19889 the program. Again, this process significantly increases the size of
19890 the generated executable file, but it does not increase the size of
19891 the executable program itself. Furthermore, if this program is run in
19892 the normal manner, it runs exactly as if the debug information were
19893 not present, and takes no more actual memory.
19895 However, if the program is run under control of @code{GDB}, the
19896 debugger is activated.  The image of the program is loaded, at which
19897 point it is ready to run.  If a run command is given, then the program
19898 will run exactly as it would have if @code{GDB} were not present. This
19899 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19900 entirely non-intrusive until a breakpoint is encountered.  If no
19901 breakpoint is ever hit, the program will run exactly as it would if no
19902 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19903 the debugging information and can respond to user commands to inspect
19904 variables, and more generally to report on the state of execution.
19906 @c **************
19907 @node Running GDB
19908 @section Running GDB
19910 @noindent
19911 This section describes how to initiate the debugger.
19912 @c The above sentence is really just filler, but it was otherwise
19913 @c clumsy to get the first paragraph nonindented given the conditional
19914 @c nature of the description
19916 @ifclear vms
19917 The debugger can be launched from a @code{GPS} menu or
19918 directly from the command line. The description below covers the latter use.
19919 All the commands shown can be used in the @code{GPS} debug console window,
19920 but there are usually more GUI-based ways to achieve the same effect.
19921 @end ifclear
19923 The command to run @code{GDB} is
19925 @smallexample
19926 $ ^gdb program^GDB PROGRAM^
19927 @end smallexample
19929 @noindent
19930 where @code{^program^PROGRAM^} is the name of the executable file. This
19931 activates the debugger and results in a prompt for debugger commands.
19932 The simplest command is simply @code{run}, which causes the program to run
19933 exactly as if the debugger were not present. The following section
19934 describes some of the additional commands that can be given to @code{GDB}.
19936 @c *******************************
19937 @node Introduction to GDB Commands
19938 @section Introduction to GDB Commands
19940 @noindent
19941 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19942 Debugging with GDB, gdb, Debugging with GDB},
19943 @ifset vms
19944 located in the GNU:[DOCS] directory,
19945 @end ifset
19946 for extensive documentation on the use
19947 of these commands, together with examples of their use. Furthermore,
19948 the command @command{help} invoked from within GDB activates a simple help
19949 facility which summarizes the available commands and their options.
19950 In this section we summarize a few of the most commonly
19951 used commands to give an idea of what @code{GDB} is about. You should create
19952 a simple program with debugging information and experiment with the use of
19953 these @code{GDB} commands on the program as you read through the
19954 following section.
19956 @table @code
19957 @item set args @var{arguments}
19958 The @var{arguments} list above is a list of arguments to be passed to
19959 the program on a subsequent run command, just as though the arguments
19960 had been entered on a normal invocation of the program. The @code{set args}
19961 command is not needed if the program does not require arguments.
19963 @item run
19964 The @code{run} command causes execution of the program to start from
19965 the beginning. If the program is already running, that is to say if
19966 you are currently positioned at a breakpoint, then a prompt will ask
19967 for confirmation that you want to abandon the current execution and
19968 restart.
19970 @item breakpoint @var{location}
19971 The breakpoint command sets a breakpoint, that is to say a point at which
19972 execution will halt and @code{GDB} will await further
19973 commands. @var{location} is
19974 either a line number within a file, given in the format @code{file:linenumber},
19975 or it is the name of a subprogram. If you request that a breakpoint be set on
19976 a subprogram that is overloaded, a prompt will ask you to specify on which of
19977 those subprograms you want to breakpoint. You can also
19978 specify that all of them should be breakpointed. If the program is run
19979 and execution encounters the breakpoint, then the program
19980 stops and @code{GDB} signals that the breakpoint was encountered by
19981 printing the line of code before which the program is halted.
19983 @item catch exception @var{name}
19984 This command causes the program execution to stop whenever exception
19985 @var{name} is raised.  If @var{name} is omitted, then the execution is
19986 suspended when any exception is raised.
19988 @item print @var{expression}
19989 This will print the value of the given expression. Most simple
19990 Ada expression formats are properly handled by @code{GDB}, so the expression
19991 can contain function calls, variables, operators, and attribute references.
19993 @item continue
19994 Continues execution following a breakpoint, until the next breakpoint or the
19995 termination of the program.
19997 @item step
19998 Executes a single line after a breakpoint. If the next statement
19999 is a subprogram call, execution continues into (the first statement of)
20000 the called subprogram.
20002 @item next
20003 Executes a single line. If this line is a subprogram call, executes and
20004 returns from the call.
20006 @item list
20007 Lists a few lines around the current source location. In practice, it
20008 is usually more convenient to have a separate edit window open with the
20009 relevant source file displayed. Successive applications of this command
20010 print subsequent lines. The command can be given an argument which is a
20011 line number, in which case it displays a few lines around the specified one.
20013 @item backtrace
20014 Displays a backtrace of the call chain. This command is typically
20015 used after a breakpoint has occurred, to examine the sequence of calls that
20016 leads to the current breakpoint. The display includes one line for each
20017 activation record (frame) corresponding to an active subprogram.
20019 @item up
20020 At a breakpoint, @code{GDB} can display the values of variables local
20021 to the current frame. The command @code{up} can be used to
20022 examine the contents of other active frames, by moving the focus up
20023 the stack, that is to say from callee to caller, one frame at a time.
20025 @item down
20026 Moves the focus of @code{GDB} down from the frame currently being
20027 examined to the frame of its callee (the reverse of the previous command),
20029 @item frame @var{n}
20030 Inspect the frame with the given number. The value 0 denotes the frame
20031 of the current breakpoint, that is to say the top of the call stack.
20033 @end table
20035 @noindent
20036 The above list is a very short introduction to the commands that
20037 @code{GDB} provides. Important additional capabilities, including conditional
20038 breakpoints, the ability to execute command sequences on a breakpoint,
20039 the ability to debug at the machine instruction level and many other
20040 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20041 Debugging with GDB}.  Note that most commands can be abbreviated
20042 (for example, c for continue, bt for backtrace).
20044 @node Using Ada Expressions
20045 @section Using Ada Expressions
20046 @cindex Ada expressions
20048 @noindent
20049 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20050 extensions. The philosophy behind the design of this subset is
20052 @itemize @bullet
20053 @item
20054 That @code{GDB} should provide basic literals and access to operations for
20055 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20056 leaving more sophisticated computations to subprograms written into the
20057 program (which therefore may be called from @code{GDB}).
20059 @item
20060 That type safety and strict adherence to Ada language restrictions
20061 are not particularly important to the @code{GDB} user.
20063 @item
20064 That brevity is important to the @code{GDB} user.
20065 @end itemize
20067 @noindent
20068 Thus, for brevity, the debugger acts as if there were
20069 implicit @code{with} and @code{use} clauses in effect for all user-written
20070 packages, thus making it unnecessary to fully qualify most names with
20071 their packages, regardless of context. Where this causes ambiguity,
20072 @code{GDB} asks the user's intent.
20074 For details on the supported Ada syntax, see @ref{Top,, Debugging with
20075 GDB, gdb, Debugging with GDB}.
20077 @node Calling User-Defined Subprograms
20078 @section Calling User-Defined Subprograms
20080 @noindent
20081 An important capability of @code{GDB} is the ability to call user-defined
20082 subprograms while debugging. This is achieved simply by entering
20083 a subprogram call statement in the form:
20085 @smallexample
20086 call subprogram-name (parameters)
20087 @end smallexample
20089 @noindent
20090 The keyword @code{call} can be omitted in the normal case where the
20091 @code{subprogram-name} does not coincide with any of the predefined
20092 @code{GDB} commands.
20094 The effect is to invoke the given subprogram, passing it the
20095 list of parameters that is supplied. The parameters can be expressions and
20096 can include variables from the program being debugged. The
20097 subprogram must be defined
20098 at the library level within your program, and @code{GDB} will call the
20099 subprogram within the environment of your program execution (which
20100 means that the subprogram is free to access or even modify variables
20101 within your program).
20103 The most important use of this facility is in allowing the inclusion of
20104 debugging routines that are tailored to particular data structures
20105 in your program. Such debugging routines can be written to provide a suitably
20106 high-level description of an abstract type, rather than a low-level dump
20107 of its physical layout. After all, the standard
20108 @code{GDB print} command only knows the physical layout of your
20109 types, not their abstract meaning. Debugging routines can provide information
20110 at the desired semantic level and are thus enormously useful.
20112 For example, when debugging GNAT itself, it is crucial to have access to
20113 the contents of the tree nodes used to represent the program internally.
20114 But tree nodes are represented simply by an integer value (which in turn
20115 is an index into a table of nodes).
20116 Using the @code{print} command on a tree node would simply print this integer
20117 value, which is not very useful. But the PN routine (defined in file
20118 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20119 a useful high level representation of the tree node, which includes the
20120 syntactic category of the node, its position in the source, the integers
20121 that denote descendant nodes and parent node, as well as varied
20122 semantic information. To study this example in more detail, you might want to
20123 look at the body of the PN procedure in the stated file.
20125 @node Using the Next Command in a Function
20126 @section Using the Next Command in a Function
20128 @noindent
20129 When you use the @code{next} command in a function, the current source
20130 location will advance to the next statement as usual. A special case
20131 arises in the case of a @code{return} statement.
20133 Part of the code for a return statement is the ``epilog'' of the function.
20134 This is the code that returns to the caller. There is only one copy of
20135 this epilog code, and it is typically associated with the last return
20136 statement in the function if there is more than one return. In some
20137 implementations, this epilog is associated with the first statement
20138 of the function.
20140 The result is that if you use the @code{next} command from a return
20141 statement that is not the last return statement of the function you
20142 may see a strange apparent jump to the last return statement or to
20143 the start of the function. You should simply ignore this odd jump.
20144 The value returned is always that from the first return statement
20145 that was stepped through.
20147 @node Ada Exceptions
20148 @section Stopping when Ada Exceptions are Raised
20149 @cindex Exceptions
20151 @noindent
20152 You can set catchpoints that stop the program execution when your program
20153 raises selected exceptions.
20155 @table @code
20156 @item catch exception
20157 Set a catchpoint that stops execution whenever (any task in the) program
20158 raises any exception.
20160 @item catch exception @var{name}
20161 Set a catchpoint that stops execution whenever (any task in the) program
20162 raises the exception @var{name}.
20164 @item catch exception unhandled
20165 Set a catchpoint that stops executing whenever (any task in the) program
20166 raises an exception for which there is no handler.
20168 @item info exceptions
20169 @itemx info exceptions @var{regexp}
20170 The @code{info exceptions} command permits the user to examine all defined
20171 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20172 argument, prints out only those exceptions whose name matches @var{regexp}.
20173 @end table
20175 @node Ada Tasks
20176 @section Ada Tasks
20177 @cindex Tasks
20179 @noindent
20180 @code{GDB} allows the following task-related commands:
20182 @table @code
20183 @item info tasks
20184 This command shows a list of current Ada tasks, as in the following example:
20186 @smallexample
20187 @iftex
20188 @leftskip=0cm
20189 @end iftex
20190 (gdb) info tasks
20191   ID       TID P-ID   Thread Pri State                 Name
20192    1   8088000   0   807e000  15 Child Activation Wait main_task
20193    2   80a4000   1   80ae000  15 Accept/Select Wait    b
20194    3   809a800   1   80a4800  15 Child Activation Wait a
20195 *  4   80ae800   3   80b8000  15 Running               c
20196 @end smallexample
20198 @noindent
20199 In this listing, the asterisk before the first task indicates it to be the
20200 currently running task. The first column lists the task ID that is used
20201 to refer to tasks in the following commands.
20203 @item break @var{linespec} task @var{taskid}
20204 @itemx break @var{linespec} task @var{taskid} if @dots{}
20205 @cindex Breakpoints and tasks
20206 These commands are like the @code{break @dots{} thread @dots{}}.
20207 @var{linespec} specifies source lines.
20209 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20210 to specify that you only want @code{GDB} to stop the program when a
20211 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20212 numeric task identifiers assigned by @code{GDB}, shown in the first
20213 column of the @samp{info tasks} display.
20215 If you do not specify @samp{task @var{taskid}} when you set a
20216 breakpoint, the breakpoint applies to @emph{all} tasks of your
20217 program.
20219 You can use the @code{task} qualifier on conditional breakpoints as
20220 well; in this case, place @samp{task @var{taskid}} before the
20221 breakpoint condition (before the @code{if}).
20223 @item task @var{taskno}
20224 @cindex Task switching
20226 This command allows to switch to the task referred by @var{taskno}. In
20227 particular, This allows to browse the backtrace of the specified
20228 task. It is advised to switch back to the original task before
20229 continuing execution otherwise the scheduling of the program may be
20230 perturbed.
20231 @end table
20233 @noindent
20234 For more detailed information on the tasking support,
20235 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
20237 @node Debugging Generic Units
20238 @section Debugging Generic Units
20239 @cindex Debugging Generic Units
20240 @cindex Generics
20242 @noindent
20243 GNAT always uses code expansion for generic instantiation. This means that
20244 each time an instantiation occurs, a complete copy of the original code is
20245 made, with appropriate substitutions of formals by actuals.
20247 It is not possible to refer to the original generic entities in
20248 @code{GDB}, but it is always possible to debug a particular instance of
20249 a generic, by using the appropriate expanded names. For example, if we have
20251 @smallexample @c ada
20252 @group
20253 @cartouche
20254 procedure g is
20256    generic package k is
20257       procedure kp (v1 : in out integer);
20258    end k;
20260    package body k is
20261       procedure kp (v1 : in out integer) is
20262       begin
20263          v1 := v1 + 1;
20264       end kp;
20265    end k;
20267    package k1 is new k;
20268    package k2 is new k;
20270    var : integer := 1;
20272 begin
20273    k1.kp (var);
20274    k2.kp (var);
20275    k1.kp (var);
20276    k2.kp (var);
20277 end;
20278 @end cartouche
20279 @end group
20280 @end smallexample
20282 @noindent
20283 Then to break on a call to procedure kp in the k2 instance, simply
20284 use the command:
20286 @smallexample
20287 (gdb) break g.k2.kp
20288 @end smallexample
20290 @noindent
20291 When the breakpoint occurs, you can step through the code of the
20292 instance in the normal manner and examine the values of local variables, as for
20293 other units.
20295 @node Remote Debugging using gdbserver
20296 @section Remote Debugging using gdbserver
20297 @cindex Remote Debugging using gdbserver
20299 @noindent
20300 On platforms where gdbserver is supported, it is possible to use this tool
20301 to debug your application remotely.  This can be useful in situations
20302 where the program needs to be run on a target host that is different
20303 from the host used for development, particularly when the target has
20304 a limited amount of resources (either CPU and/or memory).
20306 To do so, start your program using gdbserver on the target machine.
20307 gdbserver then automatically suspends the execution of your program
20308 at its entry point, waiting for a debugger to connect to it.  The
20309 following commands starts an application and tells gdbserver to
20310 wait for a connection with the debugger on localhost port 4444.
20312 @smallexample
20313 $ gdbserver localhost:4444 program
20314 Process program created; pid = 5685
20315 Listening on port 4444
20316 @end smallexample
20318 Once gdbserver has started listening, we can tell the debugger to establish
20319 a connection with this gdbserver, and then start the same debugging session
20320 as if the program was being debugged on the same host, directly under
20321 the control of GDB.
20323 @smallexample
20324 $ gdb program
20325 (gdb) target remote targethost:4444
20326 Remote debugging using targethost:4444
20327 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
20328 (gdb) b foo.adb:3
20329 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
20330 (gdb) continue
20331 Continuing.
20333 Breakpoint 1, foo () at foo.adb:4
20334 4       end foo;
20335 @end smallexample
20337 It is also possible to use gdbserver to attach to an already running
20338 program, in which case the execution of that program is simply suspended
20339 until the connection between the debugger and gdbserver is established.
20341 For more information on how to use gdbserver, @ref{Top, Server, Using
20342 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
20343 for gdbserver on x86-linux, x86-windows and x86_64-linux.
20345 @node GNAT Abnormal Termination or Failure to Terminate
20346 @section GNAT Abnormal Termination or Failure to Terminate
20347 @cindex GNAT Abnormal Termination or Failure to Terminate
20349 @noindent
20350 When presented with programs that contain serious errors in syntax
20351 or semantics,
20352 GNAT may on rare occasions  experience problems in operation, such
20353 as aborting with a
20354 segmentation fault or illegal memory access, raising an internal
20355 exception, terminating abnormally, or failing to terminate at all.
20356 In such cases, you can activate
20357 various features of GNAT that can help you pinpoint the construct in your
20358 program that is the likely source of the problem.
20360 The following strategies are presented in increasing order of
20361 difficulty, corresponding to your experience in using GNAT and your
20362 familiarity with compiler internals.
20364 @enumerate
20365 @item
20366 Run @command{gcc} with the @option{-gnatf}. This first
20367 switch causes all errors on a given line to be reported. In its absence,
20368 only the first error on a line is displayed.
20370 The @option{-gnatdO} switch causes errors to be displayed as soon as they
20371 are encountered, rather than after compilation is terminated. If GNAT
20372 terminates prematurely or goes into an infinite loop, the last error
20373 message displayed may help to pinpoint the culprit.
20375 @item
20376 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
20377 mode, @command{gcc} produces ongoing information about the progress of the
20378 compilation and provides the name of each procedure as code is
20379 generated. This switch allows you to find which Ada procedure was being
20380 compiled when it encountered a code generation problem.
20382 @item
20383 @cindex @option{-gnatdc} switch
20384 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
20385 switch that does for the front-end what @option{^-v^VERBOSE^} does
20386 for the back end. The system prints the name of each unit,
20387 either a compilation unit or nested unit, as it is being analyzed.
20388 @item
20389 Finally, you can start
20390 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
20391 front-end of GNAT, and can be run independently (normally it is just
20392 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
20393 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
20394 @code{where} command is the first line of attack; the variable
20395 @code{lineno} (seen by @code{print lineno}), used by the second phase of
20396 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
20397 which the execution stopped, and @code{input_file name} indicates the name of
20398 the source file.
20399 @end enumerate
20401 @node Naming Conventions for GNAT Source Files
20402 @section Naming Conventions for GNAT Source Files
20404 @noindent
20405 In order to examine the workings of the GNAT system, the following
20406 brief description of its organization may be helpful:
20408 @itemize @bullet
20409 @item
20410 Files with prefix @file{^sc^SC^} contain the lexical scanner.
20412 @item
20413 All files prefixed with @file{^par^PAR^} are components of the parser. The
20414 numbers correspond to chapters of the Ada Reference Manual. For example,
20415 parsing of select statements can be found in @file{par-ch9.adb}.
20417 @item
20418 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
20419 numbers correspond to chapters of the Ada standard. For example, all
20420 issues involving context clauses can be found in @file{sem_ch10.adb}. In
20421 addition, some features of the language require sufficient special processing
20422 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
20423 dynamic dispatching, etc.
20425 @item
20426 All files prefixed with @file{^exp^EXP^} perform normalization and
20427 expansion of the intermediate representation (abstract syntax tree, or AST).
20428 these files use the same numbering scheme as the parser and semantics files.
20429 For example, the construction of record initialization procedures is done in
20430 @file{exp_ch3.adb}.
20432 @item
20433 The files prefixed with @file{^bind^BIND^} implement the binder, which
20434 verifies the consistency of the compilation, determines an order of
20435 elaboration, and generates the bind file.
20437 @item
20438 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20439 data structures used by the front-end.
20441 @item
20442 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20443 the abstract syntax tree as produced by the parser.
20445 @item
20446 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20447 all entities, computed during semantic analysis.
20449 @item
20450 Library management issues are dealt with in files with prefix
20451 @file{^lib^LIB^}.
20453 @item
20454 @findex Ada
20455 @cindex Annex A
20456 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20457 defined in Annex A.
20459 @item
20460 @findex Interfaces
20461 @cindex Annex B
20462 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20463 defined in Annex B.
20465 @item
20466 @findex System
20467 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20468 both language-defined children and GNAT run-time routines.
20470 @item
20471 @findex GNAT
20472 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
20473 general-purpose packages, fully documented in their specs. All
20474 the other @file{.c} files are modifications of common @command{gcc} files.
20475 @end itemize
20477 @node Getting Internal Debugging Information
20478 @section Getting Internal Debugging Information
20480 @noindent
20481 Most compilers have internal debugging switches and modes. GNAT
20482 does also, except GNAT internal debugging switches and modes are not
20483 secret. A summary and full description of all the compiler and binder
20484 debug flags are in the file @file{debug.adb}. You must obtain the
20485 sources of the compiler to see the full detailed effects of these flags.
20487 The switches that print the source of the program (reconstructed from
20488 the internal tree) are of general interest for user programs, as are the
20489 options to print
20490 the full internal tree, and the entity table (the symbol table
20491 information). The reconstructed source provides a readable version of the
20492 program after the front-end has completed analysis and  expansion,
20493 and is useful when studying the performance of specific constructs.
20494 For example, constraint checks are indicated, complex aggregates
20495 are replaced with loops and assignments, and tasking primitives
20496 are replaced with run-time calls.
20498 @node Stack Traceback
20499 @section Stack Traceback
20500 @cindex traceback
20501 @cindex stack traceback
20502 @cindex stack unwinding
20504 @noindent
20505 Traceback is a mechanism to display the sequence of subprogram calls that
20506 leads to a specified execution point in a program. Often (but not always)
20507 the execution point is an instruction at which an exception has been raised.
20508 This mechanism is also known as @i{stack unwinding} because it obtains
20509 its information by scanning the run-time stack and recovering the activation
20510 records of all active subprograms. Stack unwinding is one of the most
20511 important tools for program debugging.
20513 The first entry stored in traceback corresponds to the deepest calling level,
20514 that is to say the subprogram currently executing the instruction
20515 from which we want to obtain the traceback.
20517 Note that there is no runtime performance penalty when stack traceback
20518 is enabled, and no exception is raised during program execution.
20520 @menu
20521 * Non-Symbolic Traceback::
20522 * Symbolic Traceback::
20523 @end menu
20525 @node Non-Symbolic Traceback
20526 @subsection Non-Symbolic Traceback
20527 @cindex traceback, non-symbolic
20529 @noindent
20530 Note: this feature is not supported on all platforms. See
20531 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20532 platforms.
20534 @menu
20535 * Tracebacks From an Unhandled Exception::
20536 * Tracebacks From Exception Occurrences (non-symbolic)::
20537 * Tracebacks From Anywhere in a Program (non-symbolic)::
20538 @end menu
20540 @node Tracebacks From an Unhandled Exception
20541 @subsubsection Tracebacks From an Unhandled Exception
20543 @noindent
20544 A runtime non-symbolic traceback is a list of addresses of call instructions.
20545 To enable this feature you must use the @option{-E}
20546 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20547 of exception information. You can retrieve this information using the
20548 @code{addr2line} tool.
20550 Here is a simple example:
20552 @smallexample @c ada
20553 @cartouche
20554 procedure STB is
20556    procedure P1 is
20557    begin
20558       raise Constraint_Error;
20559    end P1;
20561    procedure P2 is
20562    begin
20563       P1;
20564    end P2;
20566 begin
20567    P2;
20568 end STB;
20569 @end cartouche
20570 @end smallexample
20572 @smallexample
20573 $ gnatmake stb -bargs -E
20574 $ stb
20576 Execution terminated by unhandled exception
20577 Exception name: CONSTRAINT_ERROR
20578 Message: stb.adb:5
20579 Call stack traceback locations:
20580 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20581 @end smallexample
20583 @noindent
20584 As we see the traceback lists a sequence of addresses for the unhandled
20585 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20586 guess that this exception come from procedure P1. To translate these
20587 addresses into the source lines where the calls appear, the
20588 @code{addr2line} tool, described below, is invaluable. The use of this tool
20589 requires the program to be compiled with debug information.
20591 @smallexample
20592 $ gnatmake -g stb -bargs -E
20593 $ stb
20595 Execution terminated by unhandled exception
20596 Exception name: CONSTRAINT_ERROR
20597 Message: stb.adb:5
20598 Call stack traceback locations:
20599 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20601 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20602    0x4011f1 0x77e892a4
20604 00401373 at d:/stb/stb.adb:5
20605 0040138B at d:/stb/stb.adb:10
20606 0040139C at d:/stb/stb.adb:14
20607 00401335 at d:/stb/b~stb.adb:104
20608 004011C4 at /build/@dots{}/crt1.c:200
20609 004011F1 at /build/@dots{}/crt1.c:222
20610 77E892A4 in ?? at ??:0
20611 @end smallexample
20613 @noindent
20614 The @code{addr2line} tool has several other useful options:
20616 @table @code
20617 @item --functions
20618 to get the function name corresponding to any location
20620 @item --demangle=gnat
20621 to use the gnat decoding mode for the function names. Note that
20622 for binutils version 2.9.x the option is simply @option{--demangle}.
20623 @end table
20625 @smallexample
20626 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20627    0x40139c 0x401335 0x4011c4 0x4011f1
20629 00401373 in stb.p1 at d:/stb/stb.adb:5
20630 0040138B in stb.p2 at d:/stb/stb.adb:10
20631 0040139C in stb at d:/stb/stb.adb:14
20632 00401335 in main at d:/stb/b~stb.adb:104
20633 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
20634 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
20635 @end smallexample
20637 @noindent
20638 From this traceback we can see that the exception was raised in
20639 @file{stb.adb} at line 5, which was reached from a procedure call in
20640 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20641 which contains the call to the main program.
20642 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20643 and the output will vary from platform to platform.
20645 It is also possible to use @code{GDB} with these traceback addresses to debug
20646 the program. For example, we can break at a given code location, as reported
20647 in the stack traceback:
20649 @smallexample
20650 $ gdb -nw stb
20651 @ifclear vms
20652 @noindent
20653 Furthermore, this feature is not implemented inside Windows DLL. Only
20654 the non-symbolic traceback is reported in this case.
20655 @end ifclear
20657 (gdb) break *0x401373
20658 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20659 @end smallexample
20661 @noindent
20662 It is important to note that the stack traceback addresses
20663 do not change when debug information is included. This is particularly useful
20664 because it makes it possible to release software without debug information (to
20665 minimize object size), get a field report that includes a stack traceback
20666 whenever an internal bug occurs, and then be able to retrieve the sequence
20667 of calls with the same program compiled with debug information.
20669 @node Tracebacks From Exception Occurrences (non-symbolic)
20670 @subsubsection Tracebacks From Exception Occurrences
20672 @noindent
20673 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20674 The stack traceback is attached to the exception information string, and can
20675 be retrieved in an exception handler within the Ada program, by means of the
20676 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20678 @smallexample @c ada
20679 with Ada.Text_IO;
20680 with Ada.Exceptions;
20682 procedure STB is
20684    use Ada;
20685    use Ada.Exceptions;
20687    procedure P1 is
20688       K : Positive := 1;
20689    begin
20690       K := K - 1;
20691    exception
20692       when E : others =>
20693          Text_IO.Put_Line (Exception_Information (E));
20694    end P1;
20696    procedure P2 is
20697    begin
20698       P1;
20699    end P2;
20701 begin
20702    P2;
20703 end STB;
20704 @end smallexample
20706 @noindent
20707 This program will output:
20709 @smallexample
20710 $ stb
20712 Exception name: CONSTRAINT_ERROR
20713 Message: stb.adb:12
20714 Call stack traceback locations:
20715 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20716 @end smallexample
20718 @node Tracebacks From Anywhere in a Program (non-symbolic)
20719 @subsubsection Tracebacks From Anywhere in a Program
20721 @noindent
20722 It is also possible to retrieve a stack traceback from anywhere in a
20723 program. For this you need to
20724 use the @code{GNAT.Traceback} API. This package includes a procedure called
20725 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20726 display procedures described below. It is not necessary to use the
20727 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20728 is invoked explicitly.
20730 @noindent
20731 In the following example we compute a traceback at a specific location in
20732 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20733 convert addresses to strings:
20735 @smallexample @c ada
20736 with Ada.Text_IO;
20737 with GNAT.Traceback;
20738 with GNAT.Debug_Utilities;
20740 procedure STB is
20742    use Ada;
20743    use GNAT;
20744    use GNAT.Traceback;
20746    procedure P1 is
20747       TB  : Tracebacks_Array (1 .. 10);
20748       --  We are asking for a maximum of 10 stack frames.
20749       Len : Natural;
20750       --  Len will receive the actual number of stack frames returned.
20751    begin
20752       Call_Chain (TB, Len);
20754       Text_IO.Put ("In STB.P1 : ");
20756       for K in 1 .. Len loop
20757          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20758          Text_IO.Put (' ');
20759       end loop;
20761       Text_IO.New_Line;
20762    end P1;
20764    procedure P2 is
20765    begin
20766       P1;
20767    end P2;
20769 begin
20770    P2;
20771 end STB;
20772 @end smallexample
20774 @smallexample
20775 $ gnatmake -g stb
20776 $ stb
20778 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20779 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20780 @end smallexample
20782 @noindent
20783 You can then get further information by invoking the @code{addr2line}
20784 tool as described earlier (note that the hexadecimal addresses
20785 need to be specified in C format, with a leading ``0x'').
20787 @node Symbolic Traceback
20788 @subsection Symbolic Traceback
20789 @cindex traceback, symbolic
20791 @noindent
20792 A symbolic traceback is a stack traceback in which procedure names are
20793 associated with each code location.
20795 @noindent
20796 Note that this feature is not supported on all platforms. See
20797 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20798 list of currently supported platforms.
20800 @noindent
20801 Note that the symbolic traceback requires that the program be compiled
20802 with debug information. If it is not compiled with debug information
20803 only the non-symbolic information will be valid.
20805 @menu
20806 * Tracebacks From Exception Occurrences (symbolic)::
20807 * Tracebacks From Anywhere in a Program (symbolic)::
20808 @end menu
20810 @node Tracebacks From Exception Occurrences (symbolic)
20811 @subsubsection Tracebacks From Exception Occurrences
20813 @smallexample @c ada
20814 with Ada.Text_IO;
20815 with GNAT.Traceback.Symbolic;
20817 procedure STB is
20819    procedure P1 is
20820    begin
20821       raise Constraint_Error;
20822    end P1;
20824    procedure P2 is
20825    begin
20826       P1;
20827    end P2;
20829    procedure P3 is
20830    begin
20831       P2;
20832    end P3;
20834 begin
20835    P3;
20836 exception
20837    when E : others =>
20838       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20839 end STB;
20840 @end smallexample
20842 @smallexample
20843 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20844 $ stb
20846 0040149F in stb.p1 at stb.adb:8
20847 004014B7 in stb.p2 at stb.adb:13
20848 004014CF in stb.p3 at stb.adb:18
20849 004015DD in ada.stb at stb.adb:22
20850 00401461 in main at b~stb.adb:168
20851 004011C4 in __mingw_CRTStartup at crt1.c:200
20852 004011F1 in mainCRTStartup at crt1.c:222
20853 77E892A4 in ?? at ??:0
20854 @end smallexample
20856 @noindent
20857 In the above example the ``.\'' syntax in the @command{gnatmake} command
20858 is currently required by @command{addr2line} for files that are in
20859 the current working directory.
20860 Moreover, the exact sequence of linker options may vary from platform
20861 to platform.
20862 The above @option{-largs} section is for Windows platforms. By contrast,
20863 under Unix there is no need for the @option{-largs} section.
20864 Differences across platforms are due to details of linker implementation.
20866 @node Tracebacks From Anywhere in a Program (symbolic)
20867 @subsubsection Tracebacks From Anywhere in a Program
20869 @noindent
20870 It is possible to get a symbolic stack traceback
20871 from anywhere in a program, just as for non-symbolic tracebacks.
20872 The first step is to obtain a non-symbolic
20873 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20874 information. Here is an example:
20876 @smallexample @c ada
20877 with Ada.Text_IO;
20878 with GNAT.Traceback;
20879 with GNAT.Traceback.Symbolic;
20881 procedure STB is
20883    use Ada;
20884    use GNAT.Traceback;
20885    use GNAT.Traceback.Symbolic;
20887    procedure P1 is
20888       TB  : Tracebacks_Array (1 .. 10);
20889       --  We are asking for a maximum of 10 stack frames.
20890       Len : Natural;
20891       --  Len will receive the actual number of stack frames returned.
20892    begin
20893       Call_Chain (TB, Len);
20894       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20895    end P1;
20897    procedure P2 is
20898    begin
20899       P1;
20900    end P2;
20902 begin
20903    P2;
20904 end STB;
20905 @end smallexample
20907 @c ******************************
20908 @ifset vms
20909 @node Compatibility with HP Ada
20910 @chapter Compatibility with HP Ada
20911 @cindex Compatibility
20913 @noindent
20914 @cindex DEC Ada
20915 @cindex HP Ada
20916 @cindex Compatibility between GNAT and HP Ada
20917 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20918 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20919 GNAT is highly compatible
20920 with HP Ada, and it should generally be straightforward to port code
20921 from the HP Ada environment to GNAT. However, there are a few language
20922 and implementation differences of which the user must be aware. These
20923 differences are discussed in this chapter. In
20924 addition, the operating environment and command structure for the
20925 compiler are different, and these differences are also discussed.
20927 For further details on these and other compatibility issues,
20928 see Appendix E of the HP publication
20929 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20931 Except where otherwise indicated, the description of GNAT for OpenVMS
20932 applies to both the Alpha and I64 platforms.
20934 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20935 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20937 The discussion in this chapter addresses specifically the implementation
20938 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20939 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20940 GNAT always follows the Alpha implementation.
20942 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20943 attributes are recognized, although only a subset of them can sensibly
20944 be implemented.  The description of pragmas in
20945 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20946 indicates whether or not they are applicable to non-VMS systems.
20948 @menu
20949 * Ada Language Compatibility::
20950 * Differences in the Definition of Package System::
20951 * Language-Related Features::
20952 * The Package STANDARD::
20953 * The Package SYSTEM::
20954 * Tasking and Task-Related Features::
20955 * Pragmas and Pragma-Related Features::
20956 * Library of Predefined Units::
20957 * Bindings::
20958 * Main Program Definition::
20959 * Implementation-Defined Attributes::
20960 * Compiler and Run-Time Interfacing::
20961 * Program Compilation and Library Management::
20962 * Input-Output::
20963 * Implementation Limits::
20964 * Tools and Utilities::
20965 @end menu
20967 @node Ada Language Compatibility
20968 @section Ada Language Compatibility
20970 @noindent
20971 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20972 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20973 with Ada 83, and therefore Ada 83 programs will compile
20974 and run under GNAT with
20975 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20976 provides details on specific incompatibilities.
20978 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20979 as well as the pragma @code{ADA_83}, to force the compiler to
20980 operate in Ada 83 mode. This mode does not guarantee complete
20981 conformance to Ada 83, but in practice is sufficient to
20982 eliminate most sources of incompatibilities.
20983 In particular, it eliminates the recognition of the
20984 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20985 in Ada 83 programs is legal, and handles the cases of packages
20986 with optional bodies, and generics that instantiate unconstrained
20987 types without the use of @code{(<>)}.
20989 @node Differences in the Definition of Package System
20990 @section Differences in the Definition of Package @code{System}
20992 @noindent
20993 An Ada compiler is allowed to add
20994 implementation-dependent declarations to package @code{System}.
20995 In normal mode,
20996 GNAT does not take advantage of this permission, and the version of
20997 @code{System} provided by GNAT exactly matches that defined in the Ada
20998 Reference Manual.
21000 However, HP Ada adds an extensive set of declarations to package
21001 @code{System},
21002 as fully documented in the HP Ada manuals. To minimize changes required
21003 for programs that make use of these extensions, GNAT provides the pragma
21004 @code{Extend_System} for extending the definition of package System. By using:
21005 @cindex pragma @code{Extend_System}
21006 @cindex @code{Extend_System} pragma
21008 @smallexample @c ada
21009 @group
21010 @cartouche
21011 pragma Extend_System (Aux_DEC);
21012 @end cartouche
21013 @end group
21014 @end smallexample
21016 @noindent
21017 the set of definitions in @code{System} is extended to include those in
21018 package @code{System.Aux_DEC}.
21019 @cindex @code{System.Aux_DEC} package
21020 @cindex @code{Aux_DEC} package (child of @code{System})
21021 These definitions are incorporated directly into package @code{System},
21022 as though they had been declared there. For a
21023 list of the declarations added, see the spec of this package,
21024 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21025 @cindex @file{s-auxdec.ads} file
21026 The pragma @code{Extend_System} is a configuration pragma, which means that
21027 it can be placed in the file @file{gnat.adc}, so that it will automatically
21028 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21029 for further details.
21031 An alternative approach that avoids the use of the non-standard
21032 @code{Extend_System} pragma is to add a context clause to the unit that
21033 references these facilities:
21035 @smallexample @c ada
21036 @cartouche
21037 with System.Aux_DEC;
21038 use  System.Aux_DEC;
21039 @end cartouche
21040 @end smallexample
21042 @noindent
21043 The effect is not quite semantically identical to incorporating
21044 the declarations directly into package @code{System},
21045 but most programs will not notice a difference
21046 unless they use prefix notation (e.g.@: @code{System.Integer_8})
21047 to reference the entities directly in package @code{System}.
21048 For units containing such references,
21049 the prefixes must either be removed, or the pragma @code{Extend_System}
21050 must be used.
21052 @node Language-Related Features
21053 @section Language-Related Features
21055 @noindent
21056 The following sections highlight differences in types,
21057 representations of types, operations, alignment, and
21058 related topics.
21060 @menu
21061 * Integer Types and Representations::
21062 * Floating-Point Types and Representations::
21063 * Pragmas Float_Representation and Long_Float::
21064 * Fixed-Point Types and Representations::
21065 * Record and Array Component Alignment::
21066 * Address Clauses::
21067 * Other Representation Clauses::
21068 @end menu
21070 @node Integer Types and Representations
21071 @subsection Integer Types and Representations
21073 @noindent
21074 The set of predefined integer types is identical in HP Ada and GNAT.
21075 Furthermore the representation of these integer types is also identical,
21076 including the capability of size clauses forcing biased representation.
21078 In addition,
21079 HP Ada for OpenVMS Alpha systems has defined the
21080 following additional integer types in package @code{System}:
21082 @itemize @bullet
21084 @item
21085 @code{INTEGER_8}
21087 @item
21088 @code{INTEGER_16}
21090 @item
21091 @code{INTEGER_32}
21093 @item
21094 @code{INTEGER_64}
21096 @item
21097 @code{LARGEST_INTEGER}
21098 @end itemize
21100 @noindent
21101 In GNAT, the first four of these types may be obtained from the
21102 standard Ada package @code{Interfaces}.
21103 Alternatively, by use of the pragma @code{Extend_System}, identical
21104 declarations can be referenced directly in package @code{System}.
21105 On both GNAT and HP Ada, the maximum integer size is 64 bits.
21107 @node Floating-Point Types and Representations
21108 @subsection Floating-Point Types and Representations
21109 @cindex Floating-Point types
21111 @noindent
21112 The set of predefined floating-point types is identical in HP Ada and GNAT.
21113 Furthermore the representation of these floating-point
21114 types is also identical. One important difference is that the default
21115 representation for HP Ada is @code{VAX_Float}, but the default representation
21116 for GNAT is IEEE.
21118 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
21119 pragma @code{Float_Representation} as described in the HP Ada
21120 documentation.
21121 For example, the declarations:
21123 @smallexample @c ada
21124 @cartouche
21125 type F_Float is digits 6;
21126 pragma Float_Representation (VAX_Float, F_Float);
21127 @end cartouche
21128 @end smallexample
21130 @noindent
21131 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21132 format.
21133 This set of declarations actually appears in @code{System.Aux_DEC},
21134 which contains
21135 the full set of additional floating-point declarations provided in
21136 the HP Ada version of package @code{System}.
21137 This and similar declarations may be accessed in a user program
21138 by using pragma @code{Extend_System}. The use of this
21139 pragma, and the related pragma @code{Long_Float} is described in further
21140 detail in the following section.
21142 @node Pragmas Float_Representation and Long_Float
21143 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
21145 @noindent
21146 HP Ada provides the pragma @code{Float_Representation}, which
21147 acts as a program library switch to allow control over
21148 the internal representation chosen for the predefined
21149 floating-point types declared in the package @code{Standard}.
21150 The format of this pragma is as follows:
21152 @smallexample @c ada
21153 @cartouche
21154 pragma Float_Representation(VAX_Float | IEEE_Float);
21155 @end cartouche
21156 @end smallexample
21158 @noindent
21159 This pragma controls the representation of floating-point
21160 types as follows:
21162 @itemize @bullet
21163 @item
21164 @code{VAX_Float} specifies that floating-point
21165 types are represented by default with the VAX system hardware types
21166 @code{F-floating}, @code{D-floating}, @code{G-floating}.
21167 Note that the @code{H-floating}
21168 type was available only on VAX systems, and is not available
21169 in either HP Ada or GNAT.
21171 @item
21172 @code{IEEE_Float} specifies that floating-point
21173 types are represented by default with the IEEE single and
21174 double floating-point types.
21175 @end itemize
21177 @noindent
21178 GNAT provides an identical implementation of the pragma
21179 @code{Float_Representation}, except that it functions as a
21180 configuration pragma. Note that the
21181 notion of configuration pragma corresponds closely to the
21182 HP Ada notion of a program library switch.
21184 When no pragma is used in GNAT, the default is @code{IEEE_Float},
21185 which is different
21186 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
21187 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
21188 advisable to change the format of numbers passed to standard library
21189 routines, and if necessary explicit type conversions may be needed.
21191 The use of @code{IEEE_Float} is recommended in GNAT since it is more
21192 efficient, and (given that it conforms to an international standard)
21193 potentially more portable.
21194 The situation in which @code{VAX_Float} may be useful is in interfacing
21195 to existing code and data that expect the use of @code{VAX_Float}.
21196 In such a situation use the predefined @code{VAX_Float}
21197 types in package @code{System}, as extended by
21198 @code{Extend_System}. For example, use @code{System.F_Float}
21199 to specify the 32-bit @code{F-Float} format.
21201 @noindent
21202 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
21203 to allow control over the internal representation chosen
21204 for the predefined type @code{Long_Float} and for floating-point
21205 type declarations with digits specified in the range 7 .. 15.
21206 The format of this pragma is as follows:
21208 @smallexample @c ada
21209 @cartouche
21210 pragma Long_Float (D_FLOAT | G_FLOAT);
21211 @end cartouche
21212 @end smallexample
21214 @node Fixed-Point Types and Representations
21215 @subsection Fixed-Point Types and Representations
21217 @noindent
21218 On HP Ada for OpenVMS Alpha systems, rounding is
21219 away from zero for both positive and negative numbers.
21220 Therefore, @code{+0.5} rounds to @code{1},
21221 and @code{-0.5} rounds to @code{-1}.
21223 On GNAT the results of operations
21224 on fixed-point types are in accordance with the Ada
21225 rules. In particular, results of operations on decimal
21226 fixed-point types are truncated.
21228 @node Record and Array Component Alignment
21229 @subsection Record and Array Component Alignment
21231 @noindent
21232 On HP Ada for OpenVMS Alpha, all non-composite components
21233 are aligned on natural boundaries. For example, 1-byte
21234 components are aligned on byte boundaries, 2-byte
21235 components on 2-byte boundaries, 4-byte components on 4-byte
21236 byte boundaries, and so on. The OpenVMS Alpha hardware
21237 runs more efficiently with naturally aligned data.
21239 On GNAT, alignment rules are compatible
21240 with HP Ada for OpenVMS Alpha.
21242 @node Address Clauses
21243 @subsection Address Clauses
21245 @noindent
21246 In HP Ada and GNAT, address clauses are supported for
21247 objects and imported subprograms.
21248 The predefined type @code{System.Address} is a private type
21249 in both compilers on Alpha OpenVMS, with the same representation
21250 (it is simply a machine pointer). Addition, subtraction, and comparison
21251 operations are available in the standard Ada package
21252 @code{System.Storage_Elements}, or in package @code{System}
21253 if it is extended to include @code{System.Aux_DEC} using a
21254 pragma @code{Extend_System} as previously described.
21256 Note that code that @code{with}'s both this extended package @code{System}
21257 and the package @code{System.Storage_Elements} should not @code{use}
21258 both packages, or ambiguities will result. In general it is better
21259 not to mix these two sets of facilities. The Ada package was
21260 designed specifically to provide the kind of features that HP Ada
21261 adds directly to package @code{System}.
21263 The type @code{System.Address} is a 64-bit integer type in GNAT for
21264 I64 OpenVMS.  For more information,
21265 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21267 GNAT is compatible with HP Ada in its handling of address
21268 clauses, except for some limitations in
21269 the form of address clauses for composite objects with
21270 initialization. Such address clauses are easily replaced
21271 by the use of an explicitly-defined constant as described
21272 in the Ada Reference Manual (13.1(22)). For example, the sequence
21273 of declarations:
21275 @smallexample @c ada
21276 @cartouche
21277 X, Y : Integer := Init_Func;
21278 Q : String (X .. Y) := "abc";
21279 @dots{}
21280 for Q'Address use Compute_Address;
21281 @end cartouche
21282 @end smallexample
21284 @noindent
21285 will be rejected by GNAT, since the address cannot be computed at the time
21286 that @code{Q} is declared. To achieve the intended effect, write instead:
21288 @smallexample @c ada
21289 @group
21290 @cartouche
21291 X, Y : Integer := Init_Func;
21292 Q_Address : constant Address := Compute_Address;
21293 Q : String (X .. Y) := "abc";
21294 @dots{}
21295 for Q'Address use Q_Address;
21296 @end cartouche
21297 @end group
21298 @end smallexample
21300 @noindent
21301 which will be accepted by GNAT (and other Ada compilers), and is also
21302 compatible with Ada 83. A fuller description of the restrictions
21303 on address specifications is found in @ref{Top, GNAT Reference Manual,
21304 About This Guide, gnat_rm, GNAT Reference Manual}.
21306 @node Other Representation Clauses
21307 @subsection Other Representation Clauses
21309 @noindent
21310 GNAT implements in a compatible manner all the representation
21311 clauses supported by HP Ada. In addition, GNAT
21312 implements the representation clause forms that were introduced in Ada 95,
21313 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
21315 @node The Package STANDARD
21316 @section The Package @code{STANDARD}
21318 @noindent
21319 The package @code{STANDARD}, as implemented by HP Ada, is fully
21320 described in the @cite{Ada Reference Manual} and in the
21321 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
21322 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
21324 In addition, HP Ada supports the Latin-1 character set in
21325 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
21326 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
21327 the type @code{WIDE_CHARACTER}.
21329 The floating-point types supported by GNAT are those
21330 supported by HP Ada, but the defaults are different, and are controlled by
21331 pragmas. See @ref{Floating-Point Types and Representations}, for details.
21333 @node The Package SYSTEM
21334 @section The Package @code{SYSTEM}
21336 @noindent
21337 HP Ada provides a specific version of the package
21338 @code{SYSTEM} for each platform on which the language is implemented.
21339 For the complete spec of the package @code{SYSTEM}, see
21340 Appendix F of the @cite{HP Ada Language Reference Manual}.
21342 On HP Ada, the package @code{SYSTEM} includes the following conversion
21343 functions:
21344 @itemize @bullet
21345 @item @code{TO_ADDRESS(INTEGER)}
21347 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
21349 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
21351 @item @code{TO_INTEGER(ADDRESS)}
21353 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
21355 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
21356 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
21357 @end itemize
21359 @noindent
21360 By default, GNAT supplies a version of @code{SYSTEM} that matches
21361 the definition given in the @cite{Ada Reference Manual}.
21362 This
21363 is a subset of the HP system definitions, which is as
21364 close as possible to the original definitions. The only difference
21365 is that the definition of @code{SYSTEM_NAME} is different:
21367 @smallexample @c ada
21368 @cartouche
21369 type Name is (SYSTEM_NAME_GNAT);
21370 System_Name : constant Name := SYSTEM_NAME_GNAT;
21371 @end cartouche
21372 @end smallexample
21374 @noindent
21375 Also, GNAT adds the Ada declarations for
21376 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
21378 However, the use of the following pragma causes GNAT
21379 to extend the definition of package @code{SYSTEM} so that it
21380 encompasses the full set of HP-specific extensions,
21381 including the functions listed above:
21383 @smallexample @c ada
21384 @cartouche
21385 pragma Extend_System (Aux_DEC);
21386 @end cartouche
21387 @end smallexample
21389 @noindent
21390 The pragma @code{Extend_System} is a configuration pragma that
21391 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
21392 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
21394 HP Ada does not allow the recompilation of the package
21395 @code{SYSTEM}. Instead HP Ada provides several pragmas
21396 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
21397 to modify values in the package @code{SYSTEM}.
21398 On OpenVMS Alpha systems, the pragma
21399 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
21400 its single argument.
21402 GNAT does permit the recompilation of package @code{SYSTEM} using
21403 the special switch @option{-gnatg}, and this switch can be used if
21404 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
21405 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
21406 or @code{MEMORY_SIZE} by any other means.
21408 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
21409 enumeration literal @code{SYSTEM_NAME_GNAT}.
21411 The definitions provided by the use of
21413 @smallexample @c ada
21414 pragma Extend_System (AUX_Dec);
21415 @end smallexample
21417 @noindent
21418 are virtually identical to those provided by the HP Ada 83 package
21419 @code{SYSTEM}. One important difference is that the name of the
21420 @code{TO_ADDRESS}
21421 function for type @code{UNSIGNED_LONGWORD} is changed to
21422 @code{TO_ADDRESS_LONG}.
21423 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
21424 discussion of why this change was necessary.
21426 @noindent
21427 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
21428 is in fact
21429 an extension to Ada 83 not strictly compatible with the reference manual.
21430 GNAT, in order to be exactly compatible with the standard,
21431 does not provide this capability. In HP Ada 83, the
21432 point of this definition is to deal with a call like:
21434 @smallexample @c ada
21435 TO_ADDRESS (16#12777#);
21436 @end smallexample
21438 @noindent
21439 Normally, according to Ada 83 semantics, one would expect this to be
21440 ambiguous, since it matches both the @code{INTEGER} and
21441 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
21442 However, in HP Ada 83, there is no ambiguity, since the
21443 definition using @i{universal_integer} takes precedence.
21445 In GNAT, since the version with @i{universal_integer} cannot be supplied,
21446 it is
21447 not possible to be 100% compatible. Since there are many programs using
21448 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
21449 GNAT was
21450 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
21451 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
21453 @smallexample @c ada
21454 function To_Address (X : Integer) return Address;
21455 pragma Pure_Function (To_Address);
21457 function To_Address_Long (X : Unsigned_Longword) return Address;
21458 pragma Pure_Function (To_Address_Long);
21459 @end smallexample
21461 @noindent
21462 This means that programs using @code{TO_ADDRESS} for
21463 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
21465 @node Tasking and Task-Related Features
21466 @section Tasking and Task-Related Features
21468 @noindent
21469 This section compares the treatment of tasking in GNAT
21470 and in HP Ada for OpenVMS Alpha.
21471 The GNAT description applies to both Alpha and I64 OpenVMS.
21472 For detailed information on tasking in
21473 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
21474 relevant run-time reference manual.
21476 @menu
21477 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
21478 * Assigning Task IDs::
21479 * Task IDs and Delays::
21480 * Task-Related Pragmas::
21481 * Scheduling and Task Priority::
21482 * The Task Stack::
21483 * External Interrupts::
21484 @end menu
21486 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21487 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21489 @noindent
21490 On OpenVMS Alpha systems, each Ada task (except a passive
21491 task) is implemented as a single stream of execution
21492 that is created and managed by the kernel. On these
21493 systems, HP Ada tasking support is based on DECthreads,
21494 an implementation of the POSIX standard for threads.
21496 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
21497 code that calls DECthreads routines can be used together.
21498 The interaction between Ada tasks and DECthreads routines
21499 can have some benefits. For example when on OpenVMS Alpha,
21500 HP Ada can call C code that is already threaded.
21502 GNAT uses the facilities of DECthreads,
21503 and Ada tasks are mapped to threads.
21505 @node Assigning Task IDs
21506 @subsection Assigning Task IDs
21508 @noindent
21509 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
21510 the environment task that executes the main program. On
21511 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21512 that have been created but are not yet activated.
21514 On OpenVMS Alpha systems, task IDs are assigned at
21515 activation. On GNAT systems, task IDs are also assigned at
21516 task creation but do not have the same form or values as
21517 task ID values in HP Ada. There is no null task, and the
21518 environment task does not have a specific task ID value.
21520 @node Task IDs and Delays
21521 @subsection Task IDs and Delays
21523 @noindent
21524 On OpenVMS Alpha systems, tasking delays are implemented
21525 using Timer System Services. The Task ID is used for the
21526 identification of the timer request (the @code{REQIDT} parameter).
21527 If Timers are used in the application take care not to use
21528 @code{0} for the identification, because cancelling such a timer
21529 will cancel all timers and may lead to unpredictable results.
21531 @node Task-Related Pragmas
21532 @subsection Task-Related Pragmas
21534 @noindent
21535 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21536 specification of the size of the guard area for a task
21537 stack. (The guard area forms an area of memory that has no
21538 read or write access and thus helps in the detection of
21539 stack overflow.) On OpenVMS Alpha systems, if the pragma
21540 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21541 area is created. In the absence of a pragma @code{TASK_STORAGE},
21542 a default guard area is created.
21544 GNAT supplies the following task-related pragmas:
21546 @itemize @bullet
21547 @item  @code{TASK_INFO}
21549 This pragma appears within a task definition and
21550 applies to the task in which it appears. The argument
21551 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21553 @item  @code{TASK_STORAGE}
21555 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
21556 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21557 @code{SUPPRESS}, and @code{VOLATILE}.
21558 @end itemize
21559 @node Scheduling and Task Priority
21560 @subsection Scheduling and Task Priority
21562 @noindent
21563 HP Ada implements the Ada language requirement that
21564 when two tasks are eligible for execution and they have
21565 different priorities, the lower priority task does not
21566 execute while the higher priority task is waiting. The HP
21567 Ada Run-Time Library keeps a task running until either the
21568 task is suspended or a higher priority task becomes ready.
21570 On OpenVMS Alpha systems, the default strategy is round-
21571 robin with preemption. Tasks of equal priority take turns
21572 at the processor. A task is run for a certain period of
21573 time and then placed at the tail of the ready queue for
21574 its priority level.
21576 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21577 which can be used to enable or disable round-robin
21578 scheduling of tasks with the same priority.
21579 See the relevant HP Ada run-time reference manual for
21580 information on using the pragmas to control HP Ada task
21581 scheduling.
21583 GNAT follows the scheduling rules of Annex D (Real-Time
21584 Annex) of the @cite{Ada Reference Manual}. In general, this
21585 scheduling strategy is fully compatible with HP Ada
21586 although it provides some additional constraints (as
21587 fully documented in Annex D).
21588 GNAT implements time slicing control in a manner compatible with
21589 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21590 are identical to the HP Ada 83 pragma of the same name.
21591 Note that it is not possible to mix GNAT tasking and
21592 HP Ada 83 tasking in the same program, since the two run-time
21593 libraries are not compatible.
21595 @node The Task Stack
21596 @subsection The Task Stack
21598 @noindent
21599 In HP Ada, a task stack is allocated each time a
21600 non-passive task is activated. As soon as the task is
21601 terminated, the storage for the task stack is deallocated.
21602 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21603 a default stack size is used. Also, regardless of the size
21604 specified, some additional space is allocated for task
21605 management purposes. On OpenVMS Alpha systems, at least
21606 one page is allocated.
21608 GNAT handles task stacks in a similar manner. In accordance with
21609 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
21610 an alternative method for controlling the task stack size.
21611 The specification of the attribute @code{T'STORAGE_SIZE} is also
21612 supported in a manner compatible with HP Ada.
21614 @node External Interrupts
21615 @subsection External Interrupts
21617 @noindent
21618 On HP Ada, external interrupts can be associated with task entries.
21619 GNAT is compatible with HP Ada in its handling of external interrupts.
21621 @node Pragmas and Pragma-Related Features
21622 @section Pragmas and Pragma-Related Features
21624 @noindent
21625 Both HP Ada and GNAT supply all language-defined pragmas
21626 as specified by the Ada 83 standard. GNAT also supplies all
21627 language-defined pragmas introduced by Ada 95 and Ada 2005.
21628 In addition, GNAT implements the implementation-defined pragmas
21629 from HP Ada 83.
21631 @itemize @bullet
21632 @item  @code{AST_ENTRY}
21634 @item  @code{COMMON_OBJECT}
21636 @item  @code{COMPONENT_ALIGNMENT}
21638 @item  @code{EXPORT_EXCEPTION}
21640 @item  @code{EXPORT_FUNCTION}
21642 @item  @code{EXPORT_OBJECT}
21644 @item  @code{EXPORT_PROCEDURE}
21646 @item  @code{EXPORT_VALUED_PROCEDURE}
21648 @item  @code{FLOAT_REPRESENTATION}
21650 @item  @code{IDENT}
21652 @item  @code{IMPORT_EXCEPTION}
21654 @item  @code{IMPORT_FUNCTION}
21656 @item  @code{IMPORT_OBJECT}
21658 @item  @code{IMPORT_PROCEDURE}
21660 @item  @code{IMPORT_VALUED_PROCEDURE}
21662 @item  @code{INLINE_GENERIC}
21664 @item  @code{INTERFACE_NAME}
21666 @item  @code{LONG_FLOAT}
21668 @item  @code{MAIN_STORAGE}
21670 @item  @code{PASSIVE}
21672 @item  @code{PSECT_OBJECT}
21674 @item  @code{SHARE_GENERIC}
21676 @item  @code{SUPPRESS_ALL}
21678 @item  @code{TASK_STORAGE}
21680 @item  @code{TIME_SLICE}
21682 @item  @code{TITLE}
21683 @end itemize
21685 @noindent
21686 These pragmas are all fully implemented, with the exception of @code{TITLE},
21687 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21688 recognized, but which have no
21689 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21690 use of Ada protected objects. In GNAT, all generics are inlined.
21692 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21693 a separate subprogram specification which must appear before the
21694 subprogram body.
21696 GNAT also supplies a number of implementation-defined pragmas including the
21697 following:
21699 @itemize @bullet
21700 @item  @code{ABORT_DEFER}
21702 @item  @code{ADA_83}
21704 @item  @code{ADA_95}
21706 @item  @code{ADA_05}
21708 @item  @code{Ada_2005}
21710 @item  @code{Ada_12}
21712 @item  @code{Ada_2012}
21714 @item  @code{ANNOTATE}
21716 @item  @code{ASSERT}
21718 @item  @code{C_PASS_BY_COPY}
21720 @item  @code{CPP_CLASS}
21722 @item  @code{CPP_CONSTRUCTOR}
21724 @item  @code{CPP_DESTRUCTOR}
21726 @item  @code{DEBUG}
21728 @item  @code{EXTEND_SYSTEM}
21730 @item  @code{LINKER_ALIAS}
21732 @item  @code{LINKER_SECTION}
21734 @item  @code{MACHINE_ATTRIBUTE}
21736 @item  @code{NO_RETURN}
21738 @item  @code{PURE_FUNCTION}
21740 @item  @code{SOURCE_FILE_NAME}
21742 @item  @code{SOURCE_REFERENCE}
21744 @item  @code{TASK_INFO}
21746 @item  @code{UNCHECKED_UNION}
21748 @item  @code{UNIMPLEMENTED_UNIT}
21750 @item  @code{UNIVERSAL_DATA}
21752 @item  @code{UNSUPPRESS}
21754 @item  @code{WARNINGS}
21756 @item  @code{WEAK_EXTERNAL}
21757 @end itemize
21759 @noindent
21760 For full details on these and other GNAT implementation-defined pragmas,
21761 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21762 Manual}.
21764 @menu
21765 * Restrictions on the Pragma INLINE::
21766 * Restrictions on the Pragma INTERFACE::
21767 * Restrictions on the Pragma SYSTEM_NAME::
21768 @end menu
21770 @node Restrictions on the Pragma INLINE
21771 @subsection Restrictions on Pragma @code{INLINE}
21773 @noindent
21774 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21775 @itemize @bullet
21776 @item  Parameters cannot have a task type.
21778 @item  Function results cannot be task types, unconstrained
21779 array types, or unconstrained types with discriminants.
21781 @item  Bodies cannot declare the following:
21782 @itemize @bullet
21783 @item  Subprogram body or stub (imported subprogram is allowed)
21785 @item  Tasks
21787 @item  Generic declarations
21789 @item  Instantiations
21791 @item  Exceptions
21793 @item  Access types (types derived from access types allowed)
21795 @item  Array or record types
21797 @item  Dependent tasks
21799 @item  Direct recursive calls of subprogram or containing
21800 subprogram, directly or via a renaming
21802 @end itemize
21803 @end itemize
21805 @noindent
21806 In GNAT, the only restriction on pragma @code{INLINE} is that the
21807 body must occur before the call if both are in the same
21808 unit, and the size must be appropriately small. There are
21809 no other specific restrictions which cause subprograms to
21810 be incapable of being inlined.
21812 @node  Restrictions on the Pragma INTERFACE
21813 @subsection  Restrictions on Pragma @code{INTERFACE}
21815 @noindent
21816 The following restrictions on pragma @code{INTERFACE}
21817 are enforced by both HP Ada and GNAT:
21818 @itemize @bullet
21819 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21820 Default is the default on OpenVMS Alpha systems.
21822 @item  Parameter passing: Language specifies default
21823 mechanisms but can be overridden with an @code{EXPORT} pragma.
21825 @itemize @bullet
21826 @item  Ada: Use internal Ada rules.
21828 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21829 record or task type. Result cannot be a string, an
21830 array, or a record.
21832 @item  Fortran: Parameters cannot have a task type. Result cannot
21833 be a string, an array, or a record.
21834 @end itemize
21835 @end itemize
21837 @noindent
21838 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21839 record parameters for all languages.
21841 @node  Restrictions on the Pragma SYSTEM_NAME
21842 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21844 @noindent
21845 For HP Ada for OpenVMS Alpha, the enumeration literal
21846 for the type @code{NAME} is @code{OPENVMS_AXP}.
21847 In GNAT, the enumeration
21848 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21850 @node  Library of Predefined Units
21851 @section  Library of Predefined Units
21853 @noindent
21854 A library of predefined units is provided as part of the
21855 HP Ada and GNAT implementations. HP Ada does not provide
21856 the package @code{MACHINE_CODE} but instead recommends importing
21857 assembler code.
21859 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21860 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21861 version.
21862 The HP Ada Predefined Library units are modified to remove post-Ada 83
21863 incompatibilities and to make them interoperable with GNAT
21864 (@pxref{Changes to DECLIB}, for details).
21865 The units are located in the @file{DECLIB} directory.
21867 The GNAT RTL is contained in
21868 the @file{ADALIB} directory, and
21869 the default search path is set up to find @code{DECLIB} units in preference
21870 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21871 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21873 @menu
21874 * Changes to DECLIB::
21875 @end menu
21877 @node Changes to DECLIB
21878 @subsection Changes to @code{DECLIB}
21880 @noindent
21881 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21882 compatibility are minor and include the following:
21884 @itemize @bullet
21885 @item  Adjusting the location of pragmas and record representation
21886 clauses to obey Ada 95 (and thus Ada 2005) rules
21888 @item  Adding the proper notation to generic formal parameters
21889 that take unconstrained types in instantiation
21891 @item  Adding pragma @code{ELABORATE_BODY} to package specs
21892 that have package bodies not otherwise allowed
21894 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21895 ``@code{PROTECTD}''.
21896 Currently these are found only in the @code{STARLET} package spec.
21898 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21899 where the address size is constrained to 32 bits.
21900 @end itemize
21902 @noindent
21903 None of the above changes is visible to users.
21905 @node Bindings
21906 @section Bindings
21908 @noindent
21909 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21910 @itemize @bullet
21912 @item  Command Language Interpreter (CLI interface)
21914 @item  DECtalk Run-Time Library (DTK interface)
21916 @item  Librarian utility routines (LBR interface)
21918 @item  General Purpose Run-Time Library (LIB interface)
21920 @item  Math Run-Time Library (MTH interface)
21922 @item  National Character Set Run-Time Library (NCS interface)
21924 @item  Compiled Code Support Run-Time Library (OTS interface)
21926 @item  Parallel Processing Run-Time Library (PPL interface)
21928 @item  Screen Management Run-Time Library (SMG interface)
21930 @item  Sort Run-Time Library (SOR interface)
21932 @item  String Run-Time Library (STR interface)
21934 @item STARLET System Library
21935 @findex Starlet
21937 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21939 @item  X Windows Toolkit (XT interface)
21941 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21942 @end itemize
21944 @noindent
21945 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21946 directory, on both the Alpha and I64 OpenVMS platforms.
21948 The X components of DECLIB compatibility package are located in a separate
21949 library, called XDECGNAT, which is not linked with by default; this library
21950 must be explicitly linked with any application that makes use of any X facilities,
21951 with a command similar to
21953 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21955 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21956 in the
21957 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21958 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21959 @code{Xt}, and @code{X_Lib}
21960 causing the default X/Motif sharable image libraries to be linked in. This
21961 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21962 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21964 It may be necessary to edit these options files to update or correct the
21965 library names if, for example, the newer X/Motif bindings from
21966 @file{ADA$EXAMPLES}
21967 had been (previous to installing GNAT) copied and renamed to supersede the
21968 default @file{ADA$PREDEFINED} versions.
21970 @menu
21971 * Shared Libraries and Options Files::
21972 * Interfaces to C::
21973 @end menu
21975 @node Shared Libraries and Options Files
21976 @subsection Shared Libraries and Options Files
21978 @noindent
21979 When using the HP Ada
21980 predefined X and Motif bindings, the linking with their sharable images is
21981 done automatically by @command{GNAT LINK}.
21982 When using other X and Motif bindings, you need
21983 to add the corresponding sharable images to the command line for
21984 @code{GNAT LINK}. When linking with shared libraries, or with
21985 @file{.OPT} files, you must
21986 also add them to the command line for @command{GNAT LINK}.
21988 A shared library to be used with GNAT is built in the same way as other
21989 libraries under VMS. The VMS Link command can be used in standard fashion.
21991 @node Interfaces to C
21992 @subsection Interfaces to C
21994 @noindent
21995 HP Ada
21996 provides the following Ada types and operations:
21998 @itemize @bullet
21999 @item C types package (@code{C_TYPES})
22001 @item C strings (@code{C_TYPES.NULL_TERMINATED})
22003 @item Other_types (@code{SHORT_INT})
22004 @end itemize
22006 @noindent
22007 Interfacing to C with GNAT, you can use the above approach
22008 described for HP Ada or the facilities of Annex B of
22009 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
22010 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22011 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
22013 The @option{-gnatF} qualifier forces default and explicit
22014 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22015 to be uppercased for compatibility with the default behavior
22016 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22018 @node Main Program Definition
22019 @section Main Program Definition
22021 @noindent
22022 The following section discusses differences in the
22023 definition of main programs on HP Ada and GNAT.
22024 On HP Ada, main programs are defined to meet the
22025 following conditions:
22026 @itemize @bullet
22027 @item  Procedure with no formal parameters (returns @code{0} upon
22028 normal completion)
22030 @item  Procedure with no formal parameters (returns @code{42} when
22031 an unhandled exception is raised)
22033 @item  Function with no formal parameters whose returned value
22034 is of a discrete type
22036 @item  Procedure with one @code{out} formal of a discrete type for
22037 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
22039 @end itemize
22041 @noindent
22042 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22043 a main function or main procedure returns a discrete
22044 value whose size is less than 64 bits (32 on VAX systems),
22045 the value is zero- or sign-extended as appropriate.
22046 On GNAT, main programs are defined as follows:
22047 @itemize @bullet
22048 @item  Must be a non-generic, parameterless subprogram that
22049 is either a procedure or function returning an Ada
22050 @code{STANDARD.INTEGER} (the predefined type)
22052 @item  Cannot be a generic subprogram or an instantiation of a
22053 generic subprogram
22054 @end itemize
22056 @node Implementation-Defined Attributes
22057 @section Implementation-Defined Attributes
22059 @noindent
22060 GNAT provides all HP Ada implementation-defined
22061 attributes.
22063 @node Compiler and Run-Time Interfacing
22064 @section Compiler and Run-Time Interfacing
22066 @noindent
22067 HP Ada provides the following qualifiers to pass options to the linker
22068 (ACS LINK):
22069 @itemize @bullet
22070 @item  @option{/WAIT} and @option{/SUBMIT}
22072 @item  @option{/COMMAND}
22074 @item  @option{/@r{[}NO@r{]}MAP}
22076 @item  @option{/OUTPUT=@var{file-spec}}
22078 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22079 @end itemize
22081 @noindent
22082 To pass options to the linker, GNAT provides the following
22083 switches:
22085 @itemize @bullet
22086 @item   @option{/EXECUTABLE=@var{exec-name}}
22088 @item   @option{/VERBOSE}
22090 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22091 @end itemize
22093 @noindent
22094 For more information on these switches, see
22095 @ref{Switches for gnatlink}.
22096 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
22097 to control optimization. HP Ada also supplies the
22098 following pragmas:
22099 @itemize @bullet
22100 @item  @code{OPTIMIZE}
22102 @item  @code{INLINE}
22104 @item  @code{INLINE_GENERIC}
22106 @item  @code{SUPPRESS_ALL}
22108 @item  @code{PASSIVE}
22109 @end itemize
22111 @noindent
22112 In GNAT, optimization is controlled strictly by command
22113 line parameters, as described in the corresponding section of this guide.
22114 The HP pragmas for control of optimization are
22115 recognized but ignored.
22117 Note that in GNAT, the default is optimization off, whereas in HP Ada
22118 the default is that optimization is turned on.
22120 @node Program Compilation and Library Management
22121 @section Program Compilation and Library Management
22123 @noindent
22124 HP Ada and GNAT provide a comparable set of commands to
22125 build programs. HP Ada also provides a program library,
22126 which is a concept that does not exist on GNAT. Instead,
22127 GNAT provides directories of sources that are compiled as
22128 needed.
22130 The following table summarizes
22131 the HP Ada commands and provides
22132 equivalent GNAT commands. In this table, some GNAT
22133 equivalents reflect the fact that GNAT does not use the
22134 concept of a program library. Instead, it uses a model
22135 in which collections of source and object files are used
22136 in a manner consistent with other languages like C and
22137 Fortran. Therefore, standard system file commands are used
22138 to manipulate these elements. Those GNAT commands are marked with
22139 an asterisk.
22140 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
22142 @need 1500
22143 @multitable @columnfractions .35 .65
22145 @item @emph{HP Ada Command}
22146 @tab @emph{GNAT Equivalent / Description}
22148 @item @command{ADA}
22149 @tab @command{GNAT COMPILE}@*
22150 Invokes the compiler to compile one or more Ada source files.
22152 @item @command{ACS ATTACH}@*
22153 @tab [No equivalent]@*
22154 Switches control of terminal from current process running the program
22155 library manager.
22157 @item @command{ACS CHECK}
22158 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
22159 Forms the execution closure of one
22160 or more compiled units and checks completeness and currency.
22162 @item @command{ACS COMPILE}
22163 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22164 Forms the execution closure of one or
22165 more specified units, checks completeness and currency,
22166 identifies units that have revised source files, compiles same,
22167 and recompiles units that are or will become obsolete.
22168 Also completes incomplete generic instantiations.
22170 @item @command{ACS COPY FOREIGN}
22171 @tab Copy (*)@*
22172 Copies a foreign object file into the program library as a
22173 library unit body.
22175 @item @command{ACS COPY UNIT}
22176 @tab Copy (*)@*
22177 Copies a compiled unit from one program library to another.
22179 @item @command{ACS CREATE LIBRARY}
22180 @tab Create /directory (*)@*
22181 Creates a program library.
22183 @item @command{ACS CREATE SUBLIBRARY}
22184 @tab Create /directory (*)@*
22185 Creates a program sublibrary.
22187 @item @command{ACS DELETE LIBRARY}
22188 @tab @*
22189 Deletes a program library and its contents.
22191 @item @command{ACS DELETE SUBLIBRARY}
22192 @tab @*
22193 Deletes a program sublibrary and its contents.
22195 @item @command{ACS DELETE UNIT}
22196 @tab Delete file (*)@*
22197 On OpenVMS systems, deletes one or more compiled units from
22198 the current program library.
22200 @item @command{ACS DIRECTORY}
22201 @tab Directory (*)@*
22202 On OpenVMS systems, lists units contained in the current
22203 program library.
22205 @item @command{ACS ENTER FOREIGN}
22206 @tab Copy (*)@*
22207 Allows the import of a foreign body as an Ada library
22208 spec and enters a reference to a pointer.
22210 @item @command{ACS ENTER UNIT}
22211 @tab Copy (*)@*
22212 Enters a reference (pointer) from the current program library to
22213 a unit compiled into another program library.
22215 @item @command{ACS EXIT}
22216 @tab [No equivalent]@*
22217 Exits from the program library manager.
22219 @item @command{ACS EXPORT}
22220 @tab Copy (*)@*
22221 Creates an object file that contains system-specific object code
22222 for one or more units. With GNAT, object files can simply be copied
22223 into the desired directory.
22225 @item @command{ACS EXTRACT SOURCE}
22226 @tab Copy (*)@*
22227 Allows access to the copied source file for each Ada compilation unit
22229 @item @command{ACS HELP}
22230 @tab @command{HELP GNAT}@*
22231 Provides online help.
22233 @item @command{ACS LINK}
22234 @tab @command{GNAT LINK}@*
22235 Links an object file containing Ada units into an executable file.
22237 @item @command{ACS LOAD}
22238 @tab Copy (*)@*
22239 Loads (partially compiles) Ada units into the program library.
22240 Allows loading a program from a collection of files into a library
22241 without knowing the relationship among units.
22243 @item @command{ACS MERGE}
22244 @tab Copy (*)@*
22245 Merges into the current program library, one or more units from
22246 another library where they were modified.
22248 @item @command{ACS RECOMPILE}
22249 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22250 Recompiles from   external or copied source files any obsolete
22251 unit in the closure. Also, completes any incomplete generic
22252 instantiations.
22254 @item @command{ACS REENTER}
22255 @tab @command{GNAT MAKE}@*
22256 Reenters current references to units compiled after last entered
22257 with the @command{ACS ENTER UNIT} command.
22259 @item @command{ACS SET LIBRARY}
22260 @tab Set default (*)@*
22261 Defines a program library to be the compilation context as well
22262 as the target library for compiler output and commands in general.
22264 @item @command{ACS SET PRAGMA}
22265 @tab Edit @file{gnat.adc} (*)@*
22266 Redefines specified  values of the library characteristics
22267 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
22268 and @code{Float_Representation}.
22270 @item @command{ACS SET SOURCE}
22271 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
22272 Defines the source file search list for the @command{ACS COMPILE} command.
22274 @item @command{ACS SHOW LIBRARY}
22275 @tab Directory (*)@*
22276 Lists information about one or more program libraries.
22278 @item @command{ACS SHOW PROGRAM}
22279 @tab [No equivalent]@*
22280 Lists information about the execution closure of one or
22281 more units in the program library.
22283 @item @command{ACS SHOW SOURCE}
22284 @tab Show logical @code{ADA_INCLUDE_PATH}@*
22285 Shows the source file search used when compiling units.
22287 @item @command{ACS SHOW VERSION}
22288 @tab Compile with @option{VERBOSE} option
22289 Displays the version number of the compiler and program library
22290 manager used.
22292 @item @command{ACS SPAWN}
22293 @tab [No equivalent]@*
22294 Creates a subprocess of the current process (same as @command{DCL SPAWN}
22295 command).
22297 @item @command{ACS VERIFY}
22298 @tab [No equivalent]@*
22299 Performs a series of consistency checks on a program library to
22300 determine whether the library structure and library files are in
22301 valid form.
22302 @end multitable
22304 @noindent
22306 @node Input-Output
22307 @section Input-Output
22309 @noindent
22310 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22311 Management Services (RMS) to perform operations on
22312 external files.
22314 @noindent
22315 HP Ada and GNAT predefine an identical set of input-
22316 output packages. To make the use of the
22317 generic @code{TEXT_IO} operations more convenient, HP Ada
22318 provides predefined library packages that instantiate the
22319 integer and floating-point operations for the predefined
22320 integer and floating-point types as shown in the following table.
22322 @multitable @columnfractions .45 .55
22323 @item @emph{Package Name} @tab Instantiation
22325 @item @code{INTEGER_TEXT_IO}
22326 @tab @code{INTEGER_IO(INTEGER)}
22328 @item @code{SHORT_INTEGER_TEXT_IO}
22329 @tab @code{INTEGER_IO(SHORT_INTEGER)}
22331 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
22332 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
22334 @item @code{FLOAT_TEXT_IO}
22335 @tab @code{FLOAT_IO(FLOAT)}
22337 @item @code{LONG_FLOAT_TEXT_IO}
22338 @tab @code{FLOAT_IO(LONG_FLOAT)}
22339 @end multitable
22341 @noindent
22342 The HP Ada predefined packages and their operations
22343 are implemented using OpenVMS Alpha files and input-output
22344 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
22345 Familiarity with the following is recommended:
22346 @itemize @bullet
22347 @item  RMS file organizations and access methods
22349 @item  OpenVMS file specifications and directories
22351 @item  OpenVMS File Definition Language (FDL)
22352 @end itemize
22354 @noindent
22355 GNAT provides I/O facilities that are completely
22356 compatible with HP Ada. The distribution includes the
22357 standard HP Ada versions of all I/O packages, operating
22358 in a manner compatible with HP Ada. In particular, the
22359 following packages are by default the HP Ada (Ada 83)
22360 versions of these packages rather than the renamings
22361 suggested in Annex J of the Ada Reference Manual:
22362 @itemize @bullet
22363 @item  @code{TEXT_IO}
22365 @item  @code{SEQUENTIAL_IO}
22367 @item  @code{DIRECT_IO}
22368 @end itemize
22370 @noindent
22371 The use of the standard child package syntax (for
22372 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
22373 packages.
22374 GNAT provides HP-compatible predefined instantiations
22375 of the @code{TEXT_IO} packages, and also
22376 provides the standard predefined instantiations required
22377 by the @cite{Ada Reference Manual}.
22379 For further information on how GNAT interfaces to the file
22380 system or how I/O is implemented in programs written in
22381 mixed languages, see @ref{Implementation of the Standard I/O,,,
22382 gnat_rm, GNAT Reference Manual}.
22383 This chapter covers the following:
22384 @itemize @bullet
22385 @item  Standard I/O packages
22387 @item  @code{FORM} strings
22389 @item  @code{ADA.DIRECT_IO}
22391 @item  @code{ADA.SEQUENTIAL_IO}
22393 @item  @code{ADA.TEXT_IO}
22395 @item  Stream pointer positioning
22397 @item  Reading and writing non-regular files
22399 @item  @code{GET_IMMEDIATE}
22401 @item  Treating @code{TEXT_IO} files as streams
22403 @item  Shared files
22405 @item  Open modes
22406 @end itemize
22408 @node Implementation Limits
22409 @section Implementation Limits
22411 @noindent
22412 The following table lists implementation limits for HP Ada
22413 and GNAT systems.
22414 @multitable @columnfractions .60 .20 .20
22415 @sp 1
22416 @item  @emph{Compilation Parameter}
22417 @tab   @emph{HP Ada}
22418 @tab   @emph{GNAT}
22419 @sp 1
22421 @item  In a subprogram or entry  declaration, maximum number of
22422 formal parameters that are of an unconstrained record type
22423 @tab   32
22424 @tab   No set limit
22425 @sp 1
22427 @item  Maximum identifier length (number of characters)
22428 @tab   255
22429 @tab   32766
22430 @sp 1
22432 @item  Maximum number of characters in a source line
22433 @tab   255
22434 @tab   32766
22435 @sp 1
22437 @item  Maximum collection size   (number of bytes)
22438 @tab   2**31-1
22439 @tab   2**31-1
22440 @sp 1
22442 @item  Maximum number of discriminants for a record type
22443 @tab   245
22444 @tab   No set limit
22445 @sp 1
22447 @item  Maximum number of formal parameters in an entry or
22448 subprogram declaration
22449 @tab   246
22450 @tab    No set limit
22451 @sp 1
22453 @item  Maximum number of dimensions in an array type
22454 @tab   255
22455 @tab   No set limit
22456 @sp 1
22458 @item  Maximum number of library  units and subunits in a compilation.
22459 @tab   4095
22460 @tab   No set limit
22461 @sp 1
22463 @item  Maximum number of library units and subunits in an execution.
22464 @tab   16383
22465 @tab   No set limit
22466 @sp 1
22468 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22469 or @code{PSECT_OBJECT}
22470 @tab   32757
22471 @tab   No set limit
22472 @sp 1
22474 @item  Maximum number of enumeration literals in an enumeration type
22475 definition
22476 @tab   65535
22477 @tab   No set limit
22478 @sp 1
22480 @item  Maximum number of lines in a source file
22481 @tab   65534
22482 @tab   No set limit
22483 @sp 1
22485 @item  Maximum number of bits in any object
22486 @tab   2**31-1
22487 @tab   2**31-1
22488 @sp 1
22490 @item  Maximum size of the static portion of a stack frame (approximate)
22491 @tab   2**31-1
22492 @tab   2**31-1
22493 @end multitable
22495 @node Tools and Utilities
22496 @section Tools and Utilities
22498 @noindent
22499 The following table lists some of the OpenVMS development tools
22500 available for HP Ada, and the corresponding tools for
22501 use with @value{EDITION} on Alpha and I64 platforms.
22502 Aside from the debugger, all the OpenVMS tools identified are part
22503 of the DECset package.
22505 @iftex
22506 @c Specify table in TeX since Texinfo does a poor job
22507 @tex
22508 \smallskip
22509 \smallskip
22510 \settabs\+Language-Sensitive Editor\quad
22511    &Product with HP Ada\quad
22512    &\cr
22513 \+\it Tool
22514    &\it Product with HP Ada
22515    & \it Product with @value{EDITION}\cr
22516 \smallskip
22517 \+Code Management System
22518    &HP CMS
22519    & HP CMS\cr
22520 \smallskip
22521 \+Language-Sensitive Editor
22522    &HP LSE
22523    & emacs or HP LSE (Alpha)\cr
22525    &
22526    & HP LSE (I64)\cr
22527 \smallskip
22528 \+Debugger
22529    &OpenVMS Debug
22530    & gdb (Alpha),\cr
22532    &
22533    & OpenVMS Debug (I64)\cr
22534 \smallskip
22535 \+Source Code Analyzer /
22536    &HP SCA
22537    & GNAT XREF\cr
22538 \+Cross Referencer
22539    &
22540    &\cr
22541 \smallskip
22542 \+Test Manager
22543    &HP Digital Test
22544    & HP DTM\cr
22546    &Manager (DTM)
22547    &\cr
22548 \smallskip
22549 \+Performance and
22550    & HP PCA
22551    & HP PCA\cr
22552 \+Coverage Analyzer
22553    &
22554    &\cr
22555 \smallskip
22556 \+Module Management
22557    & HP MMS
22558    & Not applicable\cr
22559 \+ System
22560    &
22561    &\cr
22562 \smallskip
22563 \smallskip
22564 @end tex
22565 @end iftex
22567 @ifnottex
22568 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
22569 @c the TeX version above for the printed version
22570 @flushleft
22571 @c @multitable @columnfractions .3 .4 .4
22572 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22573 @item @i{Tool}
22574 @tab @i{Tool with HP Ada}
22575 @tab @i{Tool with @value{EDITION}}
22576 @item Code Management@*System
22577 @tab HP CMS
22578 @tab HP CMS
22579 @item Language-Sensitive@*Editor
22580 @tab HP LSE
22581 @tab emacs or HP LSE (Alpha)
22582 @item
22583 @tab
22584 @tab HP LSE (I64)
22585 @item Debugger
22586 @tab OpenVMS Debug
22587 @tab gdb (Alpha),
22588 @item
22589 @tab
22590 @tab OpenVMS Debug (I64)
22591 @item Source Code Analyzer /@*Cross Referencer
22592 @tab HP SCA
22593 @tab GNAT XREF
22594 @item Test Manager
22595 @tab HP Digital Test@*Manager (DTM)
22596 @tab HP DTM
22597 @item Performance and@*Coverage Analyzer
22598 @tab HP PCA
22599 @tab HP PCA
22600 @item Module Management@*System
22601 @tab HP MMS
22602 @tab Not applicable
22603 @end multitable
22604 @end flushleft
22605 @end ifnottex
22607 @end ifset
22609 @c **************************************
22610 @node Platform-Specific Information for the Run-Time Libraries
22611 @appendix Platform-Specific Information for the Run-Time Libraries
22612 @cindex Tasking and threads libraries
22613 @cindex Threads libraries and tasking
22614 @cindex Run-time libraries (platform-specific information)
22616 @noindent
22617 The GNAT run-time implementation may vary with respect to both the
22618 underlying threads library and the exception handling scheme.
22619 For threads support, one or more of the following are supplied:
22620 @itemize @bullet
22621 @item @b{native threads library}, a binding to the thread package from
22622 the underlying operating system
22624 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22625 POSIX thread package
22626 @end itemize
22628 @noindent
22629 For exception handling, either or both of two models are supplied:
22630 @itemize @bullet
22631 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22632 Most programs should experience a substantial speed improvement by
22633 being compiled with a ZCX run-time.
22634 This is especially true for
22635 tasking applications or applications with many exception handlers.}
22636 @cindex Zero-Cost Exceptions
22637 @cindex ZCX (Zero-Cost Exceptions)
22638 which uses binder-generated tables that
22639 are interrogated at run time to locate a handler
22641 @item @b{setjmp / longjmp} (``SJLJ''),
22642 @cindex setjmp/longjmp Exception Model
22643 @cindex SJLJ (setjmp/longjmp Exception Model)
22644 which uses dynamically-set data to establish
22645 the set of handlers
22646 @end itemize
22648 @noindent
22649 This appendix summarizes which combinations of threads and exception support
22650 are supplied on various GNAT platforms.
22651 It then shows how to select a particular library either
22652 permanently or temporarily,
22653 explains the properties of (and tradeoffs among) the various threads
22654 libraries, and provides some additional
22655 information about several specific platforms.
22657 @menu
22658 * Summary of Run-Time Configurations::
22659 * Specifying a Run-Time Library::
22660 * Choosing the Scheduling Policy::
22661 * Solaris-Specific Considerations::
22662 * Linux-Specific Considerations::
22663 * AIX-Specific Considerations::
22664 * RTX-Specific Considerations::
22665 * HP-UX-Specific Considerations::
22666 @end menu
22668 @node Summary of Run-Time Configurations
22669 @section Summary of Run-Time Configurations
22671 @multitable @columnfractions .30 .70
22672 @item @b{alpha-openvms}
22673 @item @code{@ @ }@i{rts-native (default)}
22674 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22675 @item @code{@ @ @ @ }Exceptions @tab ZCX
22677 @item @code{@ @ }@i{rts-sjlj}
22678 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22679 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22681 @item @b{ia64-hp_linux}
22682 @item @code{@ @ }@i{rts-native (default)}
22683 @item @code{@ @ @ @ }Tasking    @tab pthread library
22684 @item @code{@ @ @ @ }Exceptions @tab ZCX
22686 @item @b{ia64-hpux}
22687 @item @code{@ @ }@i{rts-native (default)}
22688 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22689 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22691 @item @b{ia64-openvms}
22692 @item @code{@ @ }@i{rts-native (default)}
22693 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22694 @item @code{@ @ @ @ }Exceptions @tab ZCX
22696 @item @b{ia64-sgi_linux}
22697 @item @code{@ @ }@i{rts-native (default)}
22698 @item @code{@ @ @ @ }Tasking    @tab pthread library
22699 @item @code{@ @ @ @ }Exceptions @tab ZCX
22701 @item @b{pa-hpux}
22702 @item @code{@ @ }@i{rts-native (default)}
22703 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22704 @item @code{@ @ @ @ }Exceptions @tab ZCX
22706 @item @code{@ @ }@i{rts-sjlj}
22707 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22708 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22710 @item @b{ppc-aix}
22711 @item @code{@ @ }@i{rts-native (default)}
22712 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22713 @item @code{@ @ @ @ }Exceptions @tab ZCX
22715 @item @code{@ @ }@i{rts-sjlj}
22716 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22717 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22719 @item @b{ppc-darwin}
22720 @item @code{@ @ }@i{rts-native (default)}
22721 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22722 @item @code{@ @ @ @ }Exceptions @tab ZCX
22724 @item @b{sparc-solaris}  @tab
22725 @item @code{@ @ }@i{rts-native (default)}
22726 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22727 @item @code{@ @ @ @ }Exceptions @tab ZCX
22729 @item @code{@ @ }@i{rts-pthread}
22730 @item @code{@ @ @ @ }Tasking    @tab pthread library
22731 @item @code{@ @ @ @ }Exceptions @tab ZCX
22733 @item @code{@ @ }@i{rts-sjlj}
22734 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22735 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22737 @item @b{sparc64-solaris}  @tab
22738 @item @code{@ @ }@i{rts-native (default)}
22739 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22740 @item @code{@ @ @ @ }Exceptions @tab ZCX
22742 @item @b{x86-linux}
22743 @item @code{@ @ }@i{rts-native (default)}
22744 @item @code{@ @ @ @ }Tasking    @tab pthread library
22745 @item @code{@ @ @ @ }Exceptions @tab ZCX
22747 @item @code{@ @ }@i{rts-sjlj}
22748 @item @code{@ @ @ @ }Tasking    @tab pthread library
22749 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22751 @item @b{x86-lynx}
22752 @item @code{@ @ }@i{rts-native (default)}
22753 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22754 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22756 @item @b{x86-solaris}
22757 @item @code{@ @ }@i{rts-native (default)}
22758 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22759 @item @code{@ @ @ @ }Exceptions @tab ZCX
22761 @item @code{@ @ }@i{rts-sjlj}
22762 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22763 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22765 @item @b{x86-windows}
22766 @item @code{@ @ }@i{rts-native (default)}
22767 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22768 @item @code{@ @ @ @ }Exceptions @tab ZCX
22770 @item @code{@ @ }@i{rts-sjlj}
22771 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22772 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22774 @item @b{x86-windows-rtx}
22775 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22776 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22777 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22779 @item @code{@ @ }@i{rts-rtx-w32}
22780 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22781 @item @code{@ @ @ @ }Exceptions @tab ZCX
22783 @item @b{x86_64-linux}
22784 @item @code{@ @ }@i{rts-native (default)}
22785 @item @code{@ @ @ @ }Tasking    @tab pthread library
22786 @item @code{@ @ @ @ }Exceptions @tab ZCX
22788 @item @code{@ @ }@i{rts-sjlj}
22789 @item @code{@ @ @ @ }Tasking    @tab pthread library
22790 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22792 @end multitable
22794 @node Specifying a Run-Time Library
22795 @section Specifying a Run-Time Library
22797 @noindent
22798 The @file{adainclude} subdirectory containing the sources of the GNAT
22799 run-time library, and the @file{adalib} subdirectory containing the
22800 @file{ALI} files and the static and/or shared GNAT library, are located
22801 in the gcc target-dependent area:
22803 @smallexample
22804 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22805 @end smallexample
22807 @noindent
22808 As indicated above, on some platforms several run-time libraries are supplied.
22809 These libraries are installed in the target dependent area and
22810 contain a complete source and binary subdirectory. The detailed description
22811 below explains the differences between the different libraries in terms of
22812 their thread support.
22814 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22815 This default run time is selected by the means of soft links.
22816 For example on x86-linux:
22818 @smallexample
22819 @group
22820  $(target-dir)
22821      |
22822      +--- adainclude----------+
22823      |                        |
22824      +--- adalib-----------+  |
22825      |                     |  |
22826      +--- rts-native       |  |
22827      |    |                |  |
22828      |    +--- adainclude <---+
22829      |    |                |
22830      |    +--- adalib <----+
22831      |
22832      +--- rts-sjlj
22833           |
22834           +--- adainclude
22835           |
22836           +--- adalib
22837 @end group
22838 @end smallexample
22840 @noindent
22841 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22842 these soft links can be modified with the following commands:
22844 @smallexample
22845 $ cd $target
22846 $ rm -f adainclude adalib
22847 $ ln -s rts-sjlj/adainclude adainclude
22848 $ ln -s rts-sjlj/adalib adalib
22849 @end smallexample
22851 @noindent
22852 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22853 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22854 @file{$target/ada_object_path}.
22856 Selecting another run-time library temporarily can be
22857 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22858 @cindex @option{--RTS} option
22860 @node Choosing the Scheduling Policy
22861 @section Choosing the Scheduling Policy
22863 @noindent
22864 When using a POSIX threads implementation, you have a choice of several
22865 scheduling policies: @code{SCHED_FIFO},
22866 @cindex @code{SCHED_FIFO} scheduling policy
22867 @code{SCHED_RR}
22868 @cindex @code{SCHED_RR} scheduling policy
22869 and @code{SCHED_OTHER}.
22870 @cindex @code{SCHED_OTHER} scheduling policy
22871 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22872 or @code{SCHED_RR} requires special (e.g., root) privileges.
22874 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22875 @code{SCHED_FIFO},
22876 @cindex @code{SCHED_FIFO} scheduling policy
22877 you can use one of the following:
22879 @itemize @bullet
22880 @item
22881 @code{pragma Time_Slice (0.0)}
22882 @cindex pragma Time_Slice
22883 @item
22884 the corresponding binder option @option{-T0}
22885 @cindex @option{-T0} option
22886 @item
22887 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22888 @cindex pragma Task_Dispatching_Policy
22889 @end itemize
22891 @noindent
22892 To specify @code{SCHED_RR},
22893 @cindex @code{SCHED_RR} scheduling policy
22894 you should use @code{pragma Time_Slice} with a
22895 value greater than @code{0.0}, or else use the corresponding @option{-T}
22896 binder option.
22898 @node Solaris-Specific Considerations
22899 @section Solaris-Specific Considerations
22900 @cindex Solaris Sparc threads libraries
22902 @noindent
22903 This section addresses some topics related to the various threads libraries
22904 on Sparc Solaris.
22906 @menu
22907 * Solaris Threads Issues::
22908 @end menu
22910 @node Solaris Threads Issues
22911 @subsection Solaris Threads Issues
22913 @noindent
22914 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22915 library based on POSIX threads --- @emph{rts-pthread}.
22916 @cindex rts-pthread threads library
22917 This run-time library has the advantage of being mostly shared across all
22918 POSIX-compliant thread implementations, and it also provides under
22919 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22920 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22921 and @code{PTHREAD_PRIO_PROTECT}
22922 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22923 semantics that can be selected using the predefined pragma
22924 @code{Locking_Policy}
22925 @cindex pragma Locking_Policy (under rts-pthread)
22926 with respectively
22927 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22928 @cindex @code{Inheritance_Locking} (under rts-pthread)
22929 @cindex @code{Ceiling_Locking} (under rts-pthread)
22931 As explained above, the native run-time library is based on the Solaris thread
22932 library (@code{libthread}) and is the default library.
22934 When the Solaris threads library is used (this is the default), programs
22935 compiled with GNAT can automatically take advantage of
22936 and can thus execute on multiple processors.
22937 The user can alternatively specify a processor on which the program should run
22938 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22939 is made by
22940 setting the environment variable @env{GNAT_PROCESSOR}
22941 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22942 to one of the following:
22944 @table @code
22945 @item -2
22946 Use the default configuration (run the program on all
22947 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22948 unset
22950 @item -1
22951 Let the run-time implementation choose one processor and run the program on
22952 that processor
22954 @item 0 .. Last_Proc
22955 Run the program on the specified processor.
22956 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22957 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22958 @end table
22960 @node Linux-Specific Considerations
22961 @section Linux-Specific Considerations
22962 @cindex Linux threads libraries
22964 @noindent
22965 On GNU/Linux without NPTL support (usually system with GNU C Library
22966 older than 2.3), the signal model is not POSIX compliant, which means
22967 that to send a signal to the process, you need to send the signal to all
22968 threads, e.g.@: by using @code{killpg()}.
22970 @node AIX-Specific Considerations
22971 @section AIX-Specific Considerations
22972 @cindex AIX resolver library
22974 @noindent
22975 On AIX, the resolver library initializes some internal structure on
22976 the first call to @code{get*by*} functions, which are used to implement
22977 @code{GNAT.Sockets.Get_Host_By_Name} and
22978 @code{GNAT.Sockets.Get_Host_By_Address}.
22979 If such initialization occurs within an Ada task, and the stack size for
22980 the task is the default size, a stack overflow may occur.
22982 To avoid this overflow, the user should either ensure that the first call
22983 to @code{GNAT.Sockets.Get_Host_By_Name} or
22984 @code{GNAT.Sockets.Get_Host_By_Addrss}
22985 occurs in the environment task, or use @code{pragma Storage_Size} to
22986 specify a sufficiently large size for the stack of the task that contains
22987 this call.
22989 @node RTX-Specific Considerations
22990 @section RTX-Specific Considerations
22991 @cindex RTX libraries
22993 @noindent
22994 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22995 API. Applications can be built to work in two different modes:
22997 @itemize @bullet
22998 @item
22999 Windows executables that run in Ring 3 to utilize memory protection
23000 (@emph{rts-rtx-w32}).
23002 @item
23003 Real-time subsystem (RTSS) executables that run in Ring 0, where
23004 performance can be optimized with RTSS applications taking precedent
23005 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
23006 the Microsoft linker to handle RTSS libraries.
23008 @end itemize
23010 @node HP-UX-Specific Considerations
23011 @section HP-UX-Specific Considerations
23012 @cindex HP-UX Scheduling
23014 @noindent
23015 On HP-UX, appropriate privileges are required to change the scheduling
23016 parameters of a task. The calling process must have appropriate
23017 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
23018 successfully change the scheduling parameters.
23020 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
23021 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
23022 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
23024 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
23025 one of the following:
23027 @itemize @bullet
23028 @item
23029 @code{pragma Time_Slice (0.0)}
23030 @cindex pragma Time_Slice
23031 @item
23032 the corresponding binder option @option{-T0}
23033 @cindex @option{-T0} option
23034 @item
23035 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23036 @cindex pragma Task_Dispatching_Policy
23037 @end itemize
23039 @noindent
23040 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
23041 you should use @code{pragma Time_Slice} with a
23042 value greater than @code{0.0}, or use the corresponding @option{-T}
23043 binder option, or set the @code{pragma Task_Dispatching_Policy
23044 (Round_Robin_Within_Priorities)}.
23046 @c *******************************
23047 @node Example of Binder Output File
23048 @appendix Example of Binder Output File
23050 @noindent
23051 This Appendix displays the source code for @command{gnatbind}'s output
23052 file generated for a simple ``Hello World'' program.
23053 Comments have been added for clarification purposes.
23055 @smallexample @c adanocomment
23056 @iftex
23057 @leftskip=0cm
23058 @end iftex
23059 --  The package is called Ada_Main unless this name is actually used
23060 --  as a unit name in the partition, in which case some other unique
23061 --  name is used.
23063 with System;
23064 package ada_main is
23066    Elab_Final_Code : Integer;
23067    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
23069    --  The main program saves the parameters (argument count,
23070    --  argument values, environment pointer) in global variables
23071    --  for later access by other units including
23072    --  Ada.Command_Line.
23074    gnat_argc : Integer;
23075    gnat_argv : System.Address;
23076    gnat_envp : System.Address;
23078    --  The actual variables are stored in a library routine. This
23079    --  is useful for some shared library situations, where there
23080    --  are problems if variables are not in the library.
23082    pragma Import (C, gnat_argc);
23083    pragma Import (C, gnat_argv);
23084    pragma Import (C, gnat_envp);
23086    --  The exit status is similarly an external location
23088    gnat_exit_status : Integer;
23089    pragma Import (C, gnat_exit_status);
23091    GNAT_Version : constant String :=
23092                     "GNAT Version: 6.0.0w (20061115)";
23093    pragma Export (C, GNAT_Version, "__gnat_version");
23095    --  This is the generated adafinal routine that performs
23096    --  finalization at the end of execution. In the case where
23097    --  Ada is the main program, this main program makes a call
23098    --  to adafinal at program termination.
23100    procedure adafinal;
23101    pragma Export (C, adafinal, "adafinal");
23103    --  This is the generated adainit routine that performs
23104    --  initialization at the start of execution. In the case
23105    --  where Ada is the main program, this main program makes
23106    --  a call to adainit at program startup.
23108    procedure adainit;
23109    pragma Export (C, adainit, "adainit");
23111    --  This routine is called at the start of execution. It is
23112    --  a dummy routine that is used by the debugger to breakpoint
23113    --  at the start of execution.
23115    procedure Break_Start;
23116    pragma Import (C, Break_Start, "__gnat_break_start");
23118    --  This is the actual generated main program (it would be
23119    --  suppressed if the no main program switch were used). As
23120    --  required by standard system conventions, this program has
23121    --  the external name main.
23123    function main
23124      (argc : Integer;
23125       argv : System.Address;
23126       envp : System.Address)
23127       return Integer;
23128    pragma Export (C, main, "main");
23130    --  The following set of constants give the version
23131    --  identification values for every unit in the bound
23132    --  partition. This identification is computed from all
23133    --  dependent semantic units, and corresponds to the
23134    --  string that would be returned by use of the
23135    --  Body_Version or Version attributes.
23137    type Version_32 is mod 2 ** 32;
23138    u00001 : constant Version_32 := 16#7880BEB3#;
23139    u00002 : constant Version_32 := 16#0D24CBD0#;
23140    u00003 : constant Version_32 := 16#3283DBEB#;
23141    u00004 : constant Version_32 := 16#2359F9ED#;
23142    u00005 : constant Version_32 := 16#664FB847#;
23143    u00006 : constant Version_32 := 16#68E803DF#;
23144    u00007 : constant Version_32 := 16#5572E604#;
23145    u00008 : constant Version_32 := 16#46B173D8#;
23146    u00009 : constant Version_32 := 16#156A40CF#;
23147    u00010 : constant Version_32 := 16#033DABE0#;
23148    u00011 : constant Version_32 := 16#6AB38FEA#;
23149    u00012 : constant Version_32 := 16#22B6217D#;
23150    u00013 : constant Version_32 := 16#68A22947#;
23151    u00014 : constant Version_32 := 16#18CC4A56#;
23152    u00015 : constant Version_32 := 16#08258E1B#;
23153    u00016 : constant Version_32 := 16#367D5222#;
23154    u00017 : constant Version_32 := 16#20C9ECA4#;
23155    u00018 : constant Version_32 := 16#50D32CB6#;
23156    u00019 : constant Version_32 := 16#39A8BB77#;
23157    u00020 : constant Version_32 := 16#5CF8FA2B#;
23158    u00021 : constant Version_32 := 16#2F1EB794#;
23159    u00022 : constant Version_32 := 16#31AB6444#;
23160    u00023 : constant Version_32 := 16#1574B6E9#;
23161    u00024 : constant Version_32 := 16#5109C189#;
23162    u00025 : constant Version_32 := 16#56D770CD#;
23163    u00026 : constant Version_32 := 16#02F9DE3D#;
23164    u00027 : constant Version_32 := 16#08AB6B2C#;
23165    u00028 : constant Version_32 := 16#3FA37670#;
23166    u00029 : constant Version_32 := 16#476457A0#;
23167    u00030 : constant Version_32 := 16#731E1B6E#;
23168    u00031 : constant Version_32 := 16#23C2E789#;
23169    u00032 : constant Version_32 := 16#0F1BD6A1#;
23170    u00033 : constant Version_32 := 16#7C25DE96#;
23171    u00034 : constant Version_32 := 16#39ADFFA2#;
23172    u00035 : constant Version_32 := 16#571DE3E7#;
23173    u00036 : constant Version_32 := 16#5EB646AB#;
23174    u00037 : constant Version_32 := 16#4249379B#;
23175    u00038 : constant Version_32 := 16#0357E00A#;
23176    u00039 : constant Version_32 := 16#3784FB72#;
23177    u00040 : constant Version_32 := 16#2E723019#;
23178    u00041 : constant Version_32 := 16#623358EA#;
23179    u00042 : constant Version_32 := 16#107F9465#;
23180    u00043 : constant Version_32 := 16#6843F68A#;
23181    u00044 : constant Version_32 := 16#63305874#;
23182    u00045 : constant Version_32 := 16#31E56CE1#;
23183    u00046 : constant Version_32 := 16#02917970#;
23184    u00047 : constant Version_32 := 16#6CCBA70E#;
23185    u00048 : constant Version_32 := 16#41CD4204#;
23186    u00049 : constant Version_32 := 16#572E3F58#;
23187    u00050 : constant Version_32 := 16#20729FF5#;
23188    u00051 : constant Version_32 := 16#1D4F93E8#;
23189    u00052 : constant Version_32 := 16#30B2EC3D#;
23190    u00053 : constant Version_32 := 16#34054F96#;
23191    u00054 : constant Version_32 := 16#5A199860#;
23192    u00055 : constant Version_32 := 16#0E7F912B#;
23193    u00056 : constant Version_32 := 16#5760634A#;
23194    u00057 : constant Version_32 := 16#5D851835#;
23196    --  The following Export pragmas export the version numbers
23197    --  with symbolic names ending in B (for body) or S
23198    --  (for spec) so that they can be located in a link. The
23199    --  information provided here is sufficient to track down
23200    --  the exact versions of units used in a given build.
23202    pragma Export (C, u00001, "helloB");
23203    pragma Export (C, u00002, "system__standard_libraryB");
23204    pragma Export (C, u00003, "system__standard_libraryS");
23205    pragma Export (C, u00004, "adaS");
23206    pragma Export (C, u00005, "ada__text_ioB");
23207    pragma Export (C, u00006, "ada__text_ioS");
23208    pragma Export (C, u00007, "ada__exceptionsB");
23209    pragma Export (C, u00008, "ada__exceptionsS");
23210    pragma Export (C, u00009, "gnatS");
23211    pragma Export (C, u00010, "gnat__heap_sort_aB");
23212    pragma Export (C, u00011, "gnat__heap_sort_aS");
23213    pragma Export (C, u00012, "systemS");
23214    pragma Export (C, u00013, "system__exception_tableB");
23215    pragma Export (C, u00014, "system__exception_tableS");
23216    pragma Export (C, u00015, "gnat__htableB");
23217    pragma Export (C, u00016, "gnat__htableS");
23218    pragma Export (C, u00017, "system__exceptionsS");
23219    pragma Export (C, u00018, "system__machine_state_operationsB");
23220    pragma Export (C, u00019, "system__machine_state_operationsS");
23221    pragma Export (C, u00020, "system__machine_codeS");
23222    pragma Export (C, u00021, "system__storage_elementsB");
23223    pragma Export (C, u00022, "system__storage_elementsS");
23224    pragma Export (C, u00023, "system__secondary_stackB");
23225    pragma Export (C, u00024, "system__secondary_stackS");
23226    pragma Export (C, u00025, "system__parametersB");
23227    pragma Export (C, u00026, "system__parametersS");
23228    pragma Export (C, u00027, "system__soft_linksB");
23229    pragma Export (C, u00028, "system__soft_linksS");
23230    pragma Export (C, u00029, "system__stack_checkingB");
23231    pragma Export (C, u00030, "system__stack_checkingS");
23232    pragma Export (C, u00031, "system__tracebackB");
23233    pragma Export (C, u00032, "system__tracebackS");
23234    pragma Export (C, u00033, "ada__streamsS");
23235    pragma Export (C, u00034, "ada__tagsB");
23236    pragma Export (C, u00035, "ada__tagsS");
23237    pragma Export (C, u00036, "system__string_opsB");
23238    pragma Export (C, u00037, "system__string_opsS");
23239    pragma Export (C, u00038, "interfacesS");
23240    pragma Export (C, u00039, "interfaces__c_streamsB");
23241    pragma Export (C, u00040, "interfaces__c_streamsS");
23242    pragma Export (C, u00041, "system__file_ioB");
23243    pragma Export (C, u00042, "system__file_ioS");
23244    pragma Export (C, u00043, "ada__finalizationB");
23245    pragma Export (C, u00044, "ada__finalizationS");
23246    pragma Export (C, u00045, "system__finalization_rootB");
23247    pragma Export (C, u00046, "system__finalization_rootS");
23248    pragma Export (C, u00047, "system__finalization_implementationB");
23249    pragma Export (C, u00048, "system__finalization_implementationS");
23250    pragma Export (C, u00049, "system__string_ops_concat_3B");
23251    pragma Export (C, u00050, "system__string_ops_concat_3S");
23252    pragma Export (C, u00051, "system__stream_attributesB");
23253    pragma Export (C, u00052, "system__stream_attributesS");
23254    pragma Export (C, u00053, "ada__io_exceptionsS");
23255    pragma Export (C, u00054, "system__unsigned_typesS");
23256    pragma Export (C, u00055, "system__file_control_blockS");
23257    pragma Export (C, u00056, "ada__finalization__list_controllerB");
23258    pragma Export (C, u00057, "ada__finalization__list_controllerS");
23260    -- BEGIN ELABORATION ORDER
23261    -- ada (spec)
23262    -- gnat (spec)
23263    -- gnat.heap_sort_a (spec)
23264    -- gnat.heap_sort_a (body)
23265    -- gnat.htable (spec)
23266    -- gnat.htable (body)
23267    -- interfaces (spec)
23268    -- system (spec)
23269    -- system.machine_code (spec)
23270    -- system.parameters (spec)
23271    -- system.parameters (body)
23272    -- interfaces.c_streams (spec)
23273    -- interfaces.c_streams (body)
23274    -- system.standard_library (spec)
23275    -- ada.exceptions (spec)
23276    -- system.exception_table (spec)
23277    -- system.exception_table (body)
23278    -- ada.io_exceptions (spec)
23279    -- system.exceptions (spec)
23280    -- system.storage_elements (spec)
23281    -- system.storage_elements (body)
23282    -- system.machine_state_operations (spec)
23283    -- system.machine_state_operations (body)
23284    -- system.secondary_stack (spec)
23285    -- system.stack_checking (spec)
23286    -- system.soft_links (spec)
23287    -- system.soft_links (body)
23288    -- system.stack_checking (body)
23289    -- system.secondary_stack (body)
23290    -- system.standard_library (body)
23291    -- system.string_ops (spec)
23292    -- system.string_ops (body)
23293    -- ada.tags (spec)
23294    -- ada.tags (body)
23295    -- ada.streams (spec)
23296    -- system.finalization_root (spec)
23297    -- system.finalization_root (body)
23298    -- system.string_ops_concat_3 (spec)
23299    -- system.string_ops_concat_3 (body)
23300    -- system.traceback (spec)
23301    -- system.traceback (body)
23302    -- ada.exceptions (body)
23303    -- system.unsigned_types (spec)
23304    -- system.stream_attributes (spec)
23305    -- system.stream_attributes (body)
23306    -- system.finalization_implementation (spec)
23307    -- system.finalization_implementation (body)
23308    -- ada.finalization (spec)
23309    -- ada.finalization (body)
23310    -- ada.finalization.list_controller (spec)
23311    -- ada.finalization.list_controller (body)
23312    -- system.file_control_block (spec)
23313    -- system.file_io (spec)
23314    -- system.file_io (body)
23315    -- ada.text_io (spec)
23316    -- ada.text_io (body)
23317    -- hello (body)
23318    -- END ELABORATION ORDER
23320 end ada_main;
23322 --  The following source file name pragmas allow the generated file
23323 --  names to be unique for different main programs. They are needed
23324 --  since the package name will always be Ada_Main.
23326 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
23327 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
23329 --  Generated package body for Ada_Main starts here
23331 package body ada_main is
23333    --  The actual finalization is performed by calling the
23334    --  library routine in System.Standard_Library.Adafinal
23336    procedure Do_Finalize;
23337    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
23339    -------------
23340    -- adainit --
23341    -------------
23343 @findex adainit
23344    procedure adainit is
23346       --  These booleans are set to True once the associated unit has
23347       --  been elaborated. It is also used to avoid elaborating the
23348       --  same unit twice.
23350       E040 : Boolean;
23351       pragma Import (Ada, E040, "interfaces__c_streams_E");
23353       E008 : Boolean;
23354       pragma Import (Ada, E008, "ada__exceptions_E");
23356       E014 : Boolean;
23357       pragma Import (Ada, E014, "system__exception_table_E");
23359       E053 : Boolean;
23360       pragma Import (Ada, E053, "ada__io_exceptions_E");
23362       E017 : Boolean;
23363       pragma Import (Ada, E017, "system__exceptions_E");
23365       E024 : Boolean;
23366       pragma Import (Ada, E024, "system__secondary_stack_E");
23368       E030 : Boolean;
23369       pragma Import (Ada, E030, "system__stack_checking_E");
23371       E028 : Boolean;
23372       pragma Import (Ada, E028, "system__soft_links_E");
23374       E035 : Boolean;
23375       pragma Import (Ada, E035, "ada__tags_E");
23377       E033 : Boolean;
23378       pragma Import (Ada, E033, "ada__streams_E");
23380       E046 : Boolean;
23381       pragma Import (Ada, E046, "system__finalization_root_E");
23383       E048 : Boolean;
23384       pragma Import (Ada, E048, "system__finalization_implementation_E");
23386       E044 : Boolean;
23387       pragma Import (Ada, E044, "ada__finalization_E");
23389       E057 : Boolean;
23390       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23392       E055 : Boolean;
23393       pragma Import (Ada, E055, "system__file_control_block_E");
23395       E042 : Boolean;
23396       pragma Import (Ada, E042, "system__file_io_E");
23398       E006 : Boolean;
23399       pragma Import (Ada, E006, "ada__text_io_E");
23401       --  Set_Globals is a library routine that stores away the
23402       --  value of the indicated set of global values in global
23403       --  variables within the library.
23405       procedure Set_Globals
23406         (Main_Priority            : Integer;
23407          Time_Slice_Value         : Integer;
23408          WC_Encoding              : Character;
23409          Locking_Policy           : Character;
23410          Queuing_Policy           : Character;
23411          Task_Dispatching_Policy  : Character;
23412          Adafinal                 : System.Address;
23413          Unreserve_All_Interrupts : Integer;
23414          Exception_Tracebacks     : Integer);
23415 @findex __gnat_set_globals
23416       pragma Import (C, Set_Globals, "__gnat_set_globals");
23418       --  SDP_Table_Build is a library routine used to build the
23419       --  exception tables. See unit Ada.Exceptions in files
23420       --  a-except.ads/adb for full details of how zero cost
23421       --  exception handling works. This procedure, the call to
23422       --  it, and the two following tables are all omitted if the
23423       --  build is in longjmp/setjmp exception mode.
23425 @findex SDP_Table_Build
23426 @findex Zero Cost Exceptions
23427       procedure SDP_Table_Build
23428         (SDP_Addresses   : System.Address;
23429          SDP_Count       : Natural;
23430          Elab_Addresses  : System.Address;
23431          Elab_Addr_Count : Natural);
23432       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
23434       --  Table of Unit_Exception_Table addresses. Used for zero
23435       --  cost exception handling to build the top level table.
23437       ST : aliased constant array (1 .. 23) of System.Address := (
23438         Hello'UET_Address,
23439         Ada.Text_Io'UET_Address,
23440         Ada.Exceptions'UET_Address,
23441         Gnat.Heap_Sort_A'UET_Address,
23442         System.Exception_Table'UET_Address,
23443         System.Machine_State_Operations'UET_Address,
23444         System.Secondary_Stack'UET_Address,
23445         System.Parameters'UET_Address,
23446         System.Soft_Links'UET_Address,
23447         System.Stack_Checking'UET_Address,
23448         System.Traceback'UET_Address,
23449         Ada.Streams'UET_Address,
23450         Ada.Tags'UET_Address,
23451         System.String_Ops'UET_Address,
23452         Interfaces.C_Streams'UET_Address,
23453         System.File_Io'UET_Address,
23454         Ada.Finalization'UET_Address,
23455         System.Finalization_Root'UET_Address,
23456         System.Finalization_Implementation'UET_Address,
23457         System.String_Ops_Concat_3'UET_Address,
23458         System.Stream_Attributes'UET_Address,
23459         System.File_Control_Block'UET_Address,
23460         Ada.Finalization.List_Controller'UET_Address);
23462       --  Table of addresses of elaboration routines. Used for
23463       --  zero cost exception handling to make sure these
23464       --  addresses are included in the top level procedure
23465       --  address table.
23467       EA : aliased constant array (1 .. 23) of System.Address := (
23468         adainit'Code_Address,
23469         Do_Finalize'Code_Address,
23470         Ada.Exceptions'Elab_Spec'Address,
23471         System.Exceptions'Elab_Spec'Address,
23472         Interfaces.C_Streams'Elab_Spec'Address,
23473         System.Exception_Table'Elab_Body'Address,
23474         Ada.Io_Exceptions'Elab_Spec'Address,
23475         System.Stack_Checking'Elab_Spec'Address,
23476         System.Soft_Links'Elab_Body'Address,
23477         System.Secondary_Stack'Elab_Body'Address,
23478         Ada.Tags'Elab_Spec'Address,
23479         Ada.Tags'Elab_Body'Address,
23480         Ada.Streams'Elab_Spec'Address,
23481         System.Finalization_Root'Elab_Spec'Address,
23482         Ada.Exceptions'Elab_Body'Address,
23483         System.Finalization_Implementation'Elab_Spec'Address,
23484         System.Finalization_Implementation'Elab_Body'Address,
23485         Ada.Finalization'Elab_Spec'Address,
23486         Ada.Finalization.List_Controller'Elab_Spec'Address,
23487         System.File_Control_Block'Elab_Spec'Address,
23488         System.File_Io'Elab_Body'Address,
23489         Ada.Text_Io'Elab_Spec'Address,
23490         Ada.Text_Io'Elab_Body'Address);
23492    --  Start of processing for adainit
23494    begin
23496       --  Call SDP_Table_Build to build the top level procedure
23497       --  table for zero cost exception handling (omitted in
23498       --  longjmp/setjmp mode).
23500       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23502       --  Call Set_Globals to record various information for
23503       --  this partition.  The values are derived by the binder
23504       --  from information stored in the ali files by the compiler.
23506 @findex __gnat_set_globals
23507       Set_Globals
23508         (Main_Priority            => -1,
23509          --  Priority of main program, -1 if no pragma Priority used
23511          Time_Slice_Value         => -1,
23512          --  Time slice from Time_Slice pragma, -1 if none used
23514          WC_Encoding              => 'b',
23515          --  Wide_Character encoding used, default is brackets
23517          Locking_Policy           => ' ',
23518          --  Locking_Policy used, default of space means not
23519          --  specified, otherwise it is the first character of
23520          --  the policy name.
23522          Queuing_Policy           => ' ',
23523          --  Queuing_Policy used, default of space means not
23524          --  specified, otherwise it is the first character of
23525          --  the policy name.
23527          Task_Dispatching_Policy  => ' ',
23528          --  Task_Dispatching_Policy used, default of space means
23529          --  not specified, otherwise first character of the
23530          --  policy name.
23532          Adafinal                 => System.Null_Address,
23533          --  Address of Adafinal routine, not used anymore
23535          Unreserve_All_Interrupts => 0,
23536          --  Set true if pragma Unreserve_All_Interrupts was used
23538          Exception_Tracebacks     => 0);
23539          --  Indicates if exception tracebacks are enabled
23541       Elab_Final_Code := 1;
23543       --  Now we have the elaboration calls for all units in the partition.
23544       --  The Elab_Spec and Elab_Body attributes generate references to the
23545       --  implicit elaboration procedures generated by the compiler for
23546       --  each unit that requires elaboration.
23548       if not E040 then
23549          Interfaces.C_Streams'Elab_Spec;
23550       end if;
23551       E040 := True;
23552       if not E008 then
23553          Ada.Exceptions'Elab_Spec;
23554       end if;
23555       if not E014 then
23556          System.Exception_Table'Elab_Body;
23557          E014 := True;
23558       end if;
23559       if not E053 then
23560          Ada.Io_Exceptions'Elab_Spec;
23561          E053 := True;
23562       end if;
23563       if not E017 then
23564          System.Exceptions'Elab_Spec;
23565          E017 := True;
23566       end if;
23567       if not E030 then
23568          System.Stack_Checking'Elab_Spec;
23569       end if;
23570       if not E028 then
23571          System.Soft_Links'Elab_Body;
23572          E028 := True;
23573       end if;
23574       E030 := True;
23575       if not E024 then
23576          System.Secondary_Stack'Elab_Body;
23577          E024 := True;
23578       end if;
23579       if not E035 then
23580          Ada.Tags'Elab_Spec;
23581       end if;
23582       if not E035 then
23583          Ada.Tags'Elab_Body;
23584          E035 := True;
23585       end if;
23586       if not E033 then
23587          Ada.Streams'Elab_Spec;
23588          E033 := True;
23589       end if;
23590       if not E046 then
23591          System.Finalization_Root'Elab_Spec;
23592       end if;
23593       E046 := True;
23594       if not E008 then
23595          Ada.Exceptions'Elab_Body;
23596          E008 := True;
23597       end if;
23598       if not E048 then
23599          System.Finalization_Implementation'Elab_Spec;
23600       end if;
23601       if not E048 then
23602          System.Finalization_Implementation'Elab_Body;
23603          E048 := True;
23604       end if;
23605       if not E044 then
23606          Ada.Finalization'Elab_Spec;
23607       end if;
23608       E044 := True;
23609       if not E057 then
23610          Ada.Finalization.List_Controller'Elab_Spec;
23611       end if;
23612       E057 := True;
23613       if not E055 then
23614          System.File_Control_Block'Elab_Spec;
23615          E055 := True;
23616       end if;
23617       if not E042 then
23618          System.File_Io'Elab_Body;
23619          E042 := True;
23620       end if;
23621       if not E006 then
23622          Ada.Text_Io'Elab_Spec;
23623       end if;
23624       if not E006 then
23625          Ada.Text_Io'Elab_Body;
23626          E006 := True;
23627       end if;
23629       Elab_Final_Code := 0;
23630    end adainit;
23632    --------------
23633    -- adafinal --
23634    --------------
23636 @findex adafinal
23637    procedure adafinal is
23638    begin
23639       Do_Finalize;
23640    end adafinal;
23642    ----------
23643    -- main --
23644    ----------
23646    --  main is actually a function, as in the ANSI C standard,
23647    --  defined to return the exit status. The three parameters
23648    --  are the argument count, argument values and environment
23649    --  pointer.
23651 @findex Main Program
23652    function main
23653      (argc : Integer;
23654       argv : System.Address;
23655       envp : System.Address)
23656       return Integer
23657    is
23658       --  The initialize routine performs low level system
23659       --  initialization using a standard library routine which
23660       --  sets up signal handling and performs any other
23661       --  required setup. The routine can be found in file
23662       --  a-init.c.
23664 @findex __gnat_initialize
23665       procedure initialize;
23666       pragma Import (C, initialize, "__gnat_initialize");
23668       --  The finalize routine performs low level system
23669       --  finalization using a standard library routine. The
23670       --  routine is found in file a-final.c and in the standard
23671       --  distribution is a dummy routine that does nothing, so
23672       --  really this is a hook for special user finalization.
23674 @findex __gnat_finalize
23675       procedure finalize;
23676       pragma Import (C, finalize, "__gnat_finalize");
23678       --  We get to the main program of the partition by using
23679       --  pragma Import because if we try to with the unit and
23680       --  call it Ada style, then not only do we waste time
23681       --  recompiling it, but also, we don't really know the right
23682       --  switches (e.g.@: identifier character set) to be used
23683       --  to compile it.
23685       procedure Ada_Main_Program;
23686       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23688    --  Start of processing for main
23690    begin
23691       --  Save global variables
23693       gnat_argc := argc;
23694       gnat_argv := argv;
23695       gnat_envp := envp;
23697       --  Call low level system initialization
23699       Initialize;
23701       --  Call our generated Ada initialization routine
23703       adainit;
23705       --  This is the point at which we want the debugger to get
23706       --  control
23708       Break_Start;
23710       --  Now we call the main program of the partition
23712       Ada_Main_Program;
23714       --  Perform Ada finalization
23716       adafinal;
23718       --  Perform low level system finalization
23720       Finalize;
23722       --  Return the proper exit status
23723       return (gnat_exit_status);
23724    end;
23726 --  This section is entirely comments, so it has no effect on the
23727 --  compilation of the Ada_Main package. It provides the list of
23728 --  object files and linker options, as well as some standard
23729 --  libraries needed for the link. The gnatlink utility parses
23730 --  this b~hello.adb file to read these comment lines to generate
23731 --  the appropriate command line arguments for the call to the
23732 --  system linker. The BEGIN/END lines are used for sentinels for
23733 --  this parsing operation.
23735 --  The exact file names will of course depend on the environment,
23736 --  host/target and location of files on the host system.
23738 @findex Object file list
23739 -- BEGIN Object file/option list
23740    --   ./hello.o
23741    --   -L./
23742    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23743    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23744 -- END Object file/option list
23746 end ada_main;
23747 @end smallexample
23749 @noindent
23750 The Ada code in the above example is exactly what is generated by the
23751 binder. We have added comments to more clearly indicate the function
23752 of each part of the generated @code{Ada_Main} package.
23754 The code is standard Ada in all respects, and can be processed by any
23755 tools that handle Ada. In particular, it is possible to use the debugger
23756 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23757 suppose that for reasons that you do not understand, your program is crashing
23758 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23759 you can place a breakpoint on the call:
23761 @smallexample @c ada
23762 Ada.Text_Io'Elab_Body;
23763 @end smallexample
23765 @noindent
23766 and trace the elaboration routine for this package to find out where
23767 the problem might be (more usually of course you would be debugging
23768 elaboration code in your own application).
23770 @node Elaboration Order Handling in GNAT
23771 @appendix Elaboration Order Handling in GNAT
23772 @cindex Order of elaboration
23773 @cindex Elaboration control
23775 @menu
23776 * Elaboration Code::
23777 * Checking the Elaboration Order::
23778 * Controlling the Elaboration Order::
23779 * Controlling Elaboration in GNAT - Internal Calls::
23780 * Controlling Elaboration in GNAT - External Calls::
23781 * Default Behavior in GNAT - Ensuring Safety::
23782 * Treatment of Pragma Elaborate::
23783 * Elaboration Issues for Library Tasks::
23784 * Mixing Elaboration Models::
23785 * What to Do If the Default Elaboration Behavior Fails::
23786 * Elaboration for Dispatching Calls::
23787 * Summary of Procedures for Elaboration Control::
23788 * Other Elaboration Order Considerations::
23789 @end menu
23791 @noindent
23792 This chapter describes the handling of elaboration code in Ada and
23793 in GNAT, and discusses how the order of elaboration of program units can
23794 be controlled in GNAT, either automatically or with explicit programming
23795 features.
23797 @node Elaboration Code
23798 @section Elaboration Code
23800 @noindent
23801 Ada provides rather general mechanisms for executing code at elaboration
23802 time, that is to say before the main program starts executing. Such code arises
23803 in three contexts:
23805 @table @asis
23806 @item Initializers for variables.
23807 Variables declared at the library level, in package specs or bodies, can
23808 require initialization that is performed at elaboration time, as in:
23809 @smallexample @c ada
23810 @cartouche
23811 Sqrt_Half : Float := Sqrt (0.5);
23812 @end cartouche
23813 @end smallexample
23815 @item Package initialization code
23816 Code in a @code{BEGIN-END} section at the outer level of a package body is
23817 executed as part of the package body elaboration code.
23819 @item Library level task allocators
23820 Tasks that are declared using task allocators at the library level
23821 start executing immediately and hence can execute at elaboration time.
23822 @end table
23824 @noindent
23825 Subprogram calls are possible in any of these contexts, which means that
23826 any arbitrary part of the program may be executed as part of the elaboration
23827 code. It is even possible to write a program which does all its work at
23828 elaboration time, with a null main program, although stylistically this
23829 would usually be considered an inappropriate way to structure
23830 a program.
23832 An important concern arises in the context of elaboration code:
23833 we have to be sure that it is executed in an appropriate order. What we
23834 have is a series of elaboration code sections, potentially one section
23835 for each unit in the program. It is important that these execute
23836 in the correct order. Correctness here means that, taking the above
23837 example of the declaration of @code{Sqrt_Half},
23838 if some other piece of
23839 elaboration code references @code{Sqrt_Half},
23840 then it must run after the
23841 section of elaboration code that contains the declaration of
23842 @code{Sqrt_Half}.
23844 There would never be any order of elaboration problem if we made a rule
23845 that whenever you @code{with} a unit, you must elaborate both the spec and body
23846 of that unit before elaborating the unit doing the @code{with}'ing:
23848 @smallexample @c ada
23849 @group
23850 @cartouche
23851 with Unit_1;
23852 package Unit_2 is @dots{}
23853 @end cartouche
23854 @end group
23855 @end smallexample
23857 @noindent
23858 would require that both the body and spec of @code{Unit_1} be elaborated
23859 before the spec of @code{Unit_2}. However, a rule like that would be far too
23860 restrictive. In particular, it would make it impossible to have routines
23861 in separate packages that were mutually recursive.
23863 You might think that a clever enough compiler could look at the actual
23864 elaboration code and determine an appropriate correct order of elaboration,
23865 but in the general case, this is not possible. Consider the following
23866 example.
23868 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23869 that references
23870 the variable @code{Sqrt_1}, which is declared in the elaboration code
23871 of the body of @code{Unit_1}:
23873 @smallexample @c ada
23874 @cartouche
23875 Sqrt_1 : Float := Sqrt (0.1);
23876 @end cartouche
23877 @end smallexample
23879 @noindent
23880 The elaboration code of the body of @code{Unit_1} also contains:
23882 @smallexample @c ada
23883 @group
23884 @cartouche
23885 if expression_1 = 1 then
23886    Q := Unit_2.Func_2;
23887 end if;
23888 @end cartouche
23889 @end group
23890 @end smallexample
23892 @noindent
23893 @code{Unit_2} is exactly parallel,
23894 it has a procedure @code{Func_2} that references
23895 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23896 the body @code{Unit_2}:
23898 @smallexample @c ada
23899 @cartouche
23900 Sqrt_2 : Float := Sqrt (0.1);
23901 @end cartouche
23902 @end smallexample
23904 @noindent
23905 The elaboration code of the body of @code{Unit_2} also contains:
23907 @smallexample @c ada
23908 @group
23909 @cartouche
23910 if expression_2 = 2 then
23911    Q := Unit_1.Func_1;
23912 end if;
23913 @end cartouche
23914 @end group
23915 @end smallexample
23917 @noindent
23918 Now the question is, which of the following orders of elaboration is
23919 acceptable:
23921 @smallexample
23922 @group
23923 Spec of Unit_1
23924 Spec of Unit_2
23925 Body of Unit_1
23926 Body of Unit_2
23927 @end group
23928 @end smallexample
23930 @noindent
23933 @smallexample
23934 @group
23935 Spec of Unit_2
23936 Spec of Unit_1
23937 Body of Unit_2
23938 Body of Unit_1
23939 @end group
23940 @end smallexample
23942 @noindent
23943 If you carefully analyze the flow here, you will see that you cannot tell
23944 at compile time the answer to this question.
23945 If @code{expression_1} is not equal to 1,
23946 and @code{expression_2} is not equal to 2,
23947 then either order is acceptable, because neither of the function calls is
23948 executed. If both tests evaluate to true, then neither order is acceptable
23949 and in fact there is no correct order.
23951 If one of the two expressions is true, and the other is false, then one
23952 of the above orders is correct, and the other is incorrect. For example,
23953 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23954 then the call to @code{Func_1}
23955 will occur, but not the call to @code{Func_2.}
23956 This means that it is essential
23957 to elaborate the body of @code{Unit_1} before
23958 the body of @code{Unit_2}, so the first
23959 order of elaboration is correct and the second is wrong.
23961 By making @code{expression_1} and @code{expression_2}
23962 depend on input data, or perhaps
23963 the time of day, we can make it impossible for the compiler or binder
23964 to figure out which of these expressions will be true, and hence it
23965 is impossible to guarantee a safe order of elaboration at run time.
23967 @node Checking the Elaboration Order
23968 @section Checking the Elaboration Order
23970 @noindent
23971 In some languages that involve the same kind of elaboration problems,
23972 e.g.@: Java and C++, the programmer is expected to worry about these
23973 ordering problems himself, and it is common to
23974 write a program in which an incorrect elaboration order  gives
23975 surprising results, because it references variables before they
23976 are initialized.
23977 Ada is designed to be a safe language, and a programmer-beware approach is
23978 clearly not sufficient. Consequently, the language provides three lines
23979 of defense:
23981 @table @asis
23982 @item Standard rules
23983 Some standard rules restrict the possible choice of elaboration
23984 order. In particular, if you @code{with} a unit, then its spec is always
23985 elaborated before the unit doing the @code{with}. Similarly, a parent
23986 spec is always elaborated before the child spec, and finally
23987 a spec is always elaborated before its corresponding body.
23989 @item Dynamic elaboration checks
23990 @cindex Elaboration checks
23991 @cindex Checks, elaboration
23992 Dynamic checks are made at run time, so that if some entity is accessed
23993 before it is elaborated (typically  by means of a subprogram call)
23994 then the exception (@code{Program_Error}) is raised.
23996 @item Elaboration control
23997 Facilities are provided for the programmer to specify the desired order
23998 of elaboration.
23999 @end table
24001 Let's look at these facilities in more detail. First, the rules for
24002 dynamic checking. One possible rule would be simply to say that the
24003 exception is raised if you access a variable which has not yet been
24004 elaborated. The trouble with this approach is that it could require
24005 expensive checks on every variable reference. Instead Ada has two
24006 rules which are a little more restrictive, but easier to check, and
24007 easier to state:
24009 @table @asis
24010 @item Restrictions on calls
24011 A subprogram can only be called at elaboration time if its body
24012 has been elaborated. The rules for elaboration given above guarantee
24013 that the spec of the subprogram has been elaborated before the
24014 call, but not the body. If this rule is violated, then the
24015 exception @code{Program_Error} is raised.
24017 @item Restrictions on instantiations
24018 A generic unit can only be instantiated if the body of the generic
24019 unit has been elaborated. Again, the rules for elaboration given above
24020 guarantee that the spec of the generic unit has been elaborated
24021 before the instantiation, but not the body. If this rule is
24022 violated, then the exception @code{Program_Error} is raised.
24023 @end table
24025 @noindent
24026 The idea is that if the body has been elaborated, then any variables
24027 it references must have been elaborated; by checking for the body being
24028 elaborated we guarantee that none of its references causes any
24029 trouble. As we noted above, this is a little too restrictive, because a
24030 subprogram that has no non-local references in its body may in fact be safe
24031 to call. However, it really would be unsafe to rely on this, because
24032 it would mean that the caller was aware of details of the implementation
24033 in the body. This goes against the basic tenets of Ada.
24035 A plausible implementation can be described as follows.
24036 A Boolean variable is associated with each subprogram
24037 and each generic unit. This variable is initialized to False, and is set to
24038 True at the point body is elaborated. Every call or instantiation checks the
24039 variable, and raises @code{Program_Error} if the variable is False.
24041 Note that one might think that it would be good enough to have one Boolean
24042 variable for each package, but that would not deal with cases of trying
24043 to call a body in the same package as the call
24044 that has not been elaborated yet.
24045 Of course a compiler may be able to do enough analysis to optimize away
24046 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24047 does such optimizations, but still the easiest conceptual model is to
24048 think of there being one variable per subprogram.
24050 @node Controlling the Elaboration Order
24051 @section Controlling the Elaboration Order
24053 @noindent
24054 In the previous section we discussed the rules in Ada which ensure
24055 that @code{Program_Error} is raised if an incorrect elaboration order is
24056 chosen. This prevents erroneous executions, but we need mechanisms to
24057 specify a correct execution and avoid the exception altogether.
24058 To achieve this, Ada provides a number of features for controlling
24059 the order of elaboration. We discuss these features in this section.
24061 First, there are several ways of indicating to the compiler that a given
24062 unit has no elaboration problems:
24064 @table @asis
24065 @item packages that do not require a body
24066 A library package that does not require a body does not permit
24067 a body (this rule was introduced in Ada 95).
24068 Thus if we have a such a package, as in:
24070 @smallexample @c ada
24071 @group
24072 @cartouche
24073 package Definitions is
24074    generic
24075       type m is new integer;
24076    package Subp is
24077       type a is array (1 .. 10) of m;
24078       type b is array (1 .. 20) of m;
24079    end Subp;
24080 end Definitions;
24081 @end cartouche
24082 @end group
24083 @end smallexample
24085 @noindent
24086 A package that @code{with}'s @code{Definitions} may safely instantiate
24087 @code{Definitions.Subp} because the compiler can determine that there
24088 definitely is no package body to worry about in this case
24090 @item pragma Pure
24091 @cindex pragma Pure
24092 @findex Pure
24093 Places sufficient restrictions on a unit to guarantee that
24094 no call to any subprogram in the unit can result in an
24095 elaboration problem. This means that the compiler does not need
24096 to worry about the point of elaboration of such units, and in
24097 particular, does not need to check any calls to any subprograms
24098 in this unit.
24100 @item pragma Preelaborate
24101 @findex Preelaborate
24102 @cindex pragma Preelaborate
24103 This pragma places slightly less stringent restrictions on a unit than
24104 does pragma Pure,
24105 but these restrictions are still sufficient to ensure that there
24106 are no elaboration problems with any calls to the unit.
24108 @item pragma Elaborate_Body
24109 @findex Elaborate_Body
24110 @cindex pragma Elaborate_Body
24111 This pragma requires that the body of a unit be elaborated immediately
24112 after its spec. Suppose a unit @code{A} has such a pragma,
24113 and unit @code{B} does
24114 a @code{with} of unit @code{A}. Recall that the standard rules require
24115 the spec of unit @code{A}
24116 to be elaborated before the @code{with}'ing unit; given the pragma in
24117 @code{A}, we also know that the body of @code{A}
24118 will be elaborated before @code{B}, so
24119 that calls to @code{A} are safe and do not need a check.
24120 @end table
24122 @noindent
24123 Note that,
24124 unlike pragma @code{Pure} and pragma @code{Preelaborate},
24125 the use of
24126 @code{Elaborate_Body} does not guarantee that the program is
24127 free of elaboration problems, because it may not be possible
24128 to satisfy the requested elaboration order.
24129 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
24130 If a programmer
24131 marks @code{Unit_1} as @code{Elaborate_Body},
24132 and not @code{Unit_2,} then the order of
24133 elaboration will be:
24135 @smallexample
24136 @group
24137 Spec of Unit_2
24138 Spec of Unit_1
24139 Body of Unit_1
24140 Body of Unit_2
24141 @end group
24142 @end smallexample
24144 @noindent
24145 Now that means that the call to @code{Func_1} in @code{Unit_2}
24146 need not be checked,
24147 it must be safe. But the call to @code{Func_2} in
24148 @code{Unit_1} may still fail if
24149 @code{Expression_1} is equal to 1,
24150 and the programmer must still take
24151 responsibility for this not being the case.
24153 If all units carry a pragma @code{Elaborate_Body}, then all problems are
24154 eliminated, except for calls entirely within a body, which are
24155 in any case fully under programmer control. However, using the pragma
24156 everywhere is not always possible.
24157 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
24158 we marked both of them as having pragma @code{Elaborate_Body}, then
24159 clearly there would be no possible elaboration order.
24161 The above pragmas allow a server to guarantee safe use by clients, and
24162 clearly this is the preferable approach. Consequently a good rule
24163 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
24164 and if this is not possible,
24165 mark them as @code{Elaborate_Body} if possible.
24166 As we have seen, there are situations where neither of these
24167 three pragmas can be used.
24168 So we also provide methods for clients to control the
24169 order of elaboration of the servers on which they depend:
24171 @table @asis
24172 @item pragma Elaborate (unit)
24173 @findex Elaborate
24174 @cindex pragma Elaborate
24175 This pragma is placed in the context clause, after a @code{with} clause,
24176 and it requires that the body of the named unit be elaborated before
24177 the unit in which the pragma occurs. The idea is to use this pragma
24178 if the current unit calls at elaboration time, directly or indirectly,
24179 some subprogram in the named unit.
24181 @item pragma Elaborate_All (unit)
24182 @findex Elaborate_All
24183 @cindex pragma Elaborate_All
24184 This is a stronger version of the Elaborate pragma. Consider the
24185 following example:
24187 @smallexample
24188 Unit A @code{with}'s unit B and calls B.Func in elab code
24189 Unit B @code{with}'s unit C, and B.Func calls C.Func
24190 @end smallexample
24192 @noindent
24193 Now if we put a pragma @code{Elaborate (B)}
24194 in unit @code{A}, this ensures that the
24195 body of @code{B} is elaborated before the call, but not the
24196 body of @code{C}, so
24197 the call to @code{C.Func} could still cause @code{Program_Error} to
24198 be raised.
24200 The effect of a pragma @code{Elaborate_All} is stronger, it requires
24201 not only that the body of the named unit be elaborated before the
24202 unit doing the @code{with}, but also the bodies of all units that the
24203 named unit uses, following @code{with} links transitively. For example,
24204 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
24205 then it requires
24206 not only that the body of @code{B} be elaborated before @code{A},
24207 but also the
24208 body of @code{C}, because @code{B} @code{with}'s @code{C}.
24209 @end table
24211 @noindent
24212 We are now in a position to give a usage rule in Ada for avoiding
24213 elaboration problems, at least if dynamic dispatching and access to
24214 subprogram values are not used. We will handle these cases separately
24215 later.
24217 The rule is simple. If a unit has elaboration code that can directly or
24218 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
24219 a generic package in a @code{with}'ed unit,
24220 then if the @code{with}'ed unit does not have
24221 pragma @code{Pure} or @code{Preelaborate}, then the client should have
24222 a pragma @code{Elaborate_All}
24223 for the @code{with}'ed unit. By following this rule a client is
24224 assured that calls can be made without risk of an exception.
24226 For generic subprogram instantiations, the rule can be relaxed to
24227 require only a pragma @code{Elaborate} since elaborating the body
24228 of a subprogram cannot cause any transitive elaboration (we are
24229 not calling the subprogram in this case, just elaborating its
24230 declaration).
24232 If this rule is not followed, then a program may be in one of four
24233 states:
24235 @table @asis
24236 @item No order exists
24237 No order of elaboration exists which follows the rules, taking into
24238 account any @code{Elaborate}, @code{Elaborate_All},
24239 or @code{Elaborate_Body} pragmas. In
24240 this case, an Ada compiler must diagnose the situation at bind
24241 time, and refuse to build an executable program.
24243 @item One or more orders exist, all incorrect
24244 One or more acceptable elaboration orders exist, and all of them
24245 generate an elaboration order problem. In this case, the binder
24246 can build an executable program, but @code{Program_Error} will be raised
24247 when the program is run.
24249 @item Several orders exist, some right, some incorrect
24250 One or more acceptable elaboration orders exists, and some of them
24251 work, and some do not. The programmer has not controlled
24252 the order of elaboration, so the binder may or may not pick one of
24253 the correct orders, and the program may or may not raise an
24254 exception when it is run. This is the worst case, because it means
24255 that the program may fail when moved to another compiler, or even
24256 another version of the same compiler.
24258 @item One or more orders exists, all correct
24259 One ore more acceptable elaboration orders exist, and all of them
24260 work. In this case the program runs successfully. This state of
24261 affairs can be guaranteed by following the rule we gave above, but
24262 may be true even if the rule is not followed.
24263 @end table
24265 @noindent
24266 Note that one additional advantage of following our rules on the use
24267 of @code{Elaborate} and @code{Elaborate_All}
24268 is that the program continues to stay in the ideal (all orders OK) state
24269 even if maintenance
24270 changes some bodies of some units. Conversely, if a program that does
24271 not follow this rule happens to be safe at some point, this state of affairs
24272 may deteriorate silently as a result of maintenance changes.
24274 You may have noticed that the above discussion did not mention
24275 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
24276 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
24277 code in the body makes calls to some other unit, so it is still necessary
24278 to use @code{Elaborate_All} on such units.
24280 @node Controlling Elaboration in GNAT - Internal Calls
24281 @section Controlling Elaboration in GNAT - Internal Calls
24283 @noindent
24284 In the case of internal calls, i.e., calls within a single package, the
24285 programmer has full control over the order of elaboration, and it is up
24286 to the programmer to elaborate declarations in an appropriate order. For
24287 example writing:
24289 @smallexample @c ada
24290 @group
24291 @cartouche
24292 function One return Float;
24294 Q : Float := One;
24296 function One return Float is
24297 begin
24298      return 1.0;
24299 end One;
24300 @end cartouche
24301 @end group
24302 @end smallexample
24304 @noindent
24305 will obviously raise @code{Program_Error} at run time, because function
24306 One will be called before its body is elaborated. In this case GNAT will
24307 generate a warning that the call will raise @code{Program_Error}:
24309 @smallexample
24310 @group
24311 @cartouche
24312  1. procedure y is
24313  2.    function One return Float;
24314  3.
24315  4.    Q : Float := One;
24316                     |
24317     >>> warning: cannot call "One" before body is elaborated
24318     >>> warning: Program_Error will be raised at run time
24320  5.
24321  6.    function One return Float is
24322  7.    begin
24323  8.         return 1.0;
24324  9.    end One;
24326 11. begin
24327 12.    null;
24328 13. end;
24329 @end cartouche
24330 @end group
24331 @end smallexample
24333 @noindent
24334 Note that in this particular case, it is likely that the call is safe, because
24335 the function @code{One} does not access any global variables.
24336 Nevertheless in Ada, we do not want the validity of the check to depend on
24337 the contents of the body (think about the separate compilation case), so this
24338 is still wrong, as we discussed in the previous sections.
24340 The error is easily corrected by rearranging the declarations so that the
24341 body of @code{One} appears before the declaration containing the call
24342 (note that in Ada 95 and Ada 2005,
24343 declarations can appear in any order, so there is no restriction that
24344 would prevent this reordering, and if we write:
24346 @smallexample @c ada
24347 @group
24348 @cartouche
24349 function One return Float;
24351 function One return Float is
24352 begin
24353      return 1.0;
24354 end One;
24356 Q : Float := One;
24357 @end cartouche
24358 @end group
24359 @end smallexample
24361 @noindent
24362 then all is well, no warning is generated, and no
24363 @code{Program_Error} exception
24364 will be raised.
24365 Things are more complicated when a chain of subprograms is executed:
24367 @smallexample @c ada
24368 @group
24369 @cartouche
24370 function A return Integer;
24371 function B return Integer;
24372 function C return Integer;
24374 function B return Integer is begin return A; end;
24375 function C return Integer is begin return B; end;
24377 X : Integer := C;
24379 function A return Integer is begin return 1; end;
24380 @end cartouche
24381 @end group
24382 @end smallexample
24384 @noindent
24385 Now the call to @code{C}
24386 at elaboration time in the declaration of @code{X} is correct, because
24387 the body of @code{C} is already elaborated,
24388 and the call to @code{B} within the body of
24389 @code{C} is correct, but the call
24390 to @code{A} within the body of @code{B} is incorrect, because the body
24391 of @code{A} has not been elaborated, so @code{Program_Error}
24392 will be raised on the call to @code{A}.
24393 In this case GNAT will generate a
24394 warning that @code{Program_Error} may be
24395 raised at the point of the call. Let's look at the warning:
24397 @smallexample
24398 @group
24399 @cartouche
24400  1. procedure x is
24401  2.    function A return Integer;
24402  3.    function B return Integer;
24403  4.    function C return Integer;
24404  5.
24405  6.    function B return Integer is begin return A; end;
24406                                                     |
24407     >>> warning: call to "A" before body is elaborated may
24408                  raise Program_Error
24409     >>> warning: "B" called at line 7
24410     >>> warning: "C" called at line 9
24412  7.    function C return Integer is begin return B; end;
24413  8.
24414  9.    X : Integer := C;
24416 11.    function A return Integer is begin return 1; end;
24418 13. begin
24419 14.    null;
24420 15. end;
24421 @end cartouche
24422 @end group
24423 @end smallexample
24425 @noindent
24426 Note that the message here says ``may raise'', instead of the direct case,
24427 where the message says ``will be raised''. That's because whether
24428 @code{A} is
24429 actually called depends in general on run-time flow of control.
24430 For example, if the body of @code{B} said
24432 @smallexample @c ada
24433 @group
24434 @cartouche
24435 function B return Integer is
24436 begin
24437    if some-condition-depending-on-input-data then
24438       return A;
24439    else
24440       return 1;
24441    end if;
24442 end B;
24443 @end cartouche
24444 @end group
24445 @end smallexample
24447 @noindent
24448 then we could not know until run time whether the incorrect call to A would
24449 actually occur, so @code{Program_Error} might
24450 or might not be raised. It is possible for a compiler to
24451 do a better job of analyzing bodies, to
24452 determine whether or not @code{Program_Error}
24453 might be raised, but it certainly
24454 couldn't do a perfect job (that would require solving the halting problem
24455 and is provably impossible), and because this is a warning anyway, it does
24456 not seem worth the effort to do the analysis. Cases in which it
24457 would be relevant are rare.
24459 In practice, warnings of either of the forms given
24460 above will usually correspond to
24461 real errors, and should be examined carefully and eliminated.
24462 In the rare case where a warning is bogus, it can be suppressed by any of
24463 the following methods:
24465 @itemize @bullet
24466 @item
24467 Compile with the @option{-gnatws} switch set
24469 @item
24470 Suppress @code{Elaboration_Check} for the called subprogram
24472 @item
24473 Use pragma @code{Warnings_Off} to turn warnings off for the call
24474 @end itemize
24476 @noindent
24477 For the internal elaboration check case,
24478 GNAT by default generates the
24479 necessary run-time checks to ensure
24480 that @code{Program_Error} is raised if any
24481 call fails an elaboration check. Of course this can only happen if a
24482 warning has been issued as described above. The use of pragma
24483 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24484 some of these checks, meaning that it may be possible (but is not
24485 guaranteed) for a program to be able to call a subprogram whose body
24486 is not yet elaborated, without raising a @code{Program_Error} exception.
24488 @node Controlling Elaboration in GNAT - External Calls
24489 @section Controlling Elaboration in GNAT - External Calls
24491 @noindent
24492 The previous section discussed the case in which the execution of a
24493 particular thread of elaboration code occurred entirely within a
24494 single unit. This is the easy case to handle, because a programmer
24495 has direct and total control over the order of elaboration, and
24496 furthermore, checks need only be generated in cases which are rare
24497 and which the compiler can easily detect.
24498 The situation is more complex when separate compilation is taken into account.
24499 Consider the following:
24501 @smallexample @c ada
24502 @cartouche
24503 @group
24504 package Math is
24505    function Sqrt (Arg : Float) return Float;
24506 end Math;
24508 package body Math is
24509    function Sqrt (Arg : Float) return Float is
24510    begin
24511          @dots{}
24512    end Sqrt;
24513 end Math;
24514 @end group
24515 @group
24516 with Math;
24517 package Stuff is
24518    X : Float := Math.Sqrt (0.5);
24519 end Stuff;
24521 with Stuff;
24522 procedure Main is
24523 begin
24524    @dots{}
24525 end Main;
24526 @end group
24527 @end cartouche
24528 @end smallexample
24530 @noindent
24531 where @code{Main} is the main program. When this program is executed, the
24532 elaboration code must first be executed, and one of the jobs of the
24533 binder is to determine the order in which the units of a program are
24534 to be elaborated. In this case we have four units: the spec and body
24535 of @code{Math},
24536 the spec of @code{Stuff} and the body of @code{Main}).
24537 In what order should the four separate sections of elaboration code
24538 be executed?
24540 There are some restrictions in the order of elaboration that the binder
24541 can choose. In particular, if unit U has a @code{with}
24542 for a package @code{X}, then you
24543 are assured that the spec of @code{X}
24544 is elaborated before U , but you are
24545 not assured that the body of @code{X}
24546 is elaborated before U.
24547 This means that in the above case, the binder is allowed to choose the
24548 order:
24550 @smallexample
24551 spec of Math
24552 spec of Stuff
24553 body of Math
24554 body of Main
24555 @end smallexample
24557 @noindent
24558 but that's not good, because now the call to @code{Math.Sqrt}
24559 that happens during
24560 the elaboration of the @code{Stuff}
24561 spec happens before the body of @code{Math.Sqrt} is
24562 elaborated, and hence causes @code{Program_Error} exception to be raised.
24563 At first glance, one might say that the binder is misbehaving, because
24564 obviously you want to elaborate the body of something you @code{with}
24565 first, but
24566 that is not a general rule that can be followed in all cases. Consider
24568 @smallexample @c ada
24569 @group
24570 @cartouche
24571 package X is @dots{}
24573 package Y is @dots{}
24575 with X;
24576 package body Y is @dots{}
24578 with Y;
24579 package body X is @dots{}
24580 @end cartouche
24581 @end group
24582 @end smallexample
24584 @noindent
24585 This is a common arrangement, and, apart from the order of elaboration
24586 problems that might arise in connection with elaboration code, this works fine.
24587 A rule that says that you must first elaborate the body of anything you
24588 @code{with} cannot work in this case:
24589 the body of @code{X} @code{with}'s @code{Y},
24590 which means you would have to
24591 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24592 which means
24593 you have to elaborate the body of @code{X} first, but @dots{} and we have a
24594 loop that cannot be broken.
24596 It is true that the binder can in many cases guess an order of elaboration
24597 that is unlikely to cause a @code{Program_Error}
24598 exception to be raised, and it tries to do so (in the
24599 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24600 by default
24601 elaborate the body of @code{Math} right after its spec, so all will be well).
24603 However, a program that blindly relies on the binder to be helpful can
24604 get into trouble, as we discussed in the previous sections, so
24605 GNAT
24606 provides a number of facilities for assisting the programmer in
24607 developing programs that are robust with respect to elaboration order.
24609 @node Default Behavior in GNAT - Ensuring Safety
24610 @section Default Behavior in GNAT - Ensuring Safety
24612 @noindent
24613 The default behavior in GNAT ensures elaboration safety. In its
24614 default mode GNAT implements the
24615 rule we previously described as the right approach. Let's restate it:
24617 @itemize
24618 @item
24619 @emph{If a unit has elaboration code that can directly or indirectly make a
24620 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24621 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24622 does not have pragma @code{Pure} or
24623 @code{Preelaborate}, then the client should have an
24624 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24626 @emph{In the case of instantiating a generic subprogram, it is always
24627 sufficient to have only an @code{Elaborate} pragma for the
24628 @code{with}'ed unit.}
24629 @end itemize
24631 @noindent
24632 By following this rule a client is assured that calls and instantiations
24633 can be made without risk of an exception.
24635 In this mode GNAT traces all calls that are potentially made from
24636 elaboration code, and puts in any missing implicit @code{Elaborate}
24637 and @code{Elaborate_All} pragmas.
24638 The advantage of this approach is that no elaboration problems
24639 are possible if the binder can find an elaboration order that is
24640 consistent with these implicit @code{Elaborate} and
24641 @code{Elaborate_All} pragmas. The
24642 disadvantage of this approach is that no such order may exist.
24644 If the binder does not generate any diagnostics, then it means that it has
24645 found an elaboration order that is guaranteed to be safe. However, the binder
24646 may still be relying on implicitly generated @code{Elaborate} and
24647 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24648 guaranteed.
24650 If it is important to guarantee portability, then the compilations should
24651 use the
24652 @option{-gnatwl}
24653 (warn on elaboration problems) switch. This will cause warning messages
24654 to be generated indicating the missing @code{Elaborate} and
24655 @code{Elaborate_All} pragmas.
24656 Consider the following source program:
24658 @smallexample @c ada
24659 @group
24660 @cartouche
24661 with k;
24662 package j is
24663   m : integer := k.r;
24664 end;
24665 @end cartouche
24666 @end group
24667 @end smallexample
24669 @noindent
24670 where it is clear that there
24671 should be a pragma @code{Elaborate_All}
24672 for unit @code{k}. An implicit pragma will be generated, and it is
24673 likely that the binder will be able to honor it. However, if you want
24674 to port this program to some other Ada compiler than GNAT.
24675 it is safer to include the pragma explicitly in the source. If this
24676 unit is compiled with the
24677 @option{-gnatwl}
24678 switch, then the compiler outputs a warning:
24680 @smallexample
24681 @group
24682 @cartouche
24683 1. with k;
24684 2. package j is
24685 3.   m : integer := k.r;
24686                      |
24687    >>> warning: call to "r" may raise Program_Error
24688    >>> warning: missing pragma Elaborate_All for "k"
24690 4. end;
24691 @end cartouche
24692 @end group
24693 @end smallexample
24695 @noindent
24696 and these warnings can be used as a guide for supplying manually
24697 the missing pragmas. It is usually a bad idea to use this warning
24698 option during development. That's because it will warn you when
24699 you need to put in a pragma, but cannot warn you when it is time
24700 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24701 unnecessary dependencies and even false circularities.
24703 This default mode is more restrictive than the Ada Reference
24704 Manual, and it is possible to construct programs which will compile
24705 using the dynamic model described there, but will run into a
24706 circularity using the safer static model we have described.
24708 Of course any Ada compiler must be able to operate in a mode
24709 consistent with the requirements of the Ada Reference Manual,
24710 and in particular must have the capability of implementing the
24711 standard dynamic model of elaboration with run-time checks.
24713 In GNAT, this standard mode can be achieved either by the use of
24714 the @option{-gnatE} switch on the compiler (@command{gcc} or
24715 @command{gnatmake}) command, or by the use of the configuration pragma:
24717 @smallexample @c ada
24718 pragma Elaboration_Checks (DYNAMIC);
24719 @end smallexample
24721 @noindent
24722 Either approach will cause the unit affected to be compiled using the
24723 standard dynamic run-time elaboration checks described in the Ada
24724 Reference Manual. The static model is generally preferable, since it
24725 is clearly safer to rely on compile and link time checks rather than
24726 run-time checks. However, in the case of legacy code, it may be
24727 difficult to meet the requirements of the static model. This
24728 issue is further discussed in
24729 @ref{What to Do If the Default Elaboration Behavior Fails}.
24731 Note that the static model provides a strict subset of the allowed
24732 behavior and programs of the Ada Reference Manual, so if you do
24733 adhere to the static model and no circularities exist,
24734 then you are assured that your program will
24735 work using the dynamic model, providing that you remove any
24736 pragma Elaborate statements from the source.
24738 @node Treatment of Pragma Elaborate
24739 @section Treatment of Pragma Elaborate
24740 @cindex Pragma Elaborate
24742 @noindent
24743 The use of @code{pragma Elaborate}
24744 should generally be avoided in Ada 95 and Ada 2005 programs,
24745 since there is no guarantee that transitive calls
24746 will be properly handled. Indeed at one point, this pragma was placed
24747 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24749 Now that's a bit restrictive. In practice, the case in which
24750 @code{pragma Elaborate} is useful is when the caller knows that there
24751 are no transitive calls, or that the called unit contains all necessary
24752 transitive @code{pragma Elaborate} statements, and legacy code often
24753 contains such uses.
24755 Strictly speaking the static mode in GNAT should ignore such pragmas,
24756 since there is no assurance at compile time that the necessary safety
24757 conditions are met. In practice, this would cause GNAT to be incompatible
24758 with correctly written Ada 83 code that had all necessary
24759 @code{pragma Elaborate} statements in place. Consequently, we made the
24760 decision that GNAT in its default mode will believe that if it encounters
24761 a @code{pragma Elaborate} then the programmer knows what they are doing,
24762 and it will trust that no elaboration errors can occur.
24764 The result of this decision is two-fold. First to be safe using the
24765 static mode, you should remove all @code{pragma Elaborate} statements.
24766 Second, when fixing circularities in existing code, you can selectively
24767 use @code{pragma Elaborate} statements to convince the static mode of
24768 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24769 statement.
24771 When using the static mode with @option{-gnatwl}, any use of
24772 @code{pragma Elaborate} will generate a warning about possible
24773 problems.
24775 @node Elaboration Issues for Library Tasks
24776 @section Elaboration Issues for Library Tasks
24777 @cindex Library tasks, elaboration issues
24778 @cindex Elaboration of library tasks
24780 @noindent
24781 In this section we examine special elaboration issues that arise for
24782 programs that declare library level tasks.
24784 Generally the model of execution of an Ada program is that all units are
24785 elaborated, and then execution of the program starts. However, the
24786 declaration of library tasks definitely does not fit this model. The
24787 reason for this is that library tasks start as soon as they are declared
24788 (more precisely, as soon as the statement part of the enclosing package
24789 body is reached), that is to say before elaboration
24790 of the program is complete. This means that if such a task calls a
24791 subprogram, or an entry in another task, the callee may or may not be
24792 elaborated yet, and in the standard
24793 Reference Manual model of dynamic elaboration checks, you can even
24794 get timing dependent Program_Error exceptions, since there can be
24795 a race between the elaboration code and the task code.
24797 The static model of elaboration in GNAT seeks to avoid all such
24798 dynamic behavior, by being conservative, and the conservative
24799 approach in this particular case is to assume that all the code
24800 in a task body is potentially executed at elaboration time if
24801 a task is declared at the library level.
24803 This can definitely result in unexpected circularities. Consider
24804 the following example
24806 @smallexample @c ada
24807 package Decls is
24808   task Lib_Task is
24809      entry Start;
24810   end Lib_Task;
24812   type My_Int is new Integer;
24814   function Ident (M : My_Int) return My_Int;
24815 end Decls;
24817 with Utils;
24818 package body Decls is
24819   task body Lib_Task is
24820   begin
24821      accept Start;
24822      Utils.Put_Val (2);
24823   end Lib_Task;
24825   function Ident (M : My_Int) return My_Int is
24826   begin
24827      return M;
24828   end Ident;
24829 end Decls;
24831 with Decls;
24832 package Utils is
24833   procedure Put_Val (Arg : Decls.My_Int);
24834 end Utils;
24836 with Text_IO;
24837 package body Utils is
24838   procedure Put_Val (Arg : Decls.My_Int) is
24839   begin
24840      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24841   end Put_Val;
24842 end Utils;
24844 with Decls;
24845 procedure Main is
24846 begin
24847    Decls.Lib_Task.Start;
24848 end;
24849 @end smallexample
24851 @noindent
24852 If the above example is compiled in the default static elaboration
24853 mode, then a circularity occurs. The circularity comes from the call
24854 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24855 this call occurs in elaboration code, we need an implicit pragma
24856 @code{Elaborate_All} for @code{Utils}. This means that not only must
24857 the spec and body of @code{Utils} be elaborated before the body
24858 of @code{Decls}, but also the spec and body of any unit that is
24859 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24860 the body of @code{Decls}. This is the transitive implication of
24861 pragma @code{Elaborate_All} and it makes sense, because in general
24862 the body of @code{Put_Val} might have a call to something in a
24863 @code{with'ed} unit.
24865 In this case, the body of Utils (actually its spec) @code{with's}
24866 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24867 must be elaborated before itself, in case there is a call from the
24868 body of @code{Utils}.
24870 Here is the exact chain of events we are worrying about:
24872 @enumerate
24873 @item
24874 In the body of @code{Decls} a call is made from within the body of a library
24875 task to a subprogram in the package @code{Utils}. Since this call may
24876 occur at elaboration time (given that the task is activated at elaboration
24877 time), we have to assume the worst, i.e., that the
24878 call does happen at elaboration time.
24880 @item
24881 This means that the body and spec of @code{Util} must be elaborated before
24882 the body of @code{Decls} so that this call does not cause an access before
24883 elaboration.
24885 @item
24886 Within the body of @code{Util}, specifically within the body of
24887 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24888 by this package.
24890 @item
24891 One such @code{with}'ed package is package @code{Decls}, so there
24892 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24893 In fact there is such a call in this example, but we would have to
24894 assume that there was such a call even if it were not there, since
24895 we are not supposed to write the body of @code{Decls} knowing what
24896 is in the body of @code{Utils}; certainly in the case of the
24897 static elaboration model, the compiler does not know what is in
24898 other bodies and must assume the worst.
24900 @item
24901 This means that the spec and body of @code{Decls} must also be
24902 elaborated before we elaborate the unit containing the call, but
24903 that unit is @code{Decls}! This means that the body of @code{Decls}
24904 must be elaborated before itself, and that's a circularity.
24905 @end enumerate
24907 @noindent
24908 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24909 the body of @code{Decls} you will get a true Ada Reference Manual
24910 circularity that makes the program illegal.
24912 In practice, we have found that problems with the static model of
24913 elaboration in existing code often arise from library tasks, so
24914 we must address this particular situation.
24916 Note that if we compile and run the program above, using the dynamic model of
24917 elaboration (that is to say use the @option{-gnatE} switch),
24918 then it compiles, binds,
24919 links, and runs, printing the expected result of 2. Therefore in some sense
24920 the circularity here is only apparent, and we need to capture
24921 the properties of this program that  distinguish it from other library-level
24922 tasks that have real elaboration problems.
24924 We have four possible answers to this question:
24926 @itemize @bullet
24928 @item
24929 Use the dynamic model of elaboration.
24931 If we use the @option{-gnatE} switch, then as noted above, the program works.
24932 Why is this? If we examine the task body, it is apparent that the task cannot
24933 proceed past the
24934 @code{accept} statement until after elaboration has been completed, because
24935 the corresponding entry call comes from the main program, not earlier.
24936 This is why the dynamic model works here. But that's really giving
24937 up on a precise analysis, and we prefer to take this approach only if we cannot
24938 solve the
24939 problem in any other manner. So let us examine two ways to reorganize
24940 the program to avoid the potential elaboration problem.
24942 @item
24943 Split library tasks into separate packages.
24945 Write separate packages, so that library tasks are isolated from
24946 other declarations as much as possible. Let us look at a variation on
24947 the above program.
24949 @smallexample @c ada
24950 package Decls1 is
24951   task Lib_Task is
24952      entry Start;
24953   end Lib_Task;
24954 end Decls1;
24956 with Utils;
24957 package body Decls1 is
24958   task body Lib_Task is
24959   begin
24960      accept Start;
24961      Utils.Put_Val (2);
24962   end Lib_Task;
24963 end Decls1;
24965 package Decls2 is
24966   type My_Int is new Integer;
24967   function Ident (M : My_Int) return My_Int;
24968 end Decls2;
24970 with Utils;
24971 package body Decls2 is
24972   function Ident (M : My_Int) return My_Int is
24973   begin
24974      return M;
24975   end Ident;
24976 end Decls2;
24978 with Decls2;
24979 package Utils is
24980   procedure Put_Val (Arg : Decls2.My_Int);
24981 end Utils;
24983 with Text_IO;
24984 package body Utils is
24985   procedure Put_Val (Arg : Decls2.My_Int) is
24986   begin
24987      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24988   end Put_Val;
24989 end Utils;
24991 with Decls1;
24992 procedure Main is
24993 begin
24994    Decls1.Lib_Task.Start;
24995 end;
24996 @end smallexample
24998 @noindent
24999 All we have done is to split @code{Decls} into two packages, one
25000 containing the library task, and one containing everything else. Now
25001 there is no cycle, and the program compiles, binds, links and executes
25002 using the default static model of elaboration.
25004 @item
25005 Declare separate task types.
25007 A significant part of the problem arises because of the use of the
25008 single task declaration form. This means that the elaboration of
25009 the task type, and the elaboration of the task itself (i.e.@: the
25010 creation of the task) happen at the same time. A good rule
25011 of style in Ada is to always create explicit task types. By
25012 following the additional step of placing task objects in separate
25013 packages from the task type declaration, many elaboration problems
25014 are avoided. Here is another modified example of the example program:
25016 @smallexample @c ada
25017 package Decls is
25018   task type Lib_Task_Type is
25019      entry Start;
25020   end Lib_Task_Type;
25022   type My_Int is new Integer;
25024   function Ident (M : My_Int) return My_Int;
25025 end Decls;
25027 with Utils;
25028 package body Decls is
25029   task body Lib_Task_Type is
25030   begin
25031      accept Start;
25032      Utils.Put_Val (2);
25033   end Lib_Task_Type;
25035   function Ident (M : My_Int) return My_Int is
25036   begin
25037      return M;
25038   end Ident;
25039 end Decls;
25041 with Decls;
25042 package Utils is
25043   procedure Put_Val (Arg : Decls.My_Int);
25044 end Utils;
25046 with Text_IO;
25047 package body Utils is
25048   procedure Put_Val (Arg : Decls.My_Int) is
25049   begin
25050      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25051   end Put_Val;
25052 end Utils;
25054 with Decls;
25055 package Declst is
25056    Lib_Task : Decls.Lib_Task_Type;
25057 end Declst;
25059 with Declst;
25060 procedure Main is
25061 begin
25062    Declst.Lib_Task.Start;
25063 end;
25064 @end smallexample
25066 @noindent
25067 What we have done here is to replace the @code{task} declaration in
25068 package @code{Decls} with a @code{task type} declaration. Then we
25069 introduce a separate package @code{Declst} to contain the actual
25070 task object. This separates the elaboration issues for
25071 the @code{task type}
25072 declaration, which causes no trouble, from the elaboration issues
25073 of the task object, which is also unproblematic, since it is now independent
25074 of the elaboration of  @code{Utils}.
25075 This separation of concerns also corresponds to
25076 a generally sound engineering principle of separating declarations
25077 from instances. This version of the program also compiles, binds, links,
25078 and executes, generating the expected output.
25080 @item
25081 Use No_Entry_Calls_In_Elaboration_Code restriction.
25082 @cindex No_Entry_Calls_In_Elaboration_Code
25084 The previous two approaches described how a program can be restructured
25085 to avoid the special problems caused by library task bodies. in practice,
25086 however, such restructuring may be difficult to apply to existing legacy code,
25087 so we must consider solutions that do not require massive rewriting.
25089 Let us consider more carefully why our original sample program works
25090 under the dynamic model of elaboration. The reason is that the code
25091 in the task body blocks immediately on the @code{accept}
25092 statement. Now of course there is nothing to prohibit elaboration
25093 code from making entry calls (for example from another library level task),
25094 so we cannot tell in isolation that
25095 the task will not execute the accept statement  during elaboration.
25097 However, in practice it is very unusual to see elaboration code
25098 make any entry calls, and the pattern of tasks starting
25099 at elaboration time and then immediately blocking on @code{accept} or
25100 @code{select} statements is very common. What this means is that
25101 the compiler is being too pessimistic when it analyzes the
25102 whole package body as though it might be executed at elaboration
25103 time.
25105 If we know that the elaboration code contains no entry calls, (a very safe
25106 assumption most of the time, that could almost be made the default
25107 behavior), then we can compile all units of the program under control
25108 of the following configuration pragma:
25110 @smallexample
25111 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
25112 @end smallexample
25114 @noindent
25115 This pragma can be placed in the @file{gnat.adc} file in the usual
25116 manner. If we take our original unmodified program and compile it
25117 in the presence of a @file{gnat.adc} containing the above pragma,
25118 then once again, we can compile, bind, link, and execute, obtaining
25119 the expected result. In the presence of this pragma, the compiler does
25120 not trace calls in a task body, that appear after the first @code{accept}
25121 or @code{select} statement, and therefore does not report a potential
25122 circularity in the original program.
25124 The compiler will check to the extent it can that the above
25125 restriction is not violated, but it is not always possible to do a
25126 complete check at compile time, so it is important to use this
25127 pragma only if the stated restriction is in fact met, that is to say
25128 no task receives an entry call before elaboration of all units is completed.
25130 @end itemize
25132 @node Mixing Elaboration Models
25133 @section Mixing Elaboration Models
25134 @noindent
25135 So far, we have assumed that the entire program is either compiled
25136 using the dynamic model or static model, ensuring consistency. It
25137 is possible to mix the two models, but rules have to be followed
25138 if this mixing is done to ensure that elaboration checks are not
25139 omitted.
25141 The basic rule is that @emph{a unit compiled with the static model cannot
25142 be @code{with'ed} by a unit compiled with the dynamic model}. The
25143 reason for this is that in the static model, a unit assumes that
25144 its clients guarantee to use (the equivalent of) pragma
25145 @code{Elaborate_All} so that no elaboration checks are required
25146 in inner subprograms, and this assumption is violated if the
25147 client is compiled with dynamic checks.
25149 The precise rule is as follows. A unit that is compiled with dynamic
25150 checks can only @code{with} a unit that meets at least one of the
25151 following criteria:
25153 @itemize @bullet
25155 @item
25156 The @code{with'ed} unit is itself compiled with dynamic elaboration
25157 checks (that is with the @option{-gnatE} switch.
25159 @item
25160 The @code{with'ed} unit is an internal GNAT implementation unit from
25161 the System, Interfaces, Ada, or GNAT hierarchies.
25163 @item
25164 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25166 @item
25167 The @code{with'ing} unit (that is the client) has an explicit pragma
25168 @code{Elaborate_All} for the @code{with'ed} unit.
25170 @end itemize
25172 @noindent
25173 If this rule is violated, that is if a unit with dynamic elaboration
25174 checks @code{with's} a unit that does not meet one of the above four
25175 criteria, then the binder (@code{gnatbind}) will issue a warning
25176 similar to that in the following example:
25178 @smallexample
25179 warning: "x.ads" has dynamic elaboration checks and with's
25180 warning:   "y.ads" which has static elaboration checks
25181 @end smallexample
25183 @noindent
25184 These warnings indicate that the rule has been violated, and that as a result
25185 elaboration checks may be missed in the resulting executable file.
25186 This warning may be suppressed using the @option{-ws} binder switch
25187 in the usual manner.
25189 One useful application of this mixing rule is in the case of a subsystem
25190 which does not itself @code{with} units from the remainder of the
25191 application. In this case, the entire subsystem can be compiled with
25192 dynamic checks to resolve a circularity in the subsystem, while
25193 allowing the main application that uses this subsystem to be compiled
25194 using the more reliable default static model.
25196 @node What to Do If the Default Elaboration Behavior Fails
25197 @section What to Do If the Default Elaboration Behavior Fails
25199 @noindent
25200 If the binder cannot find an acceptable order, it outputs detailed
25201 diagnostics. For example:
25202 @smallexample
25203 @group
25204 @iftex
25205 @leftskip=0cm
25206 @end iftex
25207 error: elaboration circularity detected
25208 info:   "proc (body)" must be elaborated before "pack (body)"
25209 info:     reason: Elaborate_All probably needed in unit "pack (body)"
25210 info:     recompile "pack (body)" with -gnatwl
25211 info:                             for full details
25212 info:       "proc (body)"
25213 info:         is needed by its spec:
25214 info:       "proc (spec)"
25215 info:         which is withed by:
25216 info:       "pack (body)"
25217 info:  "pack (body)" must be elaborated before "proc (body)"
25218 info:     reason: pragma Elaborate in unit "proc (body)"
25219 @end group
25221 @end smallexample
25223 @noindent
25224 In this case we have a cycle that the binder cannot break. On the one
25225 hand, there is an explicit pragma Elaborate in @code{proc} for
25226 @code{pack}. This means that the body of @code{pack} must be elaborated
25227 before the body of @code{proc}. On the other hand, there is elaboration
25228 code in @code{pack} that calls a subprogram in @code{proc}. This means
25229 that for maximum safety, there should really be a pragma
25230 Elaborate_All in @code{pack} for @code{proc} which would require that
25231 the body of @code{proc} be elaborated before the body of
25232 @code{pack}. Clearly both requirements cannot be satisfied.
25233 Faced with a circularity of this kind, you have three different options.
25235 @table @asis
25236 @item Fix the program
25237 The most desirable option from the point of view of long-term maintenance
25238 is to rearrange the program so that the elaboration problems are avoided.
25239 One useful technique is to place the elaboration code into separate
25240 child packages. Another is to move some of the initialization code to
25241 explicitly called subprograms, where the program controls the order
25242 of initialization explicitly. Although this is the most desirable option,
25243 it may be impractical and involve too much modification, especially in
25244 the case of complex legacy code.
25246 @item Perform dynamic checks
25247 If the compilations are done using the
25248 @option{-gnatE}
25249 (dynamic elaboration check) switch, then GNAT behaves in a quite different
25250 manner. Dynamic checks are generated for all calls that could possibly result
25251 in raising an exception. With this switch, the compiler does not generate
25252 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
25253 exactly as specified in the @cite{Ada Reference Manual}.
25254 The binder will generate
25255 an executable program that may or may not raise @code{Program_Error}, and then
25256 it is the programmer's job to ensure that it does not raise an exception. Note
25257 that it is important to compile all units with the switch, it cannot be used
25258 selectively.
25260 @item Suppress checks
25261 The drawback of dynamic checks is that they generate a
25262 significant overhead at run time, both in space and time. If you
25263 are absolutely sure that your program cannot raise any elaboration
25264 exceptions, and you still want to use the dynamic elaboration model,
25265 then you can use the configuration pragma
25266 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
25267 example this pragma could be placed in the @file{gnat.adc} file.
25269 @item Suppress checks selectively
25270 When you know that certain calls or instantiations in elaboration code cannot
25271 possibly lead to an elaboration error, and the binder nevertheless complains
25272 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
25273 elaboration circularities, it is possible to remove those warnings locally and
25274 obtain a program that will bind. Clearly this can be unsafe, and it is the
25275 responsibility of the programmer to make sure that the resulting program has no
25276 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
25277 used with different granularity to suppress warnings and break elaboration
25278 circularities:
25280 @itemize @bullet
25281 @item
25282 Place the pragma that names the called subprogram in the declarative part
25283 that contains the call.
25285 @item
25286 Place the pragma in the declarative part, without naming an entity. This
25287 disables warnings on all calls in the corresponding  declarative region.
25289 @item
25290 Place the pragma in the package spec that declares the called subprogram,
25291 and name the subprogram. This disables warnings on all elaboration calls to
25292 that subprogram.
25294 @item
25295 Place the pragma in the package spec that declares the called subprogram,
25296 without naming any entity. This disables warnings on all elaboration calls to
25297 all subprograms declared in this spec.
25299 @item Use Pragma Elaborate
25300 As previously described in section @xref{Treatment of Pragma Elaborate},
25301 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
25302 that no elaboration checks are required on calls to the designated unit.
25303 There may be cases in which the caller knows that no transitive calls
25304 can occur, so that a @code{pragma Elaborate} will be sufficient in a
25305 case where @code{pragma Elaborate_All} would cause a circularity.
25306 @end itemize
25308 @noindent
25309 These five cases are listed in order of decreasing safety, and therefore
25310 require increasing programmer care in their application. Consider the
25311 following program:
25313 @smallexample @c adanocomment
25314 package Pack1 is
25315   function F1 return Integer;
25316   X1 : Integer;
25317 end Pack1;
25319 package Pack2 is
25320   function F2 return Integer;
25321   function Pure (x : integer) return integer;
25322   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
25323   --  pragma Suppress (Elaboration_Check);              -- (4)
25324 end Pack2;
25326 with Pack2;
25327 package body Pack1 is
25328   function F1 return Integer is
25329   begin
25330     return 100;
25331   end F1;
25332   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
25333 begin
25334   declare
25335     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
25336     --  pragma Suppress(Elaboration_Check);             -- (2)
25337   begin
25338     X1 := Pack2.F2 + 1;                --  Elab. call (2)
25339   end;
25340 end Pack1;
25342 with Pack1;
25343 package body Pack2 is
25344   function F2 return Integer is
25345   begin
25346      return Pack1.F1;
25347   end F2;
25348   function Pure (x : integer) return integer is
25349   begin
25350      return x ** 3 - 3 * x;
25351   end;
25352 end Pack2;
25354 with Pack1, Ada.Text_IO;
25355 procedure Proc3 is
25356 begin
25357   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25358 end Proc3;
25359 @end smallexample
25360 In the absence of any pragmas, an attempt to bind this program produces
25361 the following diagnostics:
25362 @smallexample
25363 @group
25364 @iftex
25365 @leftskip=.5cm
25366 @end iftex
25367 error: elaboration circularity detected
25368 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
25369 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
25370 info:       recompile "pack1 (body)" with -gnatwl for full details
25371 info:          "pack1 (body)"
25372 info:             must be elaborated along with its spec:
25373 info:          "pack1 (spec)"
25374 info:             which is withed by:
25375 info:          "pack2 (body)"
25376 info:             which must be elaborated along with its spec:
25377 info:          "pack2 (spec)"
25378 info:             which is withed by:
25379 info:          "pack1 (body)"
25380 @end group
25381 @end smallexample
25382 The sources of the circularity are the two calls to @code{Pack2.Pure} and
25383 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
25384 F2 is safe, even though F2 calls F1, because the call appears after the
25385 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
25386 remove the warning on the call. It is also possible to use pragma (2)
25387 because there are no other potentially unsafe calls in the block.
25389 @noindent
25390 The call to @code{Pure} is safe because this function does not depend on the
25391 state of @code{Pack2}. Therefore any call to this function is safe, and it
25392 is correct to place pragma (3) in the corresponding package spec.
25394 @noindent
25395 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
25396 warnings on all calls to functions declared therein. Note that this is not
25397 necessarily safe, and requires more detailed examination of the subprogram
25398 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
25399 be already elaborated.
25400 @end table
25402 @noindent
25403 It is hard to generalize on which of these four approaches should be
25404 taken. Obviously if it is possible to fix the program so that the default
25405 treatment works, this is preferable, but this may not always be practical.
25406 It is certainly simple enough to use
25407 @option{-gnatE}
25408 but the danger in this case is that, even if the GNAT binder
25409 finds a correct elaboration order, it may not always do so,
25410 and certainly a binder from another Ada compiler might not. A
25411 combination of testing and analysis (for which the warnings generated
25412 with the
25413 @option{-gnatwl}
25414 switch can be useful) must be used to ensure that the program is free
25415 of errors. One switch that is useful in this testing is the
25416 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
25417 switch for
25418 @code{gnatbind}.
25419 Normally the binder tries to find an order that has the best chance
25420 of avoiding elaboration problems. However, if this switch is used, the binder
25421 plays a devil's advocate role, and tries to choose the order that
25422 has the best chance of failing. If your program works even with this
25423 switch, then it has a better chance of being error free, but this is still
25424 not a guarantee.
25426 For an example of this approach in action, consider the C-tests (executable
25427 tests) from the ACVC suite. If these are compiled and run with the default
25428 treatment, then all but one of them succeed without generating any error
25429 diagnostics from the binder. However, there is one test that fails, and
25430 this is not surprising, because the whole point of this test is to ensure
25431 that the compiler can handle cases where it is impossible to determine
25432 a correct order statically, and it checks that an exception is indeed
25433 raised at run time.
25435 This one test must be compiled and run using the
25436 @option{-gnatE}
25437 switch, and then it passes. Alternatively, the entire suite can
25438 be run using this switch. It is never wrong to run with the dynamic
25439 elaboration switch if your code is correct, and we assume that the
25440 C-tests are indeed correct (it is less efficient, but efficiency is
25441 not a factor in running the ACVC tests.)
25443 @node Elaboration for Dispatching Calls
25444 @section Elaboration for Dispatching Calls
25445 @cindex Dispatching calls
25447 @noindent
25448 In rare cases, the static elaboration model fails to prevent
25449 dispatching calls to not-yet-elaborated subprograms. In such cases, we
25450 fall back to run-time checks; premature calls to any primitive
25451 operation of a tagged type before the body of the operation has been
25452 elaborated will raise @code{Program_Error}.
25454 Access-to-subprogram types, however, are handled conservatively, and
25455 do not require run-time checks. This was not true in earlier versions
25456 of the compiler; you can use the @option{-gnatd.U} debug switch to
25457 revert to the old behavior if the new conservative behavior causes
25458 elaboration cycles.
25460 @node Summary of Procedures for Elaboration Control
25461 @section Summary of Procedures for Elaboration Control
25462 @cindex Elaboration control
25464 @noindent
25465 First, compile your program with the default options, using none of
25466 the special elaboration control switches. If the binder successfully
25467 binds your program, then you can be confident that, apart from issues
25468 raised by the use of access-to-subprogram types and dynamic dispatching,
25469 the program is free of elaboration errors. If it is important that the
25470 program be portable, then use the
25471 @option{-gnatwl}
25472 switch to generate warnings about missing @code{Elaborate} or
25473 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25475 If the program fails to bind using the default static elaboration
25476 handling, then you can fix the program to eliminate the binder
25477 message, or recompile the entire program with the
25478 @option{-gnatE} switch to generate dynamic elaboration checks,
25479 and, if you are sure there really are no elaboration problems,
25480 use a global pragma @code{Suppress (Elaboration_Check)}.
25482 @node Other Elaboration Order Considerations
25483 @section Other Elaboration Order Considerations
25484 @noindent
25485 This section has been entirely concerned with the issue of finding a valid
25486 elaboration order, as defined by the Ada Reference Manual. In a case
25487 where several elaboration orders are valid, the task is to find one
25488 of the possible valid elaboration orders (and the static model in GNAT
25489 will ensure that this is achieved).
25491 The purpose of the elaboration rules in the Ada Reference Manual is to
25492 make sure that no entity is accessed before it has been elaborated. For
25493 a subprogram, this means that the spec and body must have been elaborated
25494 before the subprogram is called. For an object, this means that the object
25495 must have been elaborated before its value is read or written. A violation
25496 of either of these two requirements is an access before elaboration order,
25497 and this section has been all about avoiding such errors.
25499 In the case where more than one order of elaboration is possible, in the
25500 sense that access before elaboration errors are avoided, then any one of
25501 the orders is ``correct'' in the sense that it meets the requirements of
25502 the Ada Reference Manual, and no such error occurs.
25504 However, it may be the case for a given program, that there are
25505 constraints on the order of elaboration that come not from consideration
25506 of avoiding elaboration errors, but rather from extra-lingual logic
25507 requirements. Consider this example:
25509 @smallexample @c ada
25510 with Init_Constants;
25511 package Constants is
25512    X : Integer := 0;
25513    Y : Integer := 0;
25514 end Constants;
25516 package Init_Constants is
25517    procedure P; -- require a body
25518 end Init_Constants;
25520 with Constants;
25521 package body Init_Constants is
25522    procedure P is begin null; end;
25523 begin
25524    Constants.X := 3;
25525    Constants.Y := 4;
25526 end Init_Constants;
25528 with Constants;
25529 package Calc is
25530    Z : Integer := Constants.X + Constants.Y;
25531 end Calc;
25533 with Calc;
25534 with Text_IO; use Text_IO;
25535 procedure Main is
25536 begin
25537    Put_Line (Calc.Z'Img);
25538 end Main;
25539 @end smallexample
25541 @noindent
25542 In this example, there is more than one valid order of elaboration. For
25543 example both the following are correct orders:
25545 @smallexample
25546 Init_Constants spec
25547 Constants spec
25548 Calc spec
25549 Init_Constants body
25550 Main body
25552   and
25554 Init_Constants spec
25555 Init_Constants body
25556 Constants spec
25557 Calc spec
25558 Main body
25559 @end smallexample
25561 @noindent
25562 There is no language rule to prefer one or the other, both are correct
25563 from an order of elaboration point of view. But the programmatic effects
25564 of the two orders are very different. In the first, the elaboration routine
25565 of @code{Calc} initializes @code{Z} to zero, and then the main program
25566 runs with this value of zero. But in the second order, the elaboration
25567 routine of @code{Calc} runs after the body of Init_Constants has set
25568 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25569 runs.
25571 One could perhaps by applying pretty clever non-artificial intelligence
25572 to the situation guess that it is more likely that the second order of
25573 elaboration is the one desired, but there is no formal linguistic reason
25574 to prefer one over the other. In fact in this particular case, GNAT will
25575 prefer the second order, because of the rule that bodies are elaborated
25576 as soon as possible, but it's just luck that this is what was wanted
25577 (if indeed the second order was preferred).
25579 If the program cares about the order of elaboration routines in a case like
25580 this, it is important to specify the order required. In this particular
25581 case, that could have been achieved by adding to the spec of Calc:
25583 @smallexample @c ada
25584 pragma Elaborate_All (Constants);
25585 @end smallexample
25587 @noindent
25588 which requires that the body (if any) and spec of @code{Constants},
25589 as well as the body and spec of any unit @code{with}'ed by
25590 @code{Constants} be elaborated before @code{Calc} is elaborated.
25592 Clearly no automatic method can always guess which alternative you require,
25593 and if you are working with legacy code that had constraints of this kind
25594 which were not properly specified by adding @code{Elaborate} or
25595 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25596 compilers can choose different orders.
25598 However, GNAT does attempt to diagnose the common situation where there
25599 are uninitialized variables in the visible part of a package spec, and the
25600 corresponding package body has an elaboration block that directly or
25601 indirectly initialized one or more of these variables. This is the situation
25602 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25603 a warning that suggests this addition if it detects this situation.
25605 The @code{gnatbind}
25606 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25607 out problems. This switch causes bodies to be elaborated as late as possible
25608 instead of as early as possible. In the example above, it would have forced
25609 the choice of the first elaboration order. If you get different results
25610 when using this switch, and particularly if one set of results is right,
25611 and one is wrong as far as you are concerned, it shows that you have some
25612 missing @code{Elaborate} pragmas. For the example above, we have the
25613 following output:
25615 @smallexample
25616 gnatmake -f -q main
25617 main
25619 gnatmake -f -q main -bargs -p
25620 main
25622 @end smallexample
25624 @noindent
25625 It is of course quite unlikely that both these results are correct, so
25626 it is up to you in a case like this to investigate the source of the
25627 difference, by looking at the two elaboration orders that are chosen,
25628 and figuring out which is correct, and then adding the necessary
25629 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25632 @c **********************************
25633 @node Overflow Check Handling in GNAT
25634 @appendix Overflow Check Handling in GNAT
25635 @cindex Overflow checks
25636 @cindex Checks (overflow)
25637 @c **********************************
25639 @menu
25640 * Background::
25641 * Overflow Checking Modes in GNAT::
25642 * Specifying the Desired Mode::
25643 * Default Settings::
25644 * Implementation Notes::
25645 @end menu
25648 @node Background
25649 @section Background
25651 @noindent
25652 Overflow checks are checks that the compiler may make to ensure
25653 that intermediate results are not out of range. For example:
25655 @smallexample @c ada
25656    A : Integer;
25657    ...
25658    A := A + 1;
25659 @end smallexample
25661 @noindent
25662 if @code{A} has the value @code{Integer'Last}, then the addition may cause
25663 overflow since the result is out of range of the type @code{Integer}.
25664 In this case @code{Constraint_Error} will be raised if checks are
25665 enabled.
25667 A trickier situation arises in examples like the following:
25669 @smallexample @c ada
25670   A, C : Integer;
25671   ...
25672   A := (A + 1) + C;
25673 @end smallexample
25675 @noindent
25676 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
25677 Now the final result of the expression on the right hand side is
25678 @code{Integer'Last} which is in range, but the question arises whether the
25679 intermediate addition of @code{(A + 1)} raises an overflow error.
25681 The (perhaps surprising) answer is that the Ada language
25682 definition does not answer this question. Instead it leaves
25683 it up to the implementation to do one of two things if overflow
25684 checks are enabled.
25686 @itemize @bullet
25687 @item
25688 raise an exception (@code{Constraint_Error}), or
25690 @item
25691 yield the correct mathematical result which is then used in
25692 subsequent operations.
25693 @end itemize
25695 @noindent
25696 If the compiler chooses the first approach, then the assignment of this
25697 example will indeed raise @code{Constraint_Error} if overflow checking is
25698 enabled, or result in erroneous execution if overflow checks are suppressed.
25700 But if the compiler
25701 chooses the second approach, then it can perform both additions yielding
25702 the correct mathematical result, which is in range, so no exception
25703 will be raised, and the right result is obtained, regardless of whether
25704 overflow checks are suppressed.
25706 Note that in the first example an
25707 exception will be raised in either case, since if the compiler
25708 gives the correct mathematical result for the addition, it will
25709 be out of range of the target type of the assignment, and thus
25710 fails the range check.
25712 This lack of specified behavior in the handling of overflow for
25713 intermediate results is a source of non-portability, and can thus
25714 be problematic when programs are ported. Most typically this arises
25715 in a situation where the original compiler did not raise an exception,
25716 and then the application is moved to a compiler where the check is
25717 performed on the intermediate result and an unexpected exception is
25718 raised.
25720 Furthermore, when using Ada 2012's preconditions and other
25721 assertion forms, another issue arises. Consider:
25723 @smallexample @c ada
25724      procedure P (A, B : Integer) with
25725        Pre => A + B <= Integer'Last;
25726 @end smallexample
25728 @noindent
25729 One often wants to regard arithmetic in a context like this from
25730 a mathematical point of view. So for example, if the two actual parameters
25731 for a call to @code{P} are both @code{Integer'Last}, then
25732 the precondition should be regarded as False. If we are executing
25733 in a mode with run-time checks enabled for preconditions, then we would
25734 like this precondition to fail, rather than raising an exception
25735 because of the intermediate overflow.
25737 However, the language definition leaves the specification of
25738 whether the above condition fails (raising @code{Assert_Error}) or
25739 causes an intermediate overflow (raising @code{Constraint_Error})
25740 up to the implementation.
25742 The situation is worse in a case such as the following:
25744 @smallexample @c ada
25745      procedure Q (A, B, C : Integer) with
25746        Pre => A + B + C <= Integer'Last;
25747 @end smallexample
25749 @noindent
25750 Consider the call
25752 @smallexample @c ada
25753      Q (A => Integer'Last, B => 1, C => -1);
25754 @end smallexample
25756 @noindent
25757 From a mathematical point of view the precondition
25758 is True, but at run time we may (but are not guaranteed to) get an
25759 exception raised because of the intermediate overflow (and we really
25760 would prefer this precondition to be considered True at run time).
25762 @node Overflow Checking Modes in GNAT
25763 @section Overflow Checking Modes in GNAT
25765 @noindent
25766 To deal with the portability issue, and with the problem of
25767 mathematical versus run-time intepretation of the expressions in
25768 assertions, GNAT provides comprehensive control over the handling
25769 of intermediate overflow. GNAT can operate in three modes, and
25770 furthemore, permits separate selection of operating modes for
25771 the expressions within assertions (here the term ``assertions''
25772 is used in the technical sense, which includes preconditions and so forth)
25773 and for expressions appearing outside assertions.
25775 The three modes are:
25777 @itemize @bullet
25778 @item   @i{Use base type for intermediate operations} (@code{STRICT})
25780      In this mode, all intermediate results for predefined arithmetic
25781      operators are computed using the base type, and the result must
25782      be in range of the base type. If this is not the
25783      case then either an exception is raised (if overflow checks are
25784      enabled) or the execution is erroneous (if overflow checks are suppressed).
25785      This is the normal default mode.
25787 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
25789      In this mode, the compiler attempts to avoid intermediate overflows by
25790      using a larger integer type, typically @code{Long_Long_Integer},
25791      as the type in which arithmetic is
25792      performed for predefined arithmetic operators. This may be slightly more
25793      expensive at
25794      run time (compared to suppressing intermediate overflow checks), though
25795      the cost is negligible on modern 64-bit machines. For the examples given
25796      earlier, no intermediate overflows would have resulted in exceptions,
25797      since the intermediate results are all in the range of
25798      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
25799      of GNAT). In addition, if checks are enabled, this reduces the number of
25800      checks that must be made, so this choice may actually result in an
25801      improvement in space and time behavior.
25803      However, there are cases where @code{Long_Long_Integer} is not large
25804      enough, consider the following example:
25806 @smallexample @c ada
25807        procedure R (A, B, C, D : Integer) with
25808          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
25809 @end smallexample
25811      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25812      Now the intermediate results are
25813      out of the range of @code{Long_Long_Integer} even though the final result
25814      is in range and the precondition is True (from a mathematical point
25815      of view). In such a case, operating in this mode, an overflow occurs
25816      for the intermediate computation (which is why this mode
25817      says @i{most} intermediate overflows are avoided). In this case,
25818      an exception is raised if overflow checks are enabled, and the
25819      execution is erroneous if overflow checks are suppressed.
25821 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
25823      In this mode, the compiler  avoids all intermediate overflows
25824      by using arbitrary precision arithmetic as required. In this
25825      mode, the above example with @code{A**2 * B**2} would
25826      not cause intermediate overflow, because the intermediate result
25827      would be evaluated using sufficient precision, and the result
25828      of evaluating the precondition would be True.
25830      This mode has the advantage of avoiding any intermediate
25831      overflows, but at the expense of significant run-time overhead,
25832      including the use of a library (included automatically in this
25833      mode) for multiple-precision arithmetic.
25835      This mode provides cleaner semantics for assertions, since now
25836      the run-time behavior emulates true arithmetic behavior for the
25837      predefined arithmetic operators, meaning that there is never a
25838      conflict between the mathematical view of the assertion, and its
25839      run-time behavior.
25841      Note that in this mode, the behavior is unaffected by whether or
25842      not overflow checks are suppressed, since overflow does not occur.
25843      It is possible for gigantic intermediate expressions to raise
25844      @code{Storage_Error} as a result of attempting to compute the
25845      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
25846      but overflow is impossible.
25849 @end itemize
25851 @noindent
25852   Note that these modes apply only to the evaluation of predefined
25853   arithmetic, membership, and comparison operators for signed integer
25854   aritmetic.
25856   For fixed-point arithmetic, checks can be suppressed. But if checks
25857   are enabled
25858   then fixed-point values are always checked for overflow against the
25859   base type for intermediate expressions (that is such checks always
25860   operate in the equivalent of @code{STRICT} mode).
25862   For floating-point, on nearly all architectures, @code{Machine_Overflows}
25863   is False, and IEEE infinities are generated, so overflow exceptions
25864   are never raised. If you want to avoid infinities, and check that
25865   final results of expressions are in range, then you can declare a
25866   constrained floating-point type, and range checks will be carried
25867   out in the normal manner (with infinite values always failing all
25868   range checks).
25871 @c -------------------------
25872 @node Specifying the Desired Mode
25873 @section Specifying the Desired Mode
25875 @noindent
25876 The desired mode of for handling intermediate overflow can be specified using
25877 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
25878 The pragma has the form
25879 @cindex pragma @code{Overflow_Mode}
25881 @smallexample @c ada
25882     pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
25883 @end smallexample
25885 @noindent
25886 where @code{MODE} is one of
25888 @itemize @bullet
25889 @item   @code{STRICT}:  intermediate overflows checked (using base type)
25890 @item   @code{MINIMIZED}: minimize intermediate overflows
25891 @item   @code{ELIMINATED}: eliminate intermediate overflows
25892 @end itemize
25894 @noindent
25895 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25896 @code{minimized} all have the same effect.
25898 If only the @code{General} parameter is present, then the given @code{MODE}
25899 applies
25900 to expressions both within and outside assertions. If both arguments
25901 are present, then @code{General} applies to expressions outside assertions,
25902 and @code{Assertions} applies to expressions within assertions. For example:
25904 @smallexample @c ada
25905    pragma Overflow_Mode
25906      (General => Minimized, Assertions => Eliminated);
25907 @end smallexample
25909 @noindent
25910 specifies that general expressions outside assertions be evaluated
25911 in ``minimize intermediate overflows'' mode, and expressions within
25912 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25913 This is often a reasonable choice, avoiding excessive overhead
25914 outside assertions, but assuring a high degree of portability
25915 when importing code from another compiler, while incurring
25916 the extra overhead for assertion expressions to ensure that
25917 the behavior at run time matches the expected mathematical
25918 behavior.
25920 The @code{Overflow_Mode} pragma has the same scoping and placement
25921 rules as pragma @code{Suppress}, so it can occur either as a
25922 configuration pragma, specifying a default for the whole
25923 program, or in a declarative scope, where it applies to the
25924 remaining declarations and statements in that scope.
25926 Note that pragma @code{Overflow_Mode} does not affect whether
25927 overflow checks are enabled or suppressed. It only controls the
25928 method used to compute intermediate values. To control whether
25929 overflow checking is enabled or suppressed, use pragma @code{Suppress}
25930 or @code{Unsuppress} in the usual manner
25932 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25933 can be used to control the checking mode default (which can be subsequently
25934 overridden using pragmas).
25935 @cindex @option{-gnato?} (gcc)
25936 @cindex @option{-gnato??} (gcc)
25938 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
25940 @itemize @bullet
25941 @item   @code{1}:
25942 use base type for intermediate operations (@code{STRICT})
25943 @item   @code{2}:
25944 minimize intermediate overflows (@code{MINIMIZED})
25945 @item   @code{3}:
25946 eliminate intermediate overflows (@code{ELIMINATED})
25947 @end itemize
25949 @noindent
25950 As with the pragma, if only one digit appears then it applies to all
25951 cases; if two digits are given, then the first applies outside
25952 assertions, and the second within assertions. Thus the equivalent
25953 of the example pragma above would be @option{-gnato23}.
25955 If no digits follow the @option{-gnato}, then it is equivalent to
25956 @option{-gnato11},
25957 causing all intermediate operations to be computed using the base
25958 type (@code{STRICT} mode).
25960 In addition to setting the mode used for computation of intermediate
25961 results, the @code{-gnato} switch also enables overflow checking (which
25962 is suppressed by default). It thus combines the effect of using
25963 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
25966 @c -------------------------
25967 @node Default Settings
25968 @section Default Settings
25970 The default mode for overflow checks is
25972 @smallexample
25973    General => Strict
25974 @end smallexample
25976 @noindent
25977 which causes all computations both inside and outside assertions to use
25978 the base type. In addition overflow checks are suppressed.
25980 This retains compatibility with previous versions of
25981 GNAT which suppressed overflow checks by default and always
25982 used the base type for computation of intermediate results.
25984 The switch @option{-gnato} (with no digits following) is equivalent to
25985 @cindex @option{-gnato} (gcc)
25987 @smallexample
25988    General => Strict
25989 @end smallexample
25991 @noindent
25992 which causes overflow checking of all intermediate overflows
25993 both inside and outside assertions against the base type.
25994 This provides compatibility
25995 with this switch as implemented in previous versions of GNAT.
25997 The pragma @code{Suppress (Overflow_Check)} disables overflow
25998 checking, but it has no effect on the method used for computing
25999 intermediate results.
26001 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
26002 checking, but it has no effect on the method used for computing
26003 intermediate results.
26005 @c -------------------------
26006 @node Implementation Notes
26007 @section Implementation Notes
26009 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
26010 reasonably efficient, and can be generally used. It also helps
26011 to ensure compatibility with code imported from some other
26012 compiler to GNAT.
26014 Setting all intermediate overflows checking (@code{CHECKED} mode)
26015 makes sense if you want to
26016 make sure that your code is compatible with any other possible
26017 Ada implementation. This may be useful in ensuring portability
26018 for code that is to be exported to some other compiler than GNAT.
26021 The Ada standard allows the reassociation of expressions at
26022 the same precedence level if no parentheses are present. For
26023 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
26024 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
26025 introducing or eliminating an overflow exception. The GNAT
26026 compiler never takes advantage of this freedom, and the
26027 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
26028 If you need the other order, you can write the parentheses
26029 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
26031 The use of @code{ELIMINATED} mode will cause the compiler to
26032 automatically include an appropriate arbitrary precision
26033 integer arithmetic package. The compiler will make calls
26034 to this package, though only in cases where it cannot be
26035 sure that @code{Long_Long_Integer} is sufficient to guard against
26036 intermediate overflows. This package does not use dynamic
26037 alllocation, but it does use the secondary stack, so an
26038 appropriate secondary stack package must be present (this
26039 is always true for standard full Ada, but may require
26040 specific steps for restricted run times such as ZFP).
26042 Although @code{ELIMINATED} mode causes expressions to use arbitrary
26043 precision arithmetic, avoiding overflow, the final result
26044 must be in an appropriate range. This is true even if the
26045 final result is of type @code{[Long_[Long_]]Integer'Base}, which
26046 still has the same bounds as its associated constrained
26047 type at run-time.
26049 Currently, the @code{ELIMINATED} mode is only available on target
26050 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
26051 platforms).
26053 @c *******************************
26054 @node Conditional Compilation
26055 @appendix Conditional Compilation
26056 @c *******************************
26057 @cindex Conditional compilation
26059 @noindent
26060 It is often necessary to arrange for a single source program
26061 to serve multiple purposes, where it is compiled in different
26062 ways to achieve these different goals. Some examples of the
26063 need for this feature are
26065 @itemize @bullet
26066 @item  Adapting a program to a different hardware environment
26067 @item  Adapting a program to a different target architecture
26068 @item  Turning debugging features on and off
26069 @item  Arranging for a program to compile with different compilers
26070 @end itemize
26072 @noindent
26073 In C, or C++, the typical approach would be to use the preprocessor
26074 that is defined as part of the language. The Ada language does not
26075 contain such a feature. This is not an oversight, but rather a very
26076 deliberate design decision, based on the experience that overuse of
26077 the preprocessing features in C and C++ can result in programs that
26078 are extremely difficult to maintain. For example, if we have ten
26079 switches that can be on or off, this means that there are a thousand
26080 separate programs, any one of which might not even be syntactically
26081 correct, and even if syntactically correct, the resulting program
26082 might not work correctly. Testing all combinations can quickly become
26083 impossible.
26085 Nevertheless, the need to tailor programs certainly exists, and in
26086 this Appendix we will discuss how this can
26087 be achieved using Ada in general, and GNAT in particular.
26089 @menu
26090 * Use of Boolean Constants::
26091 * Debugging - A Special Case::
26092 * Conditionalizing Declarations::
26093 * Use of Alternative Implementations::
26094 * Preprocessing::
26095 @end menu
26097 @node Use of Boolean Constants
26098 @section Use of Boolean Constants
26100 @noindent
26101 In the case where the difference is simply which code
26102 sequence is executed, the cleanest solution is to use Boolean
26103 constants to control which code is executed.
26105 @smallexample @c ada
26106 @group
26107 FP_Initialize_Required : constant Boolean := True;
26108 @dots{}
26109 if FP_Initialize_Required then
26110 @dots{}
26111 end if;
26112 @end group
26113 @end smallexample
26115 @noindent
26116 Not only will the code inside the @code{if} statement not be executed if
26117 the constant Boolean is @code{False}, but it will also be completely
26118 deleted from the program.
26119 However, the code is only deleted after the @code{if} statement
26120 has been checked for syntactic and semantic correctness.
26121 (In contrast, with preprocessors the code is deleted before the
26122 compiler ever gets to see it, so it is not checked until the switch
26123 is turned on.)
26124 @cindex Preprocessors (contrasted with conditional compilation)
26126 Typically the Boolean constants will be in a separate package,
26127 something like:
26129 @smallexample @c ada
26130 @group
26131 package Config is
26132    FP_Initialize_Required : constant Boolean := True;
26133    Reset_Available        : constant Boolean := False;
26134    @dots{}
26135 end Config;
26136 @end group
26137 @end smallexample
26139 @noindent
26140 The @code{Config} package exists in multiple forms for the various targets,
26141 with an appropriate script selecting the version of @code{Config} needed.
26142 Then any other unit requiring conditional compilation can do a @code{with}
26143 of @code{Config} to make the constants visible.
26146 @node Debugging - A Special Case
26147 @section Debugging - A Special Case
26149 @noindent
26150 A common use of conditional code is to execute statements (for example
26151 dynamic checks, or output of intermediate results) under control of a
26152 debug switch, so that the debugging behavior can be turned on and off.
26153 This can be done using a Boolean constant to control whether the code
26154 is active:
26156 @smallexample @c ada
26157 @group
26158 if Debugging then
26159    Put_Line ("got to the first stage!");
26160 end if;
26161 @end group
26162 @end smallexample
26164 @noindent
26167 @smallexample @c ada
26168 @group
26169 if Debugging and then Temperature > 999.0 then
26170    raise Temperature_Crazy;
26171 end if;
26172 @end group
26173 @end smallexample
26175 @noindent
26176 Since this is a common case, there are special features to deal with
26177 this in a convenient manner. For the case of tests, Ada 2005 has added
26178 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
26179 @cindex pragma @code{Assert}
26180 on the @code{Assert} pragma that has always been available in GNAT, so this
26181 feature may be used with GNAT even if you are not using Ada 2005 features.
26182 The use of pragma @code{Assert} is described in
26183 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
26184 example, the last test could be written:
26186 @smallexample @c ada
26187 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
26188 @end smallexample
26190 @noindent
26191 or simply
26193 @smallexample @c ada
26194 pragma Assert (Temperature <= 999.0);
26195 @end smallexample
26197 @noindent
26198 In both cases, if assertions are active and the temperature is excessive,
26199 the exception @code{Assert_Failure} will be raised, with the given string in
26200 the first case or a string indicating the location of the pragma in the second
26201 case used as the exception message.
26203 You can turn assertions on and off by using the @code{Assertion_Policy}
26204 pragma.
26205 @cindex pragma @code{Assertion_Policy}
26206 This is an Ada 2005 pragma which is implemented in all modes by
26207 GNAT, but only in the latest versions of GNAT which include Ada 2005
26208 capability. Alternatively, you can use the @option{-gnata} switch
26209 @cindex @option{-gnata} switch
26210 to enable assertions from the command line (this is recognized by all versions
26211 of GNAT).
26213 For the example above with the @code{Put_Line}, the GNAT-specific pragma
26214 @code{Debug} can be used:
26215 @cindex pragma @code{Debug}
26217 @smallexample @c ada
26218 pragma Debug (Put_Line ("got to the first stage!"));
26219 @end smallexample
26221 @noindent
26222 If debug pragmas are enabled, the argument, which must be of the form of
26223 a procedure call, is executed (in this case, @code{Put_Line} will be called).
26224 Only one call can be present, but of course a special debugging procedure
26225 containing any code you like can be included in the program and then
26226 called in a pragma @code{Debug} argument as needed.
26228 One advantage of pragma @code{Debug} over the @code{if Debugging then}
26229 construct is that pragma @code{Debug} can appear in declarative contexts,
26230 such as at the very beginning of a procedure, before local declarations have
26231 been elaborated.
26233 Debug pragmas are enabled using either the @option{-gnata} switch that also
26234 controls assertions, or with a separate Debug_Policy pragma.
26235 @cindex pragma @code{Debug_Policy}
26236 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
26237 in Ada 95 and Ada 83 programs as well), and is analogous to
26238 pragma @code{Assertion_Policy} to control assertions.
26240 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
26241 and thus they can appear in @file{gnat.adc} if you are not using a
26242 project file, or in the file designated to contain configuration pragmas
26243 in a project file.
26244 They then apply to all subsequent compilations. In practice the use of
26245 the @option{-gnata} switch is often the most convenient method of controlling
26246 the status of these pragmas.
26248 Note that a pragma is not a statement, so in contexts where a statement
26249 sequence is required, you can't just write a pragma on its own. You have
26250 to add a @code{null} statement.
26252 @smallexample @c ada
26253 @group
26254 if @dots{} then
26255    @dots{} -- some statements
26256 else
26257    pragma Assert (Num_Cases < 10);
26258    null;
26259 end if;
26260 @end group
26261 @end smallexample
26264 @node Conditionalizing Declarations
26265 @section Conditionalizing Declarations
26267 @noindent
26268 In some cases, it may be necessary to conditionalize declarations to meet
26269 different requirements. For example we might want a bit string whose length
26270 is set to meet some hardware message requirement.
26272 In some cases, it may be possible to do this using declare blocks controlled
26273 by conditional constants:
26275 @smallexample @c ada
26276 @group
26277 if Small_Machine then
26278    declare
26279       X : Bit_String (1 .. 10);
26280    begin
26281       @dots{}
26282    end;
26283 else
26284    declare
26285       X : Large_Bit_String (1 .. 1000);
26286    begin
26287       @dots{}
26288    end;
26289 end if;
26290 @end group
26291 @end smallexample
26293 @noindent
26294 Note that in this approach, both declarations are analyzed by the
26295 compiler so this can only be used where both declarations are legal,
26296 even though one of them will not be used.
26298 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
26299 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
26300 that are parameterized by these constants. For example
26302 @smallexample @c ada
26303 @group
26304 for Rec use
26305   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
26306 end record;
26307 @end group
26308 @end smallexample
26310 @noindent
26311 If @code{Bits_Per_Word} is set to 32, this generates either
26313 @smallexample @c ada
26314 @group
26315 for Rec use
26316   Field1 at 0 range 0 .. 32;
26317 end record;
26318 @end group
26319 @end smallexample
26321 @noindent
26322 for the big endian case, or
26324 @smallexample @c ada
26325 @group
26326 for Rec use record
26327   Field1 at 0 range 10 .. 32;
26328 end record;
26329 @end group
26330 @end smallexample
26332 @noindent
26333 for the little endian case. Since a powerful subset of Ada expression
26334 notation is usable for creating static constants, clever use of this
26335 feature can often solve quite difficult problems in conditionalizing
26336 compilation (note incidentally that in Ada 95, the little endian
26337 constant was introduced as @code{System.Default_Bit_Order}, so you do not
26338 need to define this one yourself).
26341 @node Use of Alternative Implementations
26342 @section Use of Alternative Implementations
26344 @noindent
26345 In some cases, none of the approaches described above are adequate. This
26346 can occur for example if the set of declarations required is radically
26347 different for two different configurations.
26349 In this situation, the official Ada way of dealing with conditionalizing
26350 such code is to write separate units for the different cases. As long as
26351 this does not result in excessive duplication of code, this can be done
26352 without creating maintenance problems. The approach is to share common
26353 code as far as possible, and then isolate the code and declarations
26354 that are different. Subunits are often a convenient method for breaking
26355 out a piece of a unit that is to be conditionalized, with separate files
26356 for different versions of the subunit for different targets, where the
26357 build script selects the right one to give to the compiler.
26358 @cindex Subunits (and conditional compilation)
26360 As an example, consider a situation where a new feature in Ada 2005
26361 allows something to be done in a really nice way. But your code must be able
26362 to compile with an Ada 95 compiler. Conceptually you want to say:
26364 @smallexample @c ada
26365 @group
26366 if Ada_2005 then
26367    @dots{} neat Ada 2005 code
26368 else
26369    @dots{} not quite as neat Ada 95 code
26370 end if;
26371 @end group
26372 @end smallexample
26374 @noindent
26375 where @code{Ada_2005} is a Boolean constant.
26377 But this won't work when @code{Ada_2005} is set to @code{False},
26378 since the @code{then} clause will be illegal for an Ada 95 compiler.
26379 (Recall that although such unreachable code would eventually be deleted
26380 by the compiler, it still needs to be legal.  If it uses features
26381 introduced in Ada 2005, it will be illegal in Ada 95.)
26383 So instead we write
26385 @smallexample @c ada
26386 procedure Insert is separate;
26387 @end smallexample
26389 @noindent
26390 Then we have two files for the subunit @code{Insert}, with the two sets of
26391 code.
26392 If the package containing this is called @code{File_Queries}, then we might
26393 have two files
26395 @itemize @bullet
26396 @item    @file{file_queries-insert-2005.adb}
26397 @item    @file{file_queries-insert-95.adb}
26398 @end itemize
26400 @noindent
26401 and the build script renames the appropriate file to
26403 @smallexample
26404 file_queries-insert.adb
26405 @end smallexample
26407 @noindent
26408 and then carries out the compilation.
26410 This can also be done with project files' naming schemes. For example:
26412 @smallexample @c project
26413 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
26414 @end smallexample
26416 @noindent
26417 Note also that with project files it is desirable to use a different extension
26418 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
26419 conflict may arise through another commonly used feature: to declare as part
26420 of the project a set of directories containing all the sources obeying the
26421 default naming scheme.
26423 The use of alternative units is certainly feasible in all situations,
26424 and for example the Ada part of the GNAT run-time is conditionalized
26425 based on the target architecture using this approach. As a specific example,
26426 consider the implementation of the AST feature in VMS. There is one
26427 spec:
26429 @smallexample
26430 s-asthan.ads
26431 @end smallexample
26433 @noindent
26434 which is the same for all architectures, and three bodies:
26436 @table @file
26437 @item    s-asthan.adb
26438 used for all non-VMS operating systems
26439 @item    s-asthan-vms-alpha.adb
26440 used for VMS on the Alpha
26441 @item    s-asthan-vms-ia64.adb
26442 used for VMS on the ia64
26443 @end table
26445 @noindent
26446 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
26447 this operating system feature is not available, and the two remaining
26448 versions interface with the corresponding versions of VMS to provide
26449 VMS-compatible AST handling. The GNAT build script knows the architecture
26450 and operating system, and automatically selects the right version,
26451 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
26453 Another style for arranging alternative implementations is through Ada's
26454 access-to-subprogram facility.
26455 In case some functionality is to be conditionally included,
26456 you can declare an access-to-procedure variable @code{Ref} that is initialized
26457 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
26458 when appropriate.
26459 In some library package, set @code{Ref} to @code{Proc'Access} for some
26460 procedure @code{Proc} that performs the relevant processing.
26461 The initialization only occurs if the library package is included in the
26462 program.
26463 The same idea can also be implemented using tagged types and dispatching
26464 calls.
26467 @node Preprocessing
26468 @section Preprocessing
26469 @cindex Preprocessing
26471 @noindent
26472 Although it is quite possible to conditionalize code without the use of
26473 C-style preprocessing, as described earlier in this section, it is
26474 nevertheless convenient in some cases to use the C approach. Moreover,
26475 older Ada compilers have often provided some preprocessing capability,
26476 so legacy code may depend on this approach, even though it is not
26477 standard.
26479 To accommodate such use, GNAT provides a preprocessor (modeled to a large
26480 extent on the various preprocessors that have been used
26481 with legacy code on other compilers, to enable easier transition).
26483 The preprocessor may be used in two separate modes. It can be used quite
26484 separately from the compiler, to generate a separate output source file
26485 that is then fed to the compiler as a separate step. This is the
26486 @code{gnatprep} utility, whose use is fully described in
26487 @ref{Preprocessing Using gnatprep}.
26488 @cindex @code{gnatprep}
26490 The preprocessing language allows such constructs as
26492 @smallexample
26493 @group
26494 #if DEBUG or PRIORITY > 4 then
26495    bunch of declarations
26496 #else
26497    completely different bunch of declarations
26498 #end if;
26499 @end group
26500 @end smallexample
26502 @noindent
26503 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
26504 defined either on the command line or in a separate file.
26506 The other way of running the preprocessor is even closer to the C style and
26507 often more convenient. In this approach the preprocessing is integrated into
26508 the compilation process. The compiler is fed the preprocessor input which
26509 includes @code{#if} lines etc, and then the compiler carries out the
26510 preprocessing internally and processes the resulting output.
26511 For more details on this approach, see @ref{Integrated Preprocessing}.
26514 @c *******************************
26515 @node Inline Assembler
26516 @appendix Inline Assembler
26517 @c *******************************
26519 @noindent
26520 If you need to write low-level software that interacts directly
26521 with the hardware, Ada provides two ways to incorporate assembly
26522 language code into your program.  First, you can import and invoke
26523 external routines written in assembly language, an Ada feature fully
26524 supported by GNAT@.  However, for small sections of code it may be simpler
26525 or more efficient to include assembly language statements directly
26526 in your Ada source program, using the facilities of the implementation-defined
26527 package @code{System.Machine_Code}, which incorporates the gcc
26528 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
26529 including the following:
26531 @itemize @bullet
26532 @item No need to use non-Ada tools
26533 @item Consistent interface over different targets
26534 @item Automatic usage of the proper calling conventions
26535 @item Access to Ada constants and variables
26536 @item Definition of intrinsic routines
26537 @item Possibility of inlining a subprogram comprising assembler code
26538 @item Code optimizer can take Inline Assembler code into account
26539 @end itemize
26541 This chapter presents a series of examples to show you how to use
26542 the Inline Assembler.  Although it focuses on the Intel x86,
26543 the general approach applies also to other processors.
26544 It is assumed that you are familiar with Ada
26545 and with assembly language programming.
26547 @menu
26548 * Basic Assembler Syntax::
26549 * A Simple Example of Inline Assembler::
26550 * Output Variables in Inline Assembler::
26551 * Input Variables in Inline Assembler::
26552 * Inlining Inline Assembler Code::
26553 * Other Asm Functionality::
26554 @end menu
26556 @c ---------------------------------------------------------------------------
26557 @node Basic Assembler Syntax
26558 @section Basic Assembler Syntax
26560 @noindent
26561 The assembler used by GNAT and gcc is based not on the Intel assembly
26562 language, but rather on a language that descends from the AT&T Unix
26563 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
26564 The following table summarizes the main features of @emph{as} syntax
26565 and points out the differences from the Intel conventions.
26566 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
26567 pre-processor) documentation for further information.
26569 @table @asis
26570 @item Register names
26571 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
26573 Intel: No extra punctuation; for example @code{eax}
26575 @item Immediate operand
26576 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
26578 Intel: No extra punctuation; for example @code{4}
26580 @item Address
26581 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
26583 Intel: No extra punctuation; for example @code{loc}
26585 @item Memory contents
26586 gcc / @emph{as}: No extra punctuation; for example @code{loc}
26588 Intel: Square brackets; for example @code{[loc]}
26590 @item Register contents
26591 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
26593 Intel: Square brackets; for example @code{[eax]}
26595 @item Hexadecimal numbers
26596 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
26598 Intel: Trailing ``h''; for example @code{A0h}
26600 @item Operand size
26601 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
26602 a 16-bit word
26604 Intel: Implicit, deduced by assembler; for example @code{mov}
26606 @item Instruction repetition
26607 gcc / @emph{as}: Split into two lines; for example
26609 @code{rep}
26611 @code{stosl}
26613 Intel: Keep on one line; for example @code{rep stosl}
26615 @item Order of operands
26616 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
26618 Intel: Destination first; for example @code{mov eax, 4}
26619 @end table
26621 @c ---------------------------------------------------------------------------
26622 @node A Simple Example of Inline Assembler
26623 @section A Simple Example of Inline Assembler
26625 @noindent
26626 The following example will generate a single assembly language statement,
26627 @code{nop}, which does nothing.  Despite its lack of run-time effect,
26628 the example will be useful in illustrating the basics of
26629 the Inline Assembler facility.
26631 @smallexample @c ada
26632 @group
26633 with System.Machine_Code; use System.Machine_Code;
26634 procedure Nothing is
26635 begin
26636    Asm ("nop");
26637 end Nothing;
26638 @end group
26639 @end smallexample
26641 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
26642 here it takes one parameter, a @emph{template string} that must be a static
26643 expression and that will form the generated instruction.
26644 @code{Asm} may be regarded as a compile-time procedure that parses
26645 the template string and additional parameters (none here),
26646 from which it generates a sequence of assembly language instructions.
26648 The examples in this chapter will illustrate several of the forms
26649 for invoking @code{Asm}; a complete specification of the syntax
26650 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
26651 Manual}.
26653 Under the standard GNAT conventions, the @code{Nothing} procedure
26654 should be in a file named @file{nothing.adb}.
26655 You can build the executable in the usual way:
26656 @smallexample
26657 gnatmake nothing
26658 @end smallexample
26659 However, the interesting aspect of this example is not its run-time behavior
26660 but rather the generated assembly code.
26661 To see this output, invoke the compiler as follows:
26662 @smallexample
26663    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
26664 @end smallexample
26665 where the options are:
26667 @table @code
26668 @item -c
26669 compile only (no bind or link)
26670 @item -S
26671 generate assembler listing
26672 @item -fomit-frame-pointer
26673 do not set up separate stack frames
26674 @item -gnatp
26675 do not add runtime checks
26676 @end table
26678 This gives a human-readable assembler version of the code. The resulting
26679 file will have the same name as the Ada source file, but with a @code{.s}
26680 extension. In our example, the file @file{nothing.s} has the following
26681 contents:
26683 @smallexample
26684 @group
26685 .file "nothing.adb"
26686 gcc2_compiled.:
26687 ___gnu_compiled_ada:
26688 .text
26689    .align 4
26690 .globl __ada_nothing
26691 __ada_nothing:
26692 #APP
26693    nop
26694 #NO_APP
26695    jmp L1
26696    .align 2,0x90
26698    ret
26699 @end group
26700 @end smallexample
26702 The assembly code you included is clearly indicated by
26703 the compiler, between the @code{#APP} and @code{#NO_APP}
26704 delimiters. The character before the 'APP' and 'NOAPP'
26705 can differ on different targets. For example, GNU/Linux uses '#APP' while
26706 on NT you will see '/APP'.
26708 If you make a mistake in your assembler code (such as using the
26709 wrong size modifier, or using a wrong operand for the instruction) GNAT
26710 will report this error in a temporary file, which will be deleted when
26711 the compilation is finished.  Generating an assembler file will help
26712 in such cases, since you can assemble this file separately using the
26713 @emph{as} assembler that comes with gcc.
26715 Assembling the file using the command
26717 @smallexample
26718 as @file{nothing.s}
26719 @end smallexample
26720 @noindent
26721 will give you error messages whose lines correspond to the assembler
26722 input file, so you can easily find and correct any mistakes you made.
26723 If there are no errors, @emph{as} will generate an object file
26724 @file{nothing.out}.
26726 @c ---------------------------------------------------------------------------
26727 @node Output Variables in Inline Assembler
26728 @section Output Variables in Inline Assembler
26730 @noindent
26731 The examples in this section, showing how to access the processor flags,
26732 illustrate how to specify the destination operands for assembly language
26733 statements.
26735 @smallexample @c ada
26736 @group
26737 with Interfaces; use Interfaces;
26738 with Ada.Text_IO; use Ada.Text_IO;
26739 with System.Machine_Code; use System.Machine_Code;
26740 procedure Get_Flags is
26741    Flags : Unsigned_32;
26742    use ASCII;
26743 begin
26744    Asm ("pushfl"          & LF & HT & -- push flags on stack
26745         "popl %%eax"      & LF & HT & -- load eax with flags
26746         "movl %%eax, %0",             -- store flags in variable
26747         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26748    Put_Line ("Flags register:" & Flags'Img);
26749 end Get_Flags;
26750 @end group
26751 @end smallexample
26753 In order to have a nicely aligned assembly listing, we have separated
26754 multiple assembler statements in the Asm template string with linefeed
26755 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
26756 The resulting section of the assembly output file is:
26758 @smallexample
26759 @group
26760 #APP
26761    pushfl
26762    popl %eax
26763    movl %eax, -40(%ebp)
26764 #NO_APP
26765 @end group
26766 @end smallexample
26768 It would have been legal to write the Asm invocation as:
26770 @smallexample
26771 Asm ("pushfl popl %%eax movl %%eax, %0")
26772 @end smallexample
26774 but in the generated assembler file, this would come out as:
26776 @smallexample
26777 #APP
26778    pushfl popl %eax movl %eax, -40(%ebp)
26779 #NO_APP
26780 @end smallexample
26782 which is not so convenient for the human reader.
26784 We use Ada comments
26785 at the end of each line to explain what the assembler instructions
26786 actually do.  This is a useful convention.
26788 When writing Inline Assembler instructions, you need to precede each register
26789 and variable name with a percent sign.  Since the assembler already requires
26790 a percent sign at the beginning of a register name, you need two consecutive
26791 percent signs for such names in the Asm template string, thus @code{%%eax}.
26792 In the generated assembly code, one of the percent signs will be stripped off.
26794 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
26795 variables: operands you later define using @code{Input} or @code{Output}
26796 parameters to @code{Asm}.
26797 An output variable is illustrated in
26798 the third statement in the Asm template string:
26799 @smallexample
26800 movl %%eax, %0
26801 @end smallexample
26802 The intent is to store the contents of the eax register in a variable that can
26803 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
26804 necessarily work, since the compiler might optimize by using a register
26805 to hold Flags, and the expansion of the @code{movl} instruction would not be
26806 aware of this optimization.  The solution is not to store the result directly
26807 but rather to advise the compiler to choose the correct operand form;
26808 that is the purpose of the @code{%0} output variable.
26810 Information about the output variable is supplied in the @code{Outputs}
26811 parameter to @code{Asm}:
26812 @smallexample
26813 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26814 @end smallexample
26816 The output is defined by the @code{Asm_Output} attribute of the target type;
26817 the general format is
26818 @smallexample
26819 Type'Asm_Output (constraint_string, variable_name)
26820 @end smallexample
26822 The constraint string directs the compiler how
26823 to store/access the associated variable.  In the example
26824 @smallexample
26825 Unsigned_32'Asm_Output ("=m", Flags);
26826 @end smallexample
26827 the @code{"m"} (memory) constraint tells the compiler that the variable
26828 @code{Flags} should be stored in a memory variable, thus preventing
26829 the optimizer from keeping it in a register.  In contrast,
26830 @smallexample
26831 Unsigned_32'Asm_Output ("=r", Flags);
26832 @end smallexample
26833 uses the @code{"r"} (register) constraint, telling the compiler to
26834 store the variable in a register.
26836 If the constraint is preceded by the equal character (@strong{=}), it tells
26837 the compiler that the variable will be used to store data into it.
26839 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26840 allowing the optimizer to choose whatever it deems best.
26842 There are a fairly large number of constraints, but the ones that are
26843 most useful (for the Intel x86 processor) are the following:
26845 @table @code
26846 @item =
26847 output constraint
26848 @item g
26849 global (i.e.@: can be stored anywhere)
26850 @item m
26851 in memory
26852 @item I
26853 a constant
26854 @item a
26855 use eax
26856 @item b
26857 use ebx
26858 @item c
26859 use ecx
26860 @item d
26861 use edx
26862 @item S
26863 use esi
26864 @item D
26865 use edi
26866 @item r
26867 use one of eax, ebx, ecx or edx
26868 @item q
26869 use one of eax, ebx, ecx, edx, esi or edi
26870 @end table
26872 The full set of constraints is described in the gcc and @emph{as}
26873 documentation; note that it is possible to combine certain constraints
26874 in one constraint string.
26876 You specify the association of an output variable with an assembler operand
26877 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26878 integer.  Thus in
26879 @smallexample @c ada
26880 @group
26881 Asm ("pushfl"          & LF & HT & -- push flags on stack
26882      "popl %%eax"      & LF & HT & -- load eax with flags
26883      "movl %%eax, %0",             -- store flags in variable
26884      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26885 @end group
26886 @end smallexample
26887 @noindent
26888 @code{%0} will be replaced in the expanded code by the appropriate operand,
26889 whatever
26890 the compiler decided for the @code{Flags} variable.
26892 In general, you may have any number of output variables:
26893 @itemize @bullet
26894 @item
26895 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26896 @item
26897 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26898 of @code{Asm_Output} attributes
26899 @end itemize
26901 For example:
26902 @smallexample @c ada
26903 @group
26904 Asm ("movl %%eax, %0" & LF & HT &
26905      "movl %%ebx, %1" & LF & HT &
26906      "movl %%ecx, %2",
26907      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
26908                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
26909                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
26910 @end group
26911 @end smallexample
26912 @noindent
26913 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26914 in the Ada program.
26916 As a variation on the @code{Get_Flags} example, we can use the constraints
26917 string to direct the compiler to store the eax register into the @code{Flags}
26918 variable, instead of including the store instruction explicitly in the
26919 @code{Asm} template string:
26921 @smallexample @c ada
26922 @group
26923 with Interfaces; use Interfaces;
26924 with Ada.Text_IO; use Ada.Text_IO;
26925 with System.Machine_Code; use System.Machine_Code;
26926 procedure Get_Flags_2 is
26927    Flags : Unsigned_32;
26928    use ASCII;
26929 begin
26930    Asm ("pushfl"      & LF & HT & -- push flags on stack
26931         "popl %%eax",             -- save flags in eax
26932         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26933    Put_Line ("Flags register:" & Flags'Img);
26934 end Get_Flags_2;
26935 @end group
26936 @end smallexample
26938 @noindent
26939 The @code{"a"} constraint tells the compiler that the @code{Flags}
26940 variable will come from the eax register. Here is the resulting code:
26942 @smallexample
26943 @group
26944 #APP
26945    pushfl
26946    popl %eax
26947 #NO_APP
26948    movl %eax,-40(%ebp)
26949 @end group
26950 @end smallexample
26952 @noindent
26953 The compiler generated the store of eax into Flags after
26954 expanding the assembler code.
26956 Actually, there was no need to pop the flags into the eax register;
26957 more simply, we could just pop the flags directly into the program variable:
26959 @smallexample @c ada
26960 @group
26961 with Interfaces; use Interfaces;
26962 with Ada.Text_IO; use Ada.Text_IO;
26963 with System.Machine_Code; use System.Machine_Code;
26964 procedure Get_Flags_3 is
26965    Flags : Unsigned_32;
26966    use ASCII;
26967 begin
26968    Asm ("pushfl"  & LF & HT & -- push flags on stack
26969         "pop %0",             -- save flags in Flags
26970         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26971    Put_Line ("Flags register:" & Flags'Img);
26972 end Get_Flags_3;
26973 @end group
26974 @end smallexample
26976 @c ---------------------------------------------------------------------------
26977 @node Input Variables in Inline Assembler
26978 @section Input Variables in Inline Assembler
26980 @noindent
26981 The example in this section illustrates how to specify the source operands
26982 for assembly language statements.
26983 The program simply increments its input value by 1:
26985 @smallexample @c ada
26986 @group
26987 with Interfaces; use Interfaces;
26988 with Ada.Text_IO; use Ada.Text_IO;
26989 with System.Machine_Code; use System.Machine_Code;
26990 procedure Increment is
26992    function Incr (Value : Unsigned_32) return Unsigned_32 is
26993       Result : Unsigned_32;
26994    begin
26995       Asm ("incl %0",
26996            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26997            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26998       return Result;
26999    end Incr;
27001    Value : Unsigned_32;
27003 begin
27004    Value := 5;
27005    Put_Line ("Value before is" & Value'Img);
27006    Value := Incr (Value);
27007    Put_Line ("Value after is" & Value'Img);
27008 end Increment;
27009 @end group
27010 @end smallexample
27012 The @code{Outputs} parameter to @code{Asm} specifies
27013 that the result will be in the eax register and that it is to be stored
27014 in the @code{Result} variable.
27016 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
27017 but with an @code{Asm_Input} attribute.
27018 The @code{"="} constraint, indicating an output value, is not present.
27020 You can have multiple input variables, in the same way that you can have more
27021 than one output variable.
27023 The parameter count (%0, %1) etc, still starts at the first output statement,
27024 and continues with the input statements.
27026 Just as the @code{Outputs} parameter causes the register to be stored into the
27027 target variable after execution of the assembler statements, so does the
27028 @code{Inputs} parameter cause its variable to be loaded into the register
27029 before execution of the assembler statements.
27031 Thus the effect of the @code{Asm} invocation is:
27032 @enumerate
27033 @item load the 32-bit value of @code{Value} into eax
27034 @item execute the @code{incl %eax} instruction
27035 @item store the contents of eax into the @code{Result} variable
27036 @end enumerate
27038 The resulting assembler file (with @option{-O2} optimization) contains:
27039 @smallexample
27040 @group
27041 _increment__incr.1:
27042    subl $4,%esp
27043    movl 8(%esp),%eax
27044 #APP
27045    incl %eax
27046 #NO_APP
27047    movl %eax,%edx
27048    movl %ecx,(%esp)
27049    addl $4,%esp
27050    ret
27051 @end group
27052 @end smallexample
27054 @c ---------------------------------------------------------------------------
27055 @node Inlining Inline Assembler Code
27056 @section Inlining Inline Assembler Code
27058 @noindent
27059 For a short subprogram such as the @code{Incr} function in the previous
27060 section, the overhead of the call and return (creating / deleting the stack
27061 frame) can be significant, compared to the amount of code in the subprogram
27062 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
27063 which directs the compiler to expand invocations of the subprogram at the
27064 point(s) of call, instead of setting up a stack frame for out-of-line calls.
27065 Here is the resulting program:
27067 @smallexample @c ada
27068 @group
27069 with Interfaces; use Interfaces;
27070 with Ada.Text_IO; use Ada.Text_IO;
27071 with System.Machine_Code; use System.Machine_Code;
27072 procedure Increment_2 is
27074    function Incr (Value : Unsigned_32) return Unsigned_32 is
27075       Result : Unsigned_32;
27076    begin
27077       Asm ("incl %0",
27078            Outputs => Unsigned_32'Asm_Output ("=a", Result),
27079            Inputs  => Unsigned_32'Asm_Input ("a", Value));
27080       return Result;
27081    end Incr;
27082    pragma Inline (Increment);
27084    Value : Unsigned_32;
27086 begin
27087    Value := 5;
27088    Put_Line ("Value before is" & Value'Img);
27089    Value := Increment (Value);
27090    Put_Line ("Value after is" & Value'Img);
27091 end Increment_2;
27092 @end group
27093 @end smallexample
27095 Compile the program with both optimization (@option{-O2}) and inlining
27096 (@option{-gnatn}) enabled.
27098 The @code{Incr} function is still compiled as usual, but at the
27099 point in @code{Increment} where our function used to be called:
27101 @smallexample
27102 @group
27103 pushl %edi
27104 call _increment__incr.1
27105 @end group
27106 @end smallexample
27108 @noindent
27109 the code for the function body directly appears:
27111 @smallexample
27112 @group
27113 movl %esi,%eax
27114 #APP
27115    incl %eax
27116 #NO_APP
27117    movl %eax,%edx
27118 @end group
27119 @end smallexample
27121 @noindent
27122 thus saving the overhead of stack frame setup and an out-of-line call.
27124 @c ---------------------------------------------------------------------------
27125 @node Other Asm Functionality
27126 @section Other @code{Asm} Functionality
27128 @noindent
27129 This section describes two important parameters to the @code{Asm}
27130 procedure: @code{Clobber}, which identifies register usage;
27131 and @code{Volatile}, which inhibits unwanted optimizations.
27133 @menu
27134 * The Clobber Parameter::
27135 * The Volatile Parameter::
27136 @end menu
27138 @c ---------------------------------------------------------------------------
27139 @node The Clobber Parameter
27140 @subsection The @code{Clobber} Parameter
27142 @noindent
27143 One of the dangers of intermixing assembly language and a compiled language
27144 such as Ada is that the compiler needs to be aware of which registers are
27145 being used by the assembly code.  In some cases, such as the earlier examples,
27146 the constraint string is sufficient to indicate register usage (e.g.,
27147 @code{"a"} for
27148 the eax register).  But more generally, the compiler needs an explicit
27149 identification of the registers that are used by the Inline Assembly
27150 statements.
27152 Using a register that the compiler doesn't know about
27153 could be a side effect of an instruction (like @code{mull}
27154 storing its result in both eax and edx).
27155 It can also arise from explicit register usage in your
27156 assembly code; for example:
27157 @smallexample
27158 @group
27159 Asm ("movl %0, %%ebx" & LF & HT &
27160      "movl %%ebx, %1",
27161      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27162      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
27163 @end group
27164 @end smallexample
27165 @noindent
27166 where the compiler (since it does not analyze the @code{Asm} template string)
27167 does not know you are using the ebx register.
27169 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
27170 to identify the registers that will be used by your assembly code:
27172 @smallexample
27173 @group
27174 Asm ("movl %0, %%ebx" & LF & HT &
27175      "movl %%ebx, %1",
27176      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27177      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
27178      Clobber => "ebx");
27179 @end group
27180 @end smallexample
27182 The Clobber parameter is a static string expression specifying the
27183 register(s) you are using.  Note that register names are @emph{not} prefixed
27184 by a percent sign. Also, if more than one register is used then their names
27185 are separated by commas; e.g., @code{"eax, ebx"}
27187 The @code{Clobber} parameter has several additional uses:
27188 @enumerate
27189 @item Use ``register'' name @code{cc} to indicate that flags might have changed
27190 @item Use ``register'' name @code{memory} if you changed a memory location
27191 @end enumerate
27193 @c ---------------------------------------------------------------------------
27194 @node The Volatile Parameter
27195 @subsection The @code{Volatile} Parameter
27196 @cindex Volatile parameter
27198 @noindent
27199 Compiler optimizations in the presence of Inline Assembler may sometimes have
27200 unwanted effects.  For example, when an @code{Asm} invocation with an input
27201 variable is inside a loop, the compiler might move the loading of the input
27202 variable outside the loop, regarding it as a one-time initialization.
27204 If this effect is not desired, you can disable such optimizations by setting
27205 the @code{Volatile} parameter to @code{True}; for example:
27207 @smallexample @c ada
27208 @group
27209 Asm ("movl %0, %%ebx" & LF & HT &
27210      "movl %%ebx, %1",
27211      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
27212      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
27213      Clobber  => "ebx",
27214      Volatile => True);
27215 @end group
27216 @end smallexample
27218 By default, @code{Volatile} is set to @code{False} unless there is no
27219 @code{Outputs} parameter.
27221 Although setting @code{Volatile} to @code{True} prevents unwanted
27222 optimizations, it will also disable other optimizations that might be
27223 important for efficiency. In general, you should set @code{Volatile}
27224 to @code{True} only if the compiler's optimizations have created
27225 problems.
27226 @c END OF INLINE ASSEMBLER CHAPTER
27227 @c ===============================
27229 @c ***********************************
27230 @c * Compatibility and Porting Guide *
27231 @c ***********************************
27232 @node Compatibility and Porting Guide
27233 @appendix Compatibility and Porting Guide
27235 @noindent
27236 This chapter describes the compatibility issues that may arise between
27237 GNAT and other Ada compilation systems (including those for Ada 83),
27238 and shows how GNAT can expedite porting
27239 applications developed in other Ada environments.
27241 @menu
27242 * Compatibility with Ada 83::
27243 * Compatibility between Ada 95 and Ada 2005::
27244 * Implementation-dependent characteristics::
27245 * Compatibility with Other Ada Systems::
27246 * Representation Clauses::
27247 @ifclear vms
27248 @c Brief section is only in non-VMS version
27249 @c Full chapter is in VMS version
27250 * Compatibility with HP Ada 83::
27251 @end ifclear
27252 @ifset vms
27253 * Transitioning to 64-Bit GNAT for OpenVMS::
27254 @end ifset
27255 @end menu
27257 @node Compatibility with Ada 83
27258 @section Compatibility with Ada 83
27259 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
27261 @noindent
27262 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
27263 particular, the design intention was that the difficulties associated
27264 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
27265 that occur when moving from one Ada 83 system to another.
27267 However, there are a number of points at which there are minor
27268 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
27269 full details of these issues,
27270 and should be consulted for a complete treatment.
27271 In practice the
27272 following subsections treat the most likely issues to be encountered.
27274 @menu
27275 * Legal Ada 83 programs that are illegal in Ada 95::
27276 * More deterministic semantics::
27277 * Changed semantics::
27278 * Other language compatibility issues::
27279 @end menu
27281 @node Legal Ada 83 programs that are illegal in Ada 95
27282 @subsection Legal Ada 83 programs that are illegal in Ada 95
27284 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
27285 Ada 95 and thus also in Ada 2005:
27287 @table @emph
27288 @item Character literals
27289 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
27290 @code{Wide_Character} as a new predefined character type, some uses of
27291 character literals that were legal in Ada 83 are illegal in Ada 95.
27292 For example:
27293 @smallexample @c ada
27294    for Char in 'A' .. 'Z' loop @dots{} end loop;
27295 @end smallexample
27297 @noindent
27298 The problem is that @code{'A'} and @code{'Z'} could be from either
27299 @code{Character} or @code{Wide_Character}.  The simplest correction
27300 is to make the type explicit; e.g.:
27301 @smallexample @c ada
27302    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
27303 @end smallexample
27305 @item New reserved words
27306 The identifiers @code{abstract}, @code{aliased}, @code{protected},
27307 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
27308 Existing Ada 83 code using any of these identifiers must be edited to
27309 use some alternative name.
27311 @item Freezing rules
27312 The rules in Ada 95 are slightly different with regard to the point at
27313 which entities are frozen, and representation pragmas and clauses are
27314 not permitted past the freeze point.  This shows up most typically in
27315 the form of an error message complaining that a representation item
27316 appears too late, and the appropriate corrective action is to move
27317 the item nearer to the declaration of the entity to which it refers.
27319 A particular case is that representation pragmas
27320 @ifset vms
27321 (including the
27322 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
27323 @end ifset
27324 cannot be applied to a subprogram body.  If necessary, a separate subprogram
27325 declaration must be introduced to which the pragma can be applied.
27327 @item Optional bodies for library packages
27328 In Ada 83, a package that did not require a package body was nevertheless
27329 allowed to have one.  This lead to certain surprises in compiling large
27330 systems (situations in which the body could be unexpectedly ignored by the
27331 binder).  In Ada 95, if a package does not require a body then it is not
27332 permitted to have a body.  To fix this problem, simply remove a redundant
27333 body if it is empty, or, if it is non-empty, introduce a dummy declaration
27334 into the spec that makes the body required.  One approach is to add a private
27335 part to the package declaration (if necessary), and define a parameterless
27336 procedure called @code{Requires_Body}, which must then be given a dummy
27337 procedure body in the package body, which then becomes required.
27338 Another approach (assuming that this does not introduce elaboration
27339 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
27340 since one effect of this pragma is to require the presence of a package body.
27342 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
27343 In Ada 95, the exception @code{Numeric_Error} is a renaming of
27344 @code{Constraint_Error}.
27345 This means that it is illegal to have separate exception handlers for
27346 the two exceptions.  The fix is simply to remove the handler for the
27347 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
27348 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
27350 @item Indefinite subtypes in generics
27351 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
27352 as the actual for a generic formal private type, but then the instantiation
27353 would be illegal if there were any instances of declarations of variables
27354 of this type in the generic body.  In Ada 95, to avoid this clear violation
27355 of the methodological principle known as the ``contract model'',
27356 the generic declaration explicitly indicates whether
27357 or not such instantiations are permitted.  If a generic formal parameter
27358 has explicit unknown discriminants, indicated by using @code{(<>)} after the
27359 subtype name, then it can be instantiated with indefinite types, but no
27360 stand-alone variables can be declared of this type.  Any attempt to declare
27361 such a variable will result in an illegality at the time the generic is
27362 declared.  If the @code{(<>)} notation is not used, then it is illegal
27363 to instantiate the generic with an indefinite type.
27364 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
27365 It will show up as a compile time error, and
27366 the fix is usually simply to add the @code{(<>)} to the generic declaration.
27367 @end table
27369 @node More deterministic semantics
27370 @subsection More deterministic semantics
27372 @table @emph
27373 @item Conversions
27374 Conversions from real types to integer types round away from 0.  In Ada 83
27375 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
27376 implementation freedom was intended to support unbiased rounding in
27377 statistical applications, but in practice it interfered with portability.
27378 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
27379 is required.  Numeric code may be affected by this change in semantics.
27380 Note, though, that this issue is no worse than already existed in Ada 83
27381 when porting code from one vendor to another.
27383 @item Tasking
27384 The Real-Time Annex introduces a set of policies that define the behavior of
27385 features that were implementation dependent in Ada 83, such as the order in
27386 which open select branches are executed.
27387 @end table
27389 @node Changed semantics
27390 @subsection Changed semantics
27392 @noindent
27393 The worst kind of incompatibility is one where a program that is legal in
27394 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
27395 possible in Ada 83.  Fortunately this is extremely rare, but the one
27396 situation that you should be alert to is the change in the predefined type
27397 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
27399 @table @emph
27400 @item Range of type @code{Character}
27401 The range of @code{Standard.Character} is now the full 256 characters
27402 of Latin-1, whereas in most Ada 83 implementations it was restricted
27403 to 128 characters. Although some of the effects of
27404 this change will be manifest in compile-time rejection of legal
27405 Ada 83 programs it is possible for a working Ada 83 program to have
27406 a different effect in Ada 95, one that was not permitted in Ada 83.
27407 As an example, the expression
27408 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
27409 delivers @code{255} as its value.
27410 In general, you should look at the logic of any
27411 character-processing Ada 83 program and see whether it needs to be adapted
27412 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
27413 character handling package that may be relevant if code needs to be adapted
27414 to account for the additional Latin-1 elements.
27415 The desirable fix is to
27416 modify the program to accommodate the full character set, but in some cases
27417 it may be convenient to define a subtype or derived type of Character that
27418 covers only the restricted range.
27419 @cindex Latin-1
27420 @end table
27422 @node Other language compatibility issues
27423 @subsection Other language compatibility issues
27425 @table @emph
27426 @item @option{-gnat83} switch
27427 All implementations of GNAT provide a switch that causes GNAT to operate
27428 in Ada 83 mode.  In this mode, some but not all compatibility problems
27429 of the type described above are handled automatically.  For example, the
27430 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
27431 as identifiers as in Ada 83.
27432 However,
27433 in practice, it is usually advisable to make the necessary modifications
27434 to the program to remove the need for using this switch.
27435 See @ref{Compiling Different Versions of Ada}.
27437 @item Support for removed Ada 83 pragmas and attributes
27438 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
27439 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
27440 compilers are allowed, but not required, to implement these missing
27441 elements.  In contrast with some other compilers, GNAT implements all
27442 such pragmas and attributes, eliminating this compatibility concern.  These
27443 include @code{pragma Interface} and the floating point type attributes
27444 (@code{Emax}, @code{Mantissa}, etc.), among other items.
27445 @end table
27448 @node Compatibility between Ada 95 and Ada 2005
27449 @section Compatibility between Ada 95 and Ada 2005
27450 @cindex Compatibility between Ada 95 and Ada 2005
27452 @noindent
27453 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
27454 a number of incompatibilities. Several are enumerated below;
27455 for a complete description please see the
27456 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
27457 @cite{Rationale for Ada 2005}.
27459 @table @emph
27460 @item New reserved words.
27461 The words @code{interface}, @code{overriding} and @code{synchronized} are
27462 reserved in Ada 2005.
27463 A pre-Ada 2005 program that uses any of these as an identifier will be
27464 illegal.
27466 @item New declarations in predefined packages.
27467 A number of packages in the predefined environment contain new declarations:
27468 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
27469 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
27470 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
27471 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
27472 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
27473 If an Ada 95 program does a @code{with} and @code{use} of any of these
27474 packages, the new declarations may cause name clashes.
27476 @item Access parameters.
27477 A nondispatching subprogram with an access parameter cannot be renamed
27478 as a dispatching operation.  This was permitted in Ada 95.
27480 @item Access types, discriminants, and constraints.
27481 Rule changes in this area have led to some incompatibilities; for example,
27482 constrained subtypes of some access types are not permitted in Ada 2005.
27484 @item Aggregates for limited types.
27485 The allowance of aggregates for limited types in Ada 2005 raises the
27486 possibility of ambiguities in legal Ada 95 programs, since additional types
27487 now need to be considered in expression resolution.
27489 @item Fixed-point multiplication and division.
27490 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
27491 were legal in Ada 95 and invoked the predefined versions of these operations,
27492 are now ambiguous.
27493 The ambiguity may be resolved either by applying a type conversion to the
27494 expression, or by explicitly invoking the operation from package
27495 @code{Standard}.
27497 @item Return-by-reference types.
27498 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
27499 can declare a function returning a value from an anonymous access type.
27500 @end table
27503 @node Implementation-dependent characteristics
27504 @section Implementation-dependent characteristics
27505 @noindent
27506 Although the Ada language defines the semantics of each construct as
27507 precisely as practical, in some situations (for example for reasons of
27508 efficiency, or where the effect is heavily dependent on the host or target
27509 platform) the implementation is allowed some freedom.  In porting Ada 83
27510 code to GNAT, you need to be aware of whether / how the existing code
27511 exercised such implementation dependencies.  Such characteristics fall into
27512 several categories, and GNAT offers specific support in assisting the
27513 transition from certain Ada 83 compilers.
27515 @menu
27516 * Implementation-defined pragmas::
27517 * Implementation-defined attributes::
27518 * Libraries::
27519 * Elaboration order::
27520 * Target-specific aspects::
27521 @end menu
27523 @node Implementation-defined pragmas
27524 @subsection Implementation-defined pragmas
27526 @noindent
27527 Ada compilers are allowed to supplement the language-defined pragmas, and
27528 these are a potential source of non-portability.  All GNAT-defined pragmas
27529 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
27530 Reference Manual}, and these include several that are specifically
27531 intended to correspond to other vendors' Ada 83 pragmas.
27532 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
27533 For compatibility with HP Ada 83, GNAT supplies the pragmas
27534 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
27535 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
27536 and @code{Volatile}.
27537 Other relevant pragmas include @code{External} and @code{Link_With}.
27538 Some vendor-specific
27539 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
27540 recognized, thus
27541 avoiding compiler rejection of units that contain such pragmas; they are not
27542 relevant in a GNAT context and hence are not otherwise implemented.
27544 @node Implementation-defined attributes
27545 @subsection Implementation-defined attributes
27547 Analogous to pragmas, the set of attributes may be extended by an
27548 implementation.  All GNAT-defined attributes are described in
27549 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
27550 Manual}, and these include several that are specifically intended
27551 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
27552 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
27553 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
27554 @code{Type_Class}.
27556 @node Libraries
27557 @subsection Libraries
27558 @noindent
27559 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
27560 code uses vendor-specific libraries then there are several ways to manage
27561 this in Ada 95 or Ada 2005:
27562 @enumerate
27563 @item
27564 If the source code for the libraries (specs and bodies) are
27565 available, then the libraries can be migrated in the same way as the
27566 application.
27567 @item
27568 If the source code for the specs but not the bodies are
27569 available, then you can reimplement the bodies.
27570 @item
27571 Some features introduced by Ada 95 obviate the need for library support.  For
27572 example most Ada 83 vendors supplied a package for unsigned integers.  The
27573 Ada 95 modular type feature is the preferred way to handle this need, so
27574 instead of migrating or reimplementing the unsigned integer package it may
27575 be preferable to retrofit the application using modular types.
27576 @end enumerate
27578 @node Elaboration order
27579 @subsection Elaboration order
27580 @noindent
27581 The implementation can choose any elaboration order consistent with the unit
27582 dependency relationship.  This freedom means that some orders can result in
27583 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
27584 to invoke a subprogram its body has been elaborated, or to instantiate a
27585 generic before the generic body has been elaborated.  By default GNAT
27586 attempts to choose a safe order (one that will not encounter access before
27587 elaboration problems) by implicitly inserting @code{Elaborate} or
27588 @code{Elaborate_All} pragmas where
27589 needed.  However, this can lead to the creation of elaboration circularities
27590 and a resulting rejection of the program by gnatbind.  This issue is
27591 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
27592 In brief, there are several
27593 ways to deal with this situation:
27595 @itemize @bullet
27596 @item
27597 Modify the program to eliminate the circularities, e.g.@: by moving
27598 elaboration-time code into explicitly-invoked procedures
27599 @item
27600 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
27601 @code{Elaborate} pragmas, and then inhibit the generation of implicit
27602 @code{Elaborate_All}
27603 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
27604 (by selectively suppressing elaboration checks via pragma
27605 @code{Suppress(Elaboration_Check)} when it is safe to do so).
27606 @end itemize
27608 @node Target-specific aspects
27609 @subsection Target-specific aspects
27610 @noindent
27611 Low-level applications need to deal with machine addresses, data
27612 representations, interfacing with assembler code, and similar issues.  If
27613 such an Ada 83 application is being ported to different target hardware (for
27614 example where the byte endianness has changed) then you will need to
27615 carefully examine the program logic; the porting effort will heavily depend
27616 on the robustness of the original design.  Moreover, Ada 95 (and thus
27617 Ada 2005) are sometimes
27618 incompatible with typical Ada 83 compiler practices regarding implicit
27619 packing, the meaning of the Size attribute, and the size of access values.
27620 GNAT's approach to these issues is described in @ref{Representation Clauses}.
27622 @node Compatibility with Other Ada Systems
27623 @section Compatibility with Other Ada Systems
27625 @noindent
27626 If programs avoid the use of implementation dependent and
27627 implementation defined features, as documented in the @cite{Ada
27628 Reference Manual}, there should be a high degree of portability between
27629 GNAT and other Ada systems.  The following are specific items which
27630 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
27631 compilers, but do not affect porting code to GNAT@.
27632 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
27633 the following issues may or may not arise for Ada 2005 programs
27634 when other compilers appear.)
27636 @table @emph
27637 @item Ada 83 Pragmas and Attributes
27638 Ada 95 compilers are allowed, but not required, to implement the missing
27639 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
27640 GNAT implements all such pragmas and attributes, eliminating this as
27641 a compatibility concern, but some other Ada 95 compilers reject these
27642 pragmas and attributes.
27644 @item Specialized Needs Annexes
27645 GNAT implements the full set of special needs annexes.  At the
27646 current time, it is the only Ada 95 compiler to do so.  This means that
27647 programs making use of these features may not be portable to other Ada
27648 95 compilation systems.
27650 @item Representation Clauses
27651 Some other Ada 95 compilers implement only the minimal set of
27652 representation clauses required by the Ada 95 reference manual.  GNAT goes
27653 far beyond this minimal set, as described in the next section.
27654 @end table
27656 @node Representation Clauses
27657 @section Representation Clauses
27659 @noindent
27660 The Ada 83 reference manual was quite vague in describing both the minimal
27661 required implementation of representation clauses, and also their precise
27662 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
27663 minimal set of capabilities required is still quite limited.
27665 GNAT implements the full required set of capabilities in
27666 Ada 95 and Ada 2005, but also goes much further, and in particular
27667 an effort has been made to be compatible with existing Ada 83 usage to the
27668 greatest extent possible.
27670 A few cases exist in which Ada 83 compiler behavior is incompatible with
27671 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
27672 intentional or accidental dependence on specific implementation dependent
27673 characteristics of these Ada 83 compilers.  The following is a list of
27674 the cases most likely to arise in existing Ada 83 code.
27676 @table @emph
27677 @item Implicit Packing
27678 Some Ada 83 compilers allowed a Size specification to cause implicit
27679 packing of an array or record.  This could cause expensive implicit
27680 conversions for change of representation in the presence of derived
27681 types, and the Ada design intends to avoid this possibility.
27682 Subsequent AI's were issued to make it clear that such implicit
27683 change of representation in response to a Size clause is inadvisable,
27684 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27685 Reference Manuals as implementation advice that is followed by GNAT@.
27686 The problem will show up as an error
27687 message rejecting the size clause.  The fix is simply to provide
27688 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27689 a Component_Size clause.
27691 @item Meaning of Size Attribute
27692 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27693 the minimal number of bits required to hold values of the type.  For example,
27694 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27695 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
27696 some 32 in this situation.  This problem will usually show up as a compile
27697 time error, but not always.  It is a good idea to check all uses of the
27698 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
27699 Object_Size can provide a useful way of duplicating the behavior of
27700 some Ada 83 compiler systems.
27702 @item Size of Access Types
27703 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27704 and that therefore it will be the same size as a System.Address value.  This
27705 assumption is true for GNAT in most cases with one exception.  For the case of
27706 a pointer to an unconstrained array type (where the bounds may vary from one
27707 value of the access type to another), the default is to use a ``fat pointer'',
27708 which is represented as two separate pointers, one to the bounds, and one to
27709 the array.  This representation has a number of advantages, including improved
27710 efficiency.  However, it may cause some difficulties in porting existing Ada 83
27711 code which makes the assumption that, for example, pointers fit in 32 bits on
27712 a machine with 32-bit addressing.
27714 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27715 access types in this case (where the designated type is an unconstrained array
27716 type).  These thin pointers are indeed the same size as a System.Address value.
27717 To specify a thin pointer, use a size clause for the type, for example:
27719 @smallexample @c ada
27720 type X is access all String;
27721 for X'Size use Standard'Address_Size;
27722 @end smallexample
27724 @noindent
27725 which will cause the type X to be represented using a single pointer.
27726 When using this representation, the bounds are right behind the array.
27727 This representation is slightly less efficient, and does not allow quite
27728 such flexibility in the use of foreign pointers or in using the
27729 Unrestricted_Access attribute to create pointers to non-aliased objects.
27730 But for any standard portable use of the access type it will work in
27731 a functionally correct manner and allow porting of existing code.
27732 Note that another way of forcing a thin pointer representation
27733 is to use a component size clause for the element size in an array,
27734 or a record representation clause for an access field in a record.
27735 @end table
27737 @ifclear vms
27738 @c This brief section is only in the non-VMS version
27739 @c The complete chapter on HP Ada is in the VMS version
27740 @node Compatibility with HP Ada 83
27741 @section Compatibility with HP Ada 83
27743 @noindent
27744 The VMS version of GNAT fully implements all the pragmas and attributes
27745 provided by HP Ada 83, as well as providing the standard HP Ada 83
27746 libraries, including Starlet.  In addition, data layouts and parameter
27747 passing conventions are highly compatible.  This means that porting
27748 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27749 most other porting efforts.  The following are some of the most
27750 significant differences between GNAT and HP Ada 83.
27752 @table @emph
27753 @item Default floating-point representation
27754 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27755 it is VMS format.  GNAT does implement the necessary pragmas
27756 (Long_Float, Float_Representation) for changing this default.
27758 @item System
27759 The package System in GNAT exactly corresponds to the definition in the
27760 Ada 95 reference manual, which means that it excludes many of the
27761 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
27762 that contains the additional definitions, and a special pragma,
27763 Extend_System allows this package to be treated transparently as an
27764 extension of package System.
27766 @item To_Address
27767 The definitions provided by Aux_DEC are exactly compatible with those
27768 in the HP Ada 83 version of System, with one exception.
27769 HP Ada provides the following declarations:
27771 @smallexample @c ada
27772 TO_ADDRESS (INTEGER)
27773 TO_ADDRESS (UNSIGNED_LONGWORD)
27774 TO_ADDRESS (@i{universal_integer})
27775 @end smallexample
27777 @noindent
27778 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27779 an extension to Ada 83 not strictly compatible with the reference manual.
27780 In GNAT, we are constrained to be exactly compatible with the standard,
27781 and this means we cannot provide this capability.  In HP Ada 83, the
27782 point of this definition is to deal with a call like:
27784 @smallexample @c ada
27785 TO_ADDRESS (16#12777#);
27786 @end smallexample
27788 @noindent
27789 Normally, according to the Ada 83 standard, one would expect this to be
27790 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27791 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
27792 definition using @i{universal_integer} takes precedence.
27794 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27795 is not possible to be 100% compatible.  Since there are many programs using
27796 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27797 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27798 declarations provided in the GNAT version of AUX_Dec are:
27800 @smallexample @c ada
27801 function To_Address (X : Integer) return Address;
27802 pragma Pure_Function (To_Address);
27804 function To_Address_Long (X : Unsigned_Longword)
27805  return Address;
27806 pragma Pure_Function (To_Address_Long);
27807 @end smallexample
27809 @noindent
27810 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27811 change the name to TO_ADDRESS_LONG@.
27813 @item Task_Id values
27814 The Task_Id values assigned will be different in the two systems, and GNAT
27815 does not provide a specified value for the Task_Id of the environment task,
27816 which in GNAT is treated like any other declared task.
27817 @end table
27819 @noindent
27820 For full details on these and other less significant compatibility issues,
27821 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27822 Overview and Comparison on HP Platforms}.
27824 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27825 attributes are recognized, although only a subset of them can sensibly
27826 be implemented.  The description of pragmas in @ref{Implementation
27827 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27828 indicates whether or not they are applicable to non-VMS systems.
27829 @end ifclear
27831 @ifset vms
27832 @node Transitioning to 64-Bit GNAT for OpenVMS
27833 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
27835 @noindent
27836 This section is meant to assist users of pre-2006 @value{EDITION}
27837 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
27838 the version of the GNAT technology supplied in 2006 and later for
27839 OpenVMS on both Alpha and I64.
27841 @menu
27842 * Introduction to transitioning::
27843 * Migration of 32 bit code::
27844 * Taking advantage of 64 bit addressing::
27845 * Technical details::
27846 @end menu
27848 @node Introduction to transitioning
27849 @subsection Introduction
27851 @noindent
27852 64-bit @value{EDITION} for Open VMS has been designed to meet
27853 three main goals:
27855 @enumerate
27856 @item
27857 Providing a full conforming implementation of Ada 95 and Ada 2005
27859 @item
27860 Allowing maximum backward compatibility, thus easing migration of existing
27861 Ada source code
27863 @item
27864 Supplying a path for exploiting the full 64-bit address range
27865 @end enumerate
27867 @noindent
27868 Ada's strong typing semantics has made it
27869 impractical to have different 32-bit and 64-bit modes. As soon as
27870 one object could possibly be outside the 32-bit address space, this
27871 would make it necessary for the @code{System.Address} type to be 64 bits.
27872 In particular, this would cause inconsistencies if 32-bit code is
27873 called from 64-bit code that raises an exception.
27875 This issue has been resolved by always using 64-bit addressing
27876 at the system level, but allowing for automatic conversions between
27877 32-bit and 64-bit addresses where required. Thus users who
27878 do not currently require 64-bit addressing capabilities, can
27879 recompile their code with only minimal changes (and indeed
27880 if the code is written in portable Ada, with no assumptions about
27881 the size of the @code{Address} type, then no changes at all are necessary).
27882 At the same time,
27883 this approach provides a simple, gradual upgrade path to future
27884 use of larger memories than available for 32-bit systems.
27885 Also, newly written applications or libraries will by default
27886 be fully compatible with future systems exploiting 64-bit
27887 addressing capabilities.
27889 @ref{Migration of 32 bit code}, will focus on porting applications
27890 that do not require more than 2 GB of
27891 addressable memory. This code will be referred to as
27892 @emph{32-bit code}.
27893 For applications intending to exploit the full 64-bit address space,
27894 @ref{Taking advantage of 64 bit addressing},
27895 will consider further changes that may be required.
27896 Such code will be referred to below as @emph{64-bit code}.
27898 @node Migration of 32 bit code
27899 @subsection Migration of 32-bit code
27901 @menu
27902 * Address types::
27903 * Access types and 32/64-bit allocation::
27904 * Unchecked conversions::
27905 * Predefined constants::
27906 * Interfacing with C::
27907 * 32/64-bit descriptors::
27908 * Experience with source compatibility::
27909 @end menu
27911 @node Address types
27912 @subsubsection Address types
27914 @noindent
27915 To solve the problem of mixing 64-bit and 32-bit addressing,
27916 while maintaining maximum backward compatibility, the following
27917 approach has been taken:
27919 @itemize @bullet
27920 @item
27921 @code{System.Address} always has a size of 64 bits
27922 @cindex @code{System.Address} size
27923 @cindex @code{Address} size
27925 @item
27926 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
27927 @cindex @code{System.Short_Address} size
27928 @cindex @code{Short_Address} size
27929 @end itemize
27931 @noindent
27932 Since @code{System.Short_Address} is a subtype of @code{System.Address},
27933 a @code{Short_Address}
27934 may be used where an @code{Address} is required, and vice versa, without
27935 needing explicit type conversions.
27936 By virtue of the Open VMS parameter passing conventions,
27937 even imported
27938 and exported subprograms that have 32-bit address parameters are
27939 compatible with those that have 64-bit address parameters.
27940 (See @ref{Making code 64 bit clean} for details.)
27942 The areas that may need attention are those where record types have
27943 been defined that contain components of the type @code{System.Address}, and
27944 where objects of this type are passed to code expecting a record layout with
27945 32-bit addresses.
27947 Different compilers on different platforms cannot be
27948 expected to represent the same type in the same way,
27949 since alignment constraints
27950 and other system-dependent properties affect the compiler's decision.
27951 For that reason, Ada code
27952 generally uses representation clauses to specify the expected
27953 layout where required.
27955 If such a representation clause uses 32 bits for a component having
27956 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
27957 will detect that error and produce a specific diagnostic message.
27958 The developer should then determine whether the representation
27959 should be 64 bits or not and make either of two changes:
27960 change the size to 64 bits and leave the type as @code{System.Address}, or
27961 leave the size as 32 bits and change the type to @code{System.Short_Address}.
27962 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
27963 required in any code setting or accessing the field; the compiler will
27964 automatically perform any needed conversions between address
27965 formats.
27967 @node Access types and 32/64-bit allocation
27968 @subsubsection Access types and 32/64-bit allocation
27969 @cindex 32-bit allocation
27970 @cindex 64-bit allocation
27972 @noindent
27973 By default, objects designated by access values are always allocated in
27974 the 64-bit address space, and access values themselves are represented
27975 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
27976 is required (for example if the address of an allocated object is assigned
27977 to a @code{Short_Address} variable), then several alternatives are available:
27979 @itemize @bullet
27980 @item
27981 A pool-specific access type (ie, an @w{Ada 83} access type, whose
27982 definition is @code{access T} versus @code{access all T} or
27983 @code{access constant T}), may be declared with a @code{'Size} representation
27984 clause that establishes the size as 32 bits.
27985 In such circumstances allocations for that type will
27986 be from the 32-bit heap.  Such a clause is not permitted
27987 for a general access type (declared with @code{access all} or
27988 @code{access constant}) as values of such types must be able to refer
27989 to any object of the designated type, including objects residing outside
27990 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
27991 type definitions, however, since general access types were introduced
27992 in @w{Ada 95}.
27994 @item
27995 Switches for @command{GNAT BIND} control whether the internal GNAT
27996 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
27997 @cindex @code{__gnat_malloc}
27998 The switches are respectively @option{-H64} (the default) and
27999 @option{-H32}.
28000 @cindex @option{-H32} (@command{gnatbind})
28001 @cindex @option{-H64} (@command{gnatbind})
28003 @item
28004 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
28005 @cindex @code{GNAT$NO_MALLOC_64} environment variable
28006 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
28007 If this variable is left
28008 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
28009 then the default (64-bit) allocation is used.
28010 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
28011 then 32-bit allocation is used.  The gnatbind qualifiers described above
28012 override this logical name.
28014 @item
28015 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
28016 @cindex @option{-mno-malloc64} (^gcc^gcc^)
28017 at a low level to convert explicit calls to @code{malloc} and related
28018 functions from the C run-time library so that they perform allocations
28019 in the 32-bit heap.
28020 Since all internal allocations from GNAT use @code{__gnat_malloc},
28021 this switch is not required unless the program makes explicit calls on
28022 @code{malloc} (or related functions) from interfaced C code.
28023 @end itemize
28026 @node Unchecked conversions
28027 @subsubsection Unchecked conversions
28029 @noindent
28030 In the case of an @code{Unchecked_Conversion} where the source type is a
28031 64-bit access type or the type @code{System.Address}, and the target
28032 type is a 32-bit type, the compiler will generate a warning.
28033 Even though the generated code will still perform the required
28034 conversions, it is highly recommended in these cases to use
28035 respectively a 32-bit access type or @code{System.Short_Address}
28036 as the source type.
28038 @node Predefined constants
28039 @subsubsection Predefined constants
28041 @noindent
28042 The following table shows the correspondence between pre-2006 versions of
28043 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
28044 (``New''):
28046 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
28047 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
28048 @item   @code{System.Word_Size}          @tab 32      @tab 64
28049 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
28050 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
28051 @item   @code{System.Address_Size}       @tab 32      @tab 64
28052 @end multitable
28054 @noindent
28055 If you need to refer to the specific
28056 memory size of a 32-bit implementation, instead of the
28057 actual memory size, use @code{System.Short_Memory_Size}
28058 rather than @code{System.Memory_Size}.
28059 Similarly, references to @code{System.Address_Size} may need
28060 to be replaced by @code{System.Short_Address'Size}.
28061 The program @command{gnatfind} may be useful for locating
28062 references to the above constants, so that you can verify that they
28063 are still correct.
28065 @node Interfacing with C
28066 @subsubsection Interfacing with C
28068 @noindent
28069 In order to minimize the impact of the transition to 64-bit addresses on
28070 legacy programs, some fundamental types in the @code{Interfaces.C}
28071 package hierarchy continue to be represented in 32 bits.
28072 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
28073 This eases integration with the default HP C layout choices, for example
28074 as found in the system routines in @code{DECC$SHR.EXE}.
28075 Because of this implementation choice, the type fully compatible with
28076 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
28077 Depending on the context the compiler will issue a
28078 warning or an error when type @code{Address} is used, alerting the user to a
28079 potential problem. Otherwise 32-bit programs that use
28080 @code{Interfaces.C} should normally not require code modifications
28082 The other issue arising with C interfacing concerns pragma @code{Convention}.
28083 For VMS 64-bit systems, there is an issue of the appropriate default size
28084 of C convention pointers in the absence of an explicit size clause. The HP
28085 C compiler can choose either 32 or 64 bits depending on compiler options.
28086 GNAT chooses 32-bits rather than 64-bits in the default case where no size
28087 clause is given. This proves a better choice for porting 32-bit legacy
28088 applications. In order to have a 64-bit representation, it is necessary to
28089 specify a size representation clause. For example:
28091 @smallexample @c ada
28092 type int_star is access Interfaces.C.int;
28093 pragma Convention(C, int_star);
28094 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
28095 @end smallexample
28097 @node 32/64-bit descriptors
28098 @subsubsection 32/64-bit descriptors
28100 @noindent
28101 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
28102 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
28103 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
28104 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
28105 @cindex @code{Short_Descriptor} mechanism for imported subprograms
28107 If the configuration pragma @code{Short_Descriptors} is supplied, then
28108 all descriptors will be 32 bits.
28109 @cindex pragma @code{Short_Descriptors}
28111 @node Experience with source compatibility
28112 @subsubsection Experience with source compatibility
28114 @noindent
28115 The Security Server and STARLET on I64 provide an interesting ``test case''
28116 for source compatibility issues, since it is in such system code
28117 where assumptions about @code{Address} size might be expected to occur.
28118 Indeed, there were a small number of occasions in the Security Server
28119 file @file{jibdef.ads}
28120 where a representation clause for a record type specified
28121 32 bits for a component of type @code{Address}.
28122 All of these errors were detected by the compiler.
28123 The repair was obvious and immediate; to simply replace @code{Address} by
28124 @code{Short_Address}.
28126 In the case of STARLET, there were several record types that should
28127 have had representation clauses but did not.  In these record types
28128 there was an implicit assumption that an @code{Address} value occupied
28129 32 bits.
28130 These compiled without error, but their usage resulted in run-time error
28131 returns from STARLET system calls.
28132 Future GNAT technology enhancements may include a tool that detects and flags
28133 these sorts of potential source code porting problems.
28135 @c ****************************************
28136 @node Taking advantage of 64 bit addressing
28137 @subsection Taking advantage of 64-bit addressing
28139 @menu
28140 * Making code 64 bit clean::
28141 * Allocating memory from the 64 bit storage pool::
28142 * Restrictions on use of 64 bit objects::
28143 * STARLET and other predefined libraries::
28144 @end menu
28146 @node Making code 64 bit clean
28147 @subsubsection Making code 64-bit clean
28149 @noindent
28150 In order to prevent problems that may occur when (parts of) a
28151 system start using memory outside the 32-bit address range,
28152 we recommend some additional guidelines:
28154 @itemize @bullet
28155 @item
28156 For imported subprograms that take parameters of the
28157 type @code{System.Address}, ensure that these subprograms can
28158 indeed handle 64-bit addresses. If not, or when in doubt,
28159 change the subprogram declaration to specify
28160 @code{System.Short_Address} instead.
28162 @item
28163 Resolve all warnings related to size mismatches in
28164 unchecked conversions. Failing to do so causes
28165 erroneous execution if the source object is outside
28166 the 32-bit address space.
28168 @item
28169 (optional) Explicitly use the 32-bit storage pool
28170 for access types used in a 32-bit context, or use
28171 generic access types where possible
28172 (@pxref{Restrictions on use of 64 bit objects}).
28173 @end itemize
28175 @noindent
28176 If these rules are followed, the compiler will automatically insert
28177 any necessary checks to ensure that no addresses or access values
28178 passed to 32-bit code ever refer to objects outside the 32-bit
28179 address range.
28180 Any attempt to do this will raise @code{Constraint_Error}.
28182 @node Allocating memory from the 64 bit storage pool
28183 @subsubsection Allocating memory from the 64-bit storage pool
28185 @noindent
28186 By default, all allocations -- for both pool-specific and general
28187 access types -- use the 64-bit storage pool.  To override
28188 this default, for an individual access type or globally, see
28189 @ref{Access types and 32/64-bit allocation}.
28191 @node Restrictions on use of 64 bit objects
28192 @subsubsection Restrictions on use of 64-bit objects
28194 @noindent
28195 Taking the address of an object allocated from a 64-bit storage pool,
28196 and then passing this address to a subprogram expecting
28197 @code{System.Short_Address},
28198 or assigning it to a variable of type @code{Short_Address}, will cause
28199 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
28200 (@pxref{Making code 64 bit clean}), or checks are suppressed,
28201 no exception is raised and execution
28202 will become erroneous.
28204 @node STARLET and other predefined libraries
28205 @subsubsection STARLET and other predefined libraries
28207 @noindent
28208 All code that comes as part of GNAT is 64-bit clean, but the
28209 restrictions given in @ref{Restrictions on use of 64 bit objects},
28210 still apply. Look at the package
28211 specs to see in which contexts objects allocated
28212 in 64-bit address space are acceptable.
28214 @node Technical details
28215 @subsection Technical details
28217 @noindent
28218 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
28219 Ada standard with respect to the type of @code{System.Address}. Previous
28220 versions of @value{EDITION} have defined this type as private and implemented it as a
28221 modular type.
28223 In order to allow defining @code{System.Short_Address} as a proper subtype,
28224 and to match the implicit sign extension in parameter passing,
28225 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
28226 visible (i.e., non-private) integer type.
28227 Standard operations on the type, such as the binary operators ``+'', ``-'',
28228 etc., that take @code{Address} operands and return an @code{Address} result,
28229 have been hidden by declaring these
28230 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
28231 ambiguities that would otherwise result from overloading.
28232 (Note that, although @code{Address} is a visible integer type,
28233 good programming practice dictates against exploiting the type's
28234 integer properties such as literals, since this will compromise
28235 code portability.)
28237 Defining @code{Address} as a visible integer type helps achieve
28238 maximum compatibility for existing Ada code,
28239 without sacrificing the capabilities of the 64-bit architecture.
28240 @end ifset
28242 @c ************************************************
28243 @ifset unw
28244 @node Microsoft Windows Topics
28245 @appendix Microsoft Windows Topics
28246 @cindex Windows NT
28247 @cindex Windows 95
28248 @cindex Windows 98
28250 @noindent
28251 This chapter describes topics that are specific to the Microsoft Windows
28252 platforms (NT, 2000, and XP Professional).
28254 @menu
28255 * Using GNAT on Windows::
28256 * Using a network installation of GNAT::
28257 * CONSOLE and WINDOWS subsystems::
28258 * Temporary Files::
28259 * Mixed-Language Programming on Windows::
28260 * Windows Calling Conventions::
28261 * Introduction to Dynamic Link Libraries (DLLs)::
28262 * Using DLLs with GNAT::
28263 * Building DLLs with GNAT Project files::
28264 * Building DLLs with GNAT::
28265 * Building DLLs with gnatdll::
28266 * GNAT and Windows Resources::
28267 * Debugging a DLL::
28268 * Setting Stack Size from gnatlink::
28269 * Setting Heap Size from gnatlink::
28270 @end menu
28272 @node Using GNAT on Windows
28273 @section Using GNAT on Windows
28275 @noindent
28276 One of the strengths of the GNAT technology is that its tool set
28277 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
28278 @code{gdb} debugger, etc.) is used in the same way regardless of the
28279 platform.
28281 On Windows this tool set is complemented by a number of Microsoft-specific
28282 tools that have been provided to facilitate interoperability with Windows
28283 when this is required. With these tools:
28285 @itemize @bullet
28287 @item
28288 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
28289 subsystems.
28291 @item
28292 You can use any Dynamically Linked Library (DLL) in your Ada code (both
28293 relocatable and non-relocatable DLLs are supported).
28295 @item
28296 You can build Ada DLLs for use in other applications. These applications
28297 can be written in a language other than Ada (e.g., C, C++, etc). Again both
28298 relocatable and non-relocatable Ada DLLs are supported.
28300 @item
28301 You can include Windows resources in your Ada application.
28303 @item
28304 You can use or create COM/DCOM objects.
28305 @end itemize
28307 @noindent
28308 Immediately below are listed all known general GNAT-for-Windows restrictions.
28309 Other restrictions about specific features like Windows Resources and DLLs
28310 are listed in separate sections below.
28312 @itemize @bullet
28314 @item
28315 It is not possible to use @code{GetLastError} and @code{SetLastError}
28316 when tasking, protected records, or exceptions are used. In these
28317 cases, in order to implement Ada semantics, the GNAT run-time system
28318 calls certain Win32 routines that set the last error variable to 0 upon
28319 success. It should be possible to use @code{GetLastError} and
28320 @code{SetLastError} when tasking, protected record, and exception
28321 features are not used, but it is not guaranteed to work.
28323 @item
28324 It is not possible to link against Microsoft C++ libraries except for
28325 import libraries. Interfacing must be done by the mean of DLLs.
28327 @item
28328 It is possible to link against Microsoft C libraries. Yet the preferred
28329 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
28330 doesn't require having two different development environments and makes the
28331 inter-language debugging experience smoother.
28333 @item
28334 When the compilation environment is located on FAT32 drives, users may
28335 experience recompilations of the source files that have not changed if
28336 Daylight Saving Time (DST) state has changed since the last time files
28337 were compiled. NTFS drives do not have this problem.
28339 @item
28340 No components of the GNAT toolset use any entries in the Windows
28341 registry. The only entries that can be created are file associations and
28342 PATH settings, provided the user has chosen to create them at installation
28343 time, as well as some minimal book-keeping information needed to correctly
28344 uninstall or integrate different GNAT products.
28345 @end itemize
28347 @node Using a network installation of GNAT
28348 @section Using a network installation of GNAT
28350 @noindent
28351 Make sure the system on which GNAT is installed is accessible from the
28352 current machine, i.e., the install location is shared over the network.
28353 Shared resources are accessed on Windows by means of UNC paths, which
28354 have the format @code{\\server\sharename\path}
28356 In order to use such a network installation, simply add the UNC path of the
28357 @file{bin} directory of your GNAT installation in front of your PATH. For
28358 example, if GNAT is installed in @file{\GNAT} directory of a share location
28359 called @file{c-drive} on a machine @file{LOKI}, the following command will
28360 make it available:
28362 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
28364 Be aware that every compilation using the network installation results in the
28365 transfer of large amounts of data across the network and will likely cause
28366 serious performance penalty.
28368 @node CONSOLE and WINDOWS subsystems
28369 @section CONSOLE and WINDOWS subsystems
28370 @cindex CONSOLE Subsystem
28371 @cindex WINDOWS Subsystem
28372 @cindex -mwindows
28374 @noindent
28375 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
28376 (which is the default subsystem) will always create a console when
28377 launching the application. This is not something desirable when the
28378 application has a Windows GUI. To get rid of this console the
28379 application must be using the @code{WINDOWS} subsystem. To do so
28380 the @option{-mwindows} linker option must be specified.
28382 @smallexample
28383 $ gnatmake winprog -largs -mwindows
28384 @end smallexample
28386 @node Temporary Files
28387 @section Temporary Files
28388 @cindex Temporary files
28390 @noindent
28391 It is possible to control where temporary files gets created by setting
28392 the @env{TMP} environment variable. The file will be created:
28394 @itemize
28395 @item Under the directory pointed to by the @env{TMP} environment variable if
28396 this directory exists.
28398 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
28399 set (or not pointing to a directory) and if this directory exists.
28401 @item Under the current working directory otherwise.
28402 @end itemize
28404 @noindent
28405 This allows you to determine exactly where the temporary
28406 file will be created. This is particularly useful in networked
28407 environments where you may not have write access to some
28408 directories.
28410 @node Mixed-Language Programming on Windows
28411 @section Mixed-Language Programming on Windows
28413 @noindent
28414 Developing pure Ada applications on Windows is no different than on
28415 other GNAT-supported platforms. However, when developing or porting an
28416 application that contains a mix of Ada and C/C++, the choice of your
28417 Windows C/C++ development environment conditions your overall
28418 interoperability strategy.
28420 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
28421 your application, there are no Windows-specific restrictions that
28422 affect the overall interoperability with your Ada code. If you do want
28423 to use the Microsoft tools for your C++ code, you have two choices:
28425 @enumerate
28426 @item
28427 Encapsulate your C++ code in a DLL to be linked with your Ada
28428 application. In this case, use the Microsoft or whatever environment to
28429 build the DLL and use GNAT to build your executable
28430 (@pxref{Using DLLs with GNAT}).
28432 @item
28433 Or you can encapsulate your Ada code in a DLL to be linked with the
28434 other part of your application. In this case, use GNAT to build the DLL
28435 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
28436 or whatever environment to build your executable.
28437 @end enumerate
28439 In addition to the description about C main in
28440 @pxref{Mixed Language Programming} section, if the C main uses a
28441 stand-alone library it is required on x86-windows to
28442 setup the SEH context. For this the C main must looks like this:
28444 @smallexample
28445 /* main.c */
28446 extern void adainit (void);
28447 extern void adafinal (void);
28448 extern void __gnat_initialize(void*);
28449 extern void call_to_ada (void);
28451 int main (int argc, char *argv[])
28453   int SEH [2];
28455   /* Initialize the SEH context */
28456   __gnat_initialize (&SEH);
28458   adainit();
28460   /* Then call Ada services in the stand-alone library */
28462   call_to_ada();
28464   adafinal();
28466 @end smallexample
28468 Note that this is not needed on x86_64-windows where the Windows
28469 native SEH support is used.
28471 @node Windows Calling Conventions
28472 @section Windows Calling Conventions
28473 @findex Stdcall
28474 @findex APIENTRY
28476 This section pertain only to Win32. On Win64 there is a single native
28477 calling convention. All convention specifiers are ignored on this
28478 platform.
28480 @menu
28481 * C Calling Convention::
28482 * Stdcall Calling Convention::
28483 * Win32 Calling Convention::
28484 * DLL Calling Convention::
28485 @end menu
28487 @noindent
28488 When a subprogram @code{F} (caller) calls a subprogram @code{G}
28489 (callee), there are several ways to push @code{G}'s parameters on the
28490 stack and there are several possible scenarios to clean up the stack
28491 upon @code{G}'s return. A calling convention is an agreed upon software
28492 protocol whereby the responsibilities between the caller (@code{F}) and
28493 the callee (@code{G}) are clearly defined. Several calling conventions
28494 are available for Windows:
28496 @itemize @bullet
28497 @item
28498 @code{C} (Microsoft defined)
28500 @item
28501 @code{Stdcall} (Microsoft defined)
28503 @item
28504 @code{Win32} (GNAT specific)
28506 @item
28507 @code{DLL} (GNAT specific)
28508 @end itemize
28510 @node C Calling Convention
28511 @subsection @code{C} Calling Convention
28513 @noindent
28514 This is the default calling convention used when interfacing to C/C++
28515 routines compiled with either @command{gcc} or Microsoft Visual C++.
28517 In the @code{C} calling convention subprogram parameters are pushed on the
28518 stack by the caller from right to left. The caller itself is in charge of
28519 cleaning up the stack after the call. In addition, the name of a routine
28520 with @code{C} calling convention is mangled by adding a leading underscore.
28522 The name to use on the Ada side when importing (or exporting) a routine
28523 with @code{C} calling convention is the name of the routine. For
28524 instance the C function:
28526 @smallexample
28527 int get_val (long);
28528 @end smallexample
28530 @noindent
28531 should be imported from Ada as follows:
28533 @smallexample @c ada
28534 @group
28535 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28536 pragma Import (C, Get_Val, External_Name => "get_val");
28537 @end group
28538 @end smallexample
28540 @noindent
28541 Note that in this particular case the @code{External_Name} parameter could
28542 have been omitted since, when missing, this parameter is taken to be the
28543 name of the Ada entity in lower case. When the @code{Link_Name} parameter
28544 is missing, as in the above example, this parameter is set to be the
28545 @code{External_Name} with a leading underscore.
28547 When importing a variable defined in C, you should always use the @code{C}
28548 calling convention unless the object containing the variable is part of a
28549 DLL (in which case you should use the @code{Stdcall} calling
28550 convention, @pxref{Stdcall Calling Convention}).
28552 @node Stdcall Calling Convention
28553 @subsection @code{Stdcall} Calling Convention
28555 @noindent
28556 This convention, which was the calling convention used for Pascal
28557 programs, is used by Microsoft for all the routines in the Win32 API for
28558 efficiency reasons. It must be used to import any routine for which this
28559 convention was specified.
28561 In the @code{Stdcall} calling convention subprogram parameters are pushed
28562 on the stack by the caller from right to left. The callee (and not the
28563 caller) is in charge of cleaning the stack on routine exit. In addition,
28564 the name of a routine with @code{Stdcall} calling convention is mangled by
28565 adding a leading underscore (as for the @code{C} calling convention) and a
28566 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
28567 bytes) of the parameters passed to the routine.
28569 The name to use on the Ada side when importing a C routine with a
28570 @code{Stdcall} calling convention is the name of the C routine. The leading
28571 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
28572 the compiler. For instance the Win32 function:
28574 @smallexample
28575 @b{APIENTRY} int get_val (long);
28576 @end smallexample
28578 @noindent
28579 should be imported from Ada as follows:
28581 @smallexample @c ada
28582 @group
28583 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28584 pragma Import (Stdcall, Get_Val);
28585 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
28586 @end group
28587 @end smallexample
28589 @noindent
28590 As for the @code{C} calling convention, when the @code{External_Name}
28591 parameter is missing, it is taken to be the name of the Ada entity in lower
28592 case. If instead of writing the above import pragma you write:
28594 @smallexample @c ada
28595 @group
28596 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28597 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
28598 @end group
28599 @end smallexample
28601 @noindent
28602 then the imported routine is @code{_retrieve_val@@4}. However, if instead
28603 of specifying the @code{External_Name} parameter you specify the
28604 @code{Link_Name} as in the following example:
28606 @smallexample @c ada
28607 @group
28608 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28609 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
28610 @end group
28611 @end smallexample
28613 @noindent
28614 then the imported routine is @code{retrieve_val}, that is, there is no
28615 decoration at all. No leading underscore and no Stdcall suffix
28616 @code{@@}@code{@var{nn}}.
28618 @noindent
28619 This is especially important as in some special cases a DLL's entry
28620 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
28621 name generated for a call has it.
28623 @noindent
28624 It is also possible to import variables defined in a DLL by using an
28625 import pragma for a variable. As an example, if a DLL contains a
28626 variable defined as:
28628 @smallexample
28629 int my_var;
28630 @end smallexample
28632 @noindent
28633 then, to access this variable from Ada you should write:
28635 @smallexample @c ada
28636 @group
28637 My_Var : Interfaces.C.int;
28638 pragma Import (Stdcall, My_Var);
28639 @end group
28640 @end smallexample
28642 @noindent
28643 Note that to ease building cross-platform bindings this convention
28644 will be handled as a @code{C} calling convention on non-Windows platforms.
28646 @node Win32 Calling Convention
28647 @subsection @code{Win32} Calling Convention
28649 @noindent
28650 This convention, which is GNAT-specific is fully equivalent to the
28651 @code{Stdcall} calling convention described above.
28653 @node DLL Calling Convention
28654 @subsection @code{DLL} Calling Convention
28656 @noindent
28657 This convention, which is GNAT-specific is fully equivalent to the
28658 @code{Stdcall} calling convention described above.
28660 @node Introduction to Dynamic Link Libraries (DLLs)
28661 @section Introduction to Dynamic Link Libraries (DLLs)
28662 @findex DLL
28664 @noindent
28665 A Dynamically Linked Library (DLL) is a library that can be shared by
28666 several applications running under Windows. A DLL can contain any number of
28667 routines and variables.
28669 One advantage of DLLs is that you can change and enhance them without
28670 forcing all the applications that depend on them to be relinked or
28671 recompiled. However, you should be aware than all calls to DLL routines are
28672 slower since, as you will understand below, such calls are indirect.
28674 To illustrate the remainder of this section, suppose that an application
28675 wants to use the services of a DLL @file{API.dll}. To use the services
28676 provided by @file{API.dll} you must statically link against the DLL or
28677 an import library which contains a jump table with an entry for each
28678 routine and variable exported by the DLL. In the Microsoft world this
28679 import library is called @file{API.lib}. When using GNAT this import
28680 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
28681 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
28683 After you have linked your application with the DLL or the import library
28684 and you run your application, here is what happens:
28686 @enumerate
28687 @item
28688 Your application is loaded into memory.
28690 @item
28691 The DLL @file{API.dll} is mapped into the address space of your
28692 application. This means that:
28694 @itemize @bullet
28695 @item
28696 The DLL will use the stack of the calling thread.
28698 @item
28699 The DLL will use the virtual address space of the calling process.
28701 @item
28702 The DLL will allocate memory from the virtual address space of the calling
28703 process.
28705 @item
28706 Handles (pointers) can be safely exchanged between routines in the DLL
28707 routines and routines in the application using the DLL.
28708 @end itemize
28710 @item
28711 The entries in the jump table (from the import library @file{libAPI.dll.a}
28712 or @file{API.lib} or automatically created when linking against a DLL)
28713 which is part of your application are initialized with the addresses
28714 of the routines and variables in @file{API.dll}.
28716 @item
28717 If present in @file{API.dll}, routines @code{DllMain} or
28718 @code{DllMainCRTStartup} are invoked. These routines typically contain
28719 the initialization code needed for the well-being of the routines and
28720 variables exported by the DLL.
28721 @end enumerate
28723 @noindent
28724 There is an additional point which is worth mentioning. In the Windows
28725 world there are two kind of DLLs: relocatable and non-relocatable
28726 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
28727 in the target application address space. If the addresses of two
28728 non-relocatable DLLs overlap and these happen to be used by the same
28729 application, a conflict will occur and the application will run
28730 incorrectly. Hence, when possible, it is always preferable to use and
28731 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
28732 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
28733 User's Guide) removes the debugging symbols from the DLL but the DLL can
28734 still be relocated.
28736 As a side note, an interesting difference between Microsoft DLLs and
28737 Unix shared libraries, is the fact that on most Unix systems all public
28738 routines are exported by default in a Unix shared library, while under
28739 Windows it is possible (but not required) to list exported routines in
28740 a definition file (@pxref{The Definition File}).
28742 @node Using DLLs with GNAT
28743 @section Using DLLs with GNAT
28745 @menu
28746 * Creating an Ada Spec for the DLL Services::
28747 * Creating an Import Library::
28748 @end menu
28750 @noindent
28751 To use the services of a DLL, say @file{API.dll}, in your Ada application
28752 you must have:
28754 @enumerate
28755 @item
28756 The Ada spec for the routines and/or variables you want to access in
28757 @file{API.dll}. If not available this Ada spec must be built from the C/C++
28758 header files provided with the DLL.
28760 @item
28761 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
28762 mentioned an import library is a statically linked library containing the
28763 import table which will be filled at load time to point to the actual
28764 @file{API.dll} routines. Sometimes you don't have an import library for the
28765 DLL you want to use. The following sections will explain how to build
28766 one. Note that this is optional.
28768 @item
28769 The actual DLL, @file{API.dll}.
28770 @end enumerate
28772 @noindent
28773 Once you have all the above, to compile an Ada application that uses the
28774 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
28775 you simply issue the command
28777 @smallexample
28778 $ gnatmake my_ada_app -largs -lAPI
28779 @end smallexample
28781 @noindent
28782 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
28783 tells the GNAT linker to look for an import library. The linker will
28784 look for a library name in this specific order:
28786 @enumerate
28787 @item @file{libAPI.dll.a}
28788 @item @file{API.dll.a}
28789 @item @file{libAPI.a}
28790 @item @file{API.lib}
28791 @item @file{libAPI.dll}
28792 @item @file{API.dll}
28793 @end enumerate
28795 The first three are the GNU style import libraries. The third is the
28796 Microsoft style import libraries. The last two are the actual DLL names.
28798 Note that if the Ada package spec for @file{API.dll} contains the
28799 following pragma
28801 @smallexample @c ada
28802 pragma Linker_Options ("-lAPI");
28803 @end smallexample
28805 @noindent
28806 you do not have to add @option{-largs -lAPI} at the end of the
28807 @command{gnatmake} command.
28809 If any one of the items above is missing you will have to create it
28810 yourself. The following sections explain how to do so using as an
28811 example a fictitious DLL called @file{API.dll}.
28813 @node Creating an Ada Spec for the DLL Services
28814 @subsection Creating an Ada Spec for the DLL Services
28816 @noindent
28817 A DLL typically comes with a C/C++ header file which provides the
28818 definitions of the routines and variables exported by the DLL. The Ada
28819 equivalent of this header file is a package spec that contains definitions
28820 for the imported entities. If the DLL you intend to use does not come with
28821 an Ada spec you have to generate one such spec yourself. For example if
28822 the header file of @file{API.dll} is a file @file{api.h} containing the
28823 following two definitions:
28825 @smallexample
28826 @group
28827 @cartouche
28828 int some_var;
28829 int get (char *);
28830 @end cartouche
28831 @end group
28832 @end smallexample
28834 @noindent
28835 then the equivalent Ada spec could be:
28837 @smallexample @c ada
28838 @group
28839 @cartouche
28840 with Interfaces.C.Strings;
28841 package API is
28842    use Interfaces;
28844    Some_Var : C.int;
28845    function Get (Str : C.Strings.Chars_Ptr) return C.int;
28847 private
28848    pragma Import (C, Get);
28849    pragma Import (DLL, Some_Var);
28850 end API;
28851 @end cartouche
28852 @end group
28853 @end smallexample
28855 @noindent
28856 Note that a variable is
28857 @strong{always imported with a DLL convention}. A function
28858 can have @code{C} or @code{Stdcall} convention.
28859 (@pxref{Windows Calling Conventions}).
28861 @node Creating an Import Library
28862 @subsection Creating an Import Library
28863 @cindex Import library
28865 @menu
28866 * The Definition File::
28867 * GNAT-Style Import Library::
28868 * Microsoft-Style Import Library::
28869 @end menu
28871 @noindent
28872 If a Microsoft-style import library @file{API.lib} or a GNAT-style
28873 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
28874 with @file{API.dll} you can skip this section. You can also skip this
28875 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
28876 as in this case it is possible to link directly against the
28877 DLL. Otherwise read on.
28879 @node The Definition File
28880 @subsubsection The Definition File
28881 @cindex Definition file
28882 @findex .def
28884 @noindent
28885 As previously mentioned, and unlike Unix systems, the list of symbols
28886 that are exported from a DLL must be provided explicitly in Windows.
28887 The main goal of a definition file is precisely that: list the symbols
28888 exported by a DLL. A definition file (usually a file with a @code{.def}
28889 suffix) has the following structure:
28891 @smallexample
28892 @group
28893 @cartouche
28894 @r{[}LIBRARY @var{name}@r{]}
28895 @r{[}DESCRIPTION @var{string}@r{]}
28896 EXPORTS
28897    @var{symbol1}
28898    @var{symbol2}
28899    @dots{}
28900 @end cartouche
28901 @end group
28902 @end smallexample
28904 @table @code
28905 @item LIBRARY @var{name}
28906 This section, which is optional, gives the name of the DLL.
28908 @item DESCRIPTION @var{string}
28909 This section, which is optional, gives a description string that will be
28910 embedded in the import library.
28912 @item EXPORTS
28913 This section gives the list of exported symbols (procedures, functions or
28914 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
28915 section of @file{API.def} looks like:
28917 @smallexample
28918 @group
28919 @cartouche
28920 EXPORTS
28921    some_var
28922    get
28923 @end cartouche
28924 @end group
28925 @end smallexample
28926 @end table
28928 @noindent
28929 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28930 (@pxref{Windows Calling Conventions}) for a Stdcall
28931 calling convention function in the exported symbols list.
28933 @noindent
28934 There can actually be other sections in a definition file, but these
28935 sections are not relevant to the discussion at hand.
28937 @node GNAT-Style Import Library
28938 @subsubsection GNAT-Style Import Library
28940 @noindent
28941 To create a static import library from @file{API.dll} with the GNAT tools
28942 you should proceed as follows:
28944 @enumerate
28945 @item
28946 Create the definition file @file{API.def} (@pxref{The Definition File}).
28947 For that use the @code{dll2def} tool as follows:
28949 @smallexample
28950 $ dll2def API.dll > API.def
28951 @end smallexample
28953 @noindent
28954 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28955 to standard output the list of entry points in the DLL. Note that if
28956 some routines in the DLL have the @code{Stdcall} convention
28957 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28958 suffix then you'll have to edit @file{api.def} to add it, and specify
28959 @option{-k} to @command{gnatdll} when creating the import library.
28961 @noindent
28962 Here are some hints to find the right @code{@@}@var{nn} suffix.
28964 @enumerate
28965 @item
28966 If you have the Microsoft import library (.lib), it is possible to get
28967 the right symbols by using Microsoft @code{dumpbin} tool (see the
28968 corresponding Microsoft documentation for further details).
28970 @smallexample
28971 $ dumpbin /exports api.lib
28972 @end smallexample
28974 @item
28975 If you have a message about a missing symbol at link time the compiler
28976 tells you what symbol is expected. You just have to go back to the
28977 definition file and add the right suffix.
28978 @end enumerate
28980 @item
28981 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28982 (@pxref{Using gnatdll}) as follows:
28984 @smallexample
28985 $ gnatdll -e API.def -d API.dll
28986 @end smallexample
28988 @noindent
28989 @code{gnatdll} takes as input a definition file @file{API.def} and the
28990 name of the DLL containing the services listed in the definition file
28991 @file{API.dll}. The name of the static import library generated is
28992 computed from the name of the definition file as follows: if the
28993 definition file name is @var{xyz}@code{.def}, the import library name will
28994 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
28995 @option{-e} could have been removed because the name of the definition
28996 file (before the ``@code{.def}'' suffix) is the same as the name of the
28997 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
28998 @end enumerate
29000 @node Microsoft-Style Import Library
29001 @subsubsection Microsoft-Style Import Library
29003 @noindent
29004 With GNAT you can either use a GNAT-style or Microsoft-style import
29005 library. A Microsoft import library is needed only if you plan to make an
29006 Ada DLL available to applications developed with Microsoft
29007 tools (@pxref{Mixed-Language Programming on Windows}).
29009 To create a Microsoft-style import library for @file{API.dll} you
29010 should proceed as follows:
29012 @enumerate
29013 @item
29014 Create the definition file @file{API.def} from the DLL. For this use either
29015 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
29016 tool (see the corresponding Microsoft documentation for further details).
29018 @item
29019 Build the actual import library using Microsoft's @code{lib} utility:
29021 @smallexample
29022 $ lib -machine:IX86 -def:API.def -out:API.lib
29023 @end smallexample
29025 @noindent
29026 If you use the above command the definition file @file{API.def} must
29027 contain a line giving the name of the DLL:
29029 @smallexample
29030 LIBRARY      "API"
29031 @end smallexample
29033 @noindent
29034 See the Microsoft documentation for further details about the usage of
29035 @code{lib}.
29036 @end enumerate
29038 @node Building DLLs with GNAT Project files
29039 @section Building DLLs with GNAT Project files
29040 @cindex DLLs, building
29042 @noindent
29043 There is nothing specific to Windows in the build process.
29044 @pxref{Library Projects}.
29046 @noindent
29047 Due to a system limitation, it is not possible under Windows to create threads
29048 when inside the @code{DllMain} routine which is used for auto-initialization
29049 of shared libraries, so it is not possible to have library level tasks in SALs.
29051 @node Building DLLs with GNAT
29052 @section Building DLLs with GNAT
29053 @cindex DLLs, building
29055 @noindent
29056 This section explain how to build DLLs using the GNAT built-in DLL
29057 support. With the following procedure it is straight forward to build
29058 and use DLLs with GNAT.
29060 @enumerate
29062 @item building object files
29064 The first step is to build all objects files that are to be included
29065 into the DLL. This is done by using the standard @command{gnatmake} tool.
29067 @item building the DLL
29069 To build the DLL you must use @command{gcc}'s @option{-shared} and
29070 @option{-shared-libgcc} options. It is quite simple to use this method:
29072 @smallexample
29073 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
29074 @end smallexample
29076 It is important to note that in this case all symbols found in the
29077 object files are automatically exported. It is possible to restrict
29078 the set of symbols to export by passing to @command{gcc} a definition
29079 file, @pxref{The Definition File}. For example:
29081 @smallexample
29082 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
29083 @end smallexample
29085 If you use a definition file you must export the elaboration procedures
29086 for every package that required one. Elaboration procedures are named
29087 using the package name followed by "_E".
29089 @item preparing DLL to be used
29091 For the DLL to be used by client programs the bodies must be hidden
29092 from it and the .ali set with read-only attribute. This is very important
29093 otherwise GNAT will recompile all packages and will not actually use
29094 the code in the DLL. For example:
29096 @smallexample
29097 $ mkdir apilib
29098 $ copy *.ads *.ali api.dll apilib
29099 $ attrib +R apilib\*.ali
29100 @end smallexample
29102 @end enumerate
29104 At this point it is possible to use the DLL by directly linking
29105 against it. Note that you must use the GNAT shared runtime when using
29106 GNAT shared libraries. This is achieved by using @option{-shared} binder's
29107 option.
29109 @smallexample
29110 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
29111 @end smallexample
29113 @node Building DLLs with gnatdll
29114 @section Building DLLs with gnatdll
29115 @cindex DLLs, building
29117 @menu
29118 * Limitations When Using Ada DLLs from Ada::
29119 * Exporting Ada Entities::
29120 * Ada DLLs and Elaboration::
29121 * Ada DLLs and Finalization::
29122 * Creating a Spec for Ada DLLs::
29123 * Creating the Definition File::
29124 * Using gnatdll::
29125 @end menu
29127 @noindent
29128 Note that it is preferred to use GNAT Project files
29129 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
29130 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
29132 This section explains how to build DLLs containing Ada code using
29133 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
29134 remainder of this section.
29136 The steps required to build an Ada DLL that is to be used by Ada as well as
29137 non-Ada applications are as follows:
29139 @enumerate
29140 @item
29141 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
29142 @code{Stdcall} calling convention to avoid any Ada name mangling for the
29143 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
29144 skip this step if you plan to use the Ada DLL only from Ada applications.
29146 @item
29147 Your Ada code must export an initialization routine which calls the routine
29148 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
29149 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
29150 routine exported by the Ada DLL must be invoked by the clients of the DLL
29151 to initialize the DLL.
29153 @item
29154 When useful, the DLL should also export a finalization routine which calls
29155 routine @code{adafinal} generated by @command{gnatbind} to perform the
29156 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
29157 The finalization routine exported by the Ada DLL must be invoked by the
29158 clients of the DLL when the DLL services are no further needed.
29160 @item
29161 You must provide a spec for the services exported by the Ada DLL in each
29162 of the programming languages to which you plan to make the DLL available.
29164 @item
29165 You must provide a definition file listing the exported entities
29166 (@pxref{The Definition File}).
29168 @item
29169 Finally you must use @code{gnatdll} to produce the DLL and the import
29170 library (@pxref{Using gnatdll}).
29171 @end enumerate
29173 @noindent
29174 Note that a relocatable DLL stripped using the @code{strip}
29175 binutils tool will not be relocatable anymore. To build a DLL without
29176 debug information pass @code{-largs -s} to @code{gnatdll}. This
29177 restriction does not apply to a DLL built using a Library Project.
29178 @pxref{Library Projects}.
29180 @node Limitations When Using Ada DLLs from Ada
29181 @subsection Limitations When Using Ada DLLs from Ada
29183 @noindent
29184 When using Ada DLLs from Ada applications there is a limitation users
29185 should be aware of. Because on Windows the GNAT run time is not in a DLL of
29186 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
29187 each Ada DLL includes the services of the GNAT run time that are necessary
29188 to the Ada code inside the DLL. As a result, when an Ada program uses an
29189 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
29190 one in the main program.
29192 It is therefore not possible to exchange GNAT run-time objects between the
29193 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
29194 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
29195 types, etc.
29197 It is completely safe to exchange plain elementary, array or record types,
29198 Windows object handles, etc.
29200 @node Exporting Ada Entities
29201 @subsection Exporting Ada Entities
29202 @cindex Export table
29204 @noindent
29205 Building a DLL is a way to encapsulate a set of services usable from any
29206 application. As a result, the Ada entities exported by a DLL should be
29207 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
29208 any Ada name mangling. As an example here is an Ada package
29209 @code{API}, spec and body, exporting two procedures, a function, and a
29210 variable:
29212 @smallexample @c ada
29213 @group
29214 @cartouche
29215 with Interfaces.C; use Interfaces;
29216 package API is
29217    Count : C.int := 0;
29218    function Factorial (Val : C.int) return C.int;
29220    procedure Initialize_API;
29221    procedure Finalize_API;
29222    --  Initialization & Finalization routines. More in the next section.
29223 private
29224    pragma Export (C, Initialize_API);
29225    pragma Export (C, Finalize_API);
29226    pragma Export (C, Count);
29227    pragma Export (C, Factorial);
29228 end API;
29229 @end cartouche
29230 @end group
29231 @end smallexample
29233 @smallexample @c ada
29234 @group
29235 @cartouche
29236 package body API is
29237    function Factorial (Val : C.int) return C.int is
29238       Fact : C.int := 1;
29239    begin
29240       Count := Count + 1;
29241       for K in 1 .. Val loop
29242          Fact := Fact * K;
29243       end loop;
29244       return Fact;
29245    end Factorial;
29247    procedure Initialize_API is
29248       procedure Adainit;
29249       pragma Import (C, Adainit);
29250    begin
29251       Adainit;
29252    end Initialize_API;
29254    procedure Finalize_API is
29255       procedure Adafinal;
29256       pragma Import (C, Adafinal);
29257    begin
29258       Adafinal;
29259    end Finalize_API;
29260 end API;
29261 @end cartouche
29262 @end group
29263 @end smallexample
29265 @noindent
29266 If the Ada DLL you are building will only be used by Ada applications
29267 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
29268 convention. As an example, the previous package could be written as
29269 follows:
29271 @smallexample @c ada
29272 @group
29273 @cartouche
29274 package API is
29275    Count : Integer := 0;
29276    function Factorial (Val : Integer) return Integer;
29278    procedure Initialize_API;
29279    procedure Finalize_API;
29280    --  Initialization and Finalization routines.
29281 end API;
29282 @end cartouche
29283 @end group
29284 @end smallexample
29286 @smallexample @c ada
29287 @group
29288 @cartouche
29289 package body API is
29290    function Factorial (Val : Integer) return Integer is
29291       Fact : Integer := 1;
29292    begin
29293       Count := Count + 1;
29294       for K in 1 .. Val loop
29295          Fact := Fact * K;
29296       end loop;
29297       return Fact;
29298    end Factorial;
29300    @dots{}
29301    --  The remainder of this package body is unchanged.
29302 end API;
29303 @end cartouche
29304 @end group
29305 @end smallexample
29307 @noindent
29308 Note that if you do not export the Ada entities with a @code{C} or
29309 @code{Stdcall} convention you will have to provide the mangled Ada names
29310 in the definition file of the Ada DLL
29311 (@pxref{Creating the Definition File}).
29313 @node Ada DLLs and Elaboration
29314 @subsection Ada DLLs and Elaboration
29315 @cindex DLLs and elaboration
29317 @noindent
29318 The DLL that you are building contains your Ada code as well as all the
29319 routines in the Ada library that are needed by it. The first thing a
29320 user of your DLL must do is elaborate the Ada code
29321 (@pxref{Elaboration Order Handling in GNAT}).
29323 To achieve this you must export an initialization routine
29324 (@code{Initialize_API} in the previous example), which must be invoked
29325 before using any of the DLL services. This elaboration routine must call
29326 the Ada elaboration routine @code{adainit} generated by the GNAT binder
29327 (@pxref{Binding with Non-Ada Main Programs}). See the body of
29328 @code{Initialize_Api} for an example. Note that the GNAT binder is
29329 automatically invoked during the DLL build process by the @code{gnatdll}
29330 tool (@pxref{Using gnatdll}).
29332 When a DLL is loaded, Windows systematically invokes a routine called
29333 @code{DllMain}. It would therefore be possible to call @code{adainit}
29334 directly from @code{DllMain} without having to provide an explicit
29335 initialization routine. Unfortunately, it is not possible to call
29336 @code{adainit} from the @code{DllMain} if your program has library level
29337 tasks because access to the @code{DllMain} entry point is serialized by
29338 the system (that is, only a single thread can execute ``through'' it at a
29339 time), which means that the GNAT run time will deadlock waiting for the
29340 newly created task to complete its initialization.
29342 @node Ada DLLs and Finalization
29343 @subsection Ada DLLs and Finalization
29344 @cindex DLLs and finalization
29346 @noindent
29347 When the services of an Ada DLL are no longer needed, the client code should
29348 invoke the DLL finalization routine, if available. The DLL finalization
29349 routine is in charge of releasing all resources acquired by the DLL. In the
29350 case of the Ada code contained in the DLL, this is achieved by calling
29351 routine @code{adafinal} generated by the GNAT binder
29352 (@pxref{Binding with Non-Ada Main Programs}).
29353 See the body of @code{Finalize_Api} for an
29354 example. As already pointed out the GNAT binder is automatically invoked
29355 during the DLL build process by the @code{gnatdll} tool
29356 (@pxref{Using gnatdll}).
29358 @node Creating a Spec for Ada DLLs
29359 @subsection Creating a Spec for Ada DLLs
29361 @noindent
29362 To use the services exported by the Ada DLL from another programming
29363 language (e.g.@: C), you have to translate the specs of the exported Ada
29364 entities in that language. For instance in the case of @code{API.dll},
29365 the corresponding C header file could look like:
29367 @smallexample
29368 @group
29369 @cartouche
29370 extern int *_imp__count;
29371 #define count (*_imp__count)
29372 int factorial (int);
29373 @end cartouche
29374 @end group
29375 @end smallexample
29377 @noindent
29378 It is important to understand that when building an Ada DLL to be used by
29379 other Ada applications, you need two different specs for the packages
29380 contained in the DLL: one for building the DLL and the other for using
29381 the DLL. This is because the @code{DLL} calling convention is needed to
29382 use a variable defined in a DLL, but when building the DLL, the variable
29383 must have either the @code{Ada} or @code{C} calling convention. As an
29384 example consider a DLL comprising the following package @code{API}:
29386 @smallexample @c ada
29387 @group
29388 @cartouche
29389 package API is
29390    Count : Integer := 0;
29391    @dots{}
29392    --  Remainder of the package omitted.
29393 end API;
29394 @end cartouche
29395 @end group
29396 @end smallexample
29398 @noindent
29399 After producing a DLL containing package @code{API}, the spec that
29400 must be used to import @code{API.Count} from Ada code outside of the
29401 DLL is:
29403 @smallexample @c ada
29404 @group
29405 @cartouche
29406 package API is
29407    Count : Integer;
29408    pragma Import (DLL, Count);
29409 end API;
29410 @end cartouche
29411 @end group
29412 @end smallexample
29414 @node Creating the Definition File
29415 @subsection Creating the Definition File
29417 @noindent
29418 The definition file is the last file needed to build the DLL. It lists
29419 the exported symbols. As an example, the definition file for a DLL
29420 containing only package @code{API} (where all the entities are exported
29421 with a @code{C} calling convention) is:
29423 @smallexample
29424 @group
29425 @cartouche
29426 EXPORTS
29427     count
29428     factorial
29429     finalize_api
29430     initialize_api
29431 @end cartouche
29432 @end group
29433 @end smallexample
29435 @noindent
29436 If the @code{C} calling convention is missing from package @code{API},
29437 then the definition file contains the mangled Ada names of the above
29438 entities, which in this case are:
29440 @smallexample
29441 @group
29442 @cartouche
29443 EXPORTS
29444     api__count
29445     api__factorial
29446     api__finalize_api
29447     api__initialize_api
29448 @end cartouche
29449 @end group
29450 @end smallexample
29452 @node Using gnatdll
29453 @subsection Using @code{gnatdll}
29454 @findex gnatdll
29456 @menu
29457 * gnatdll Example::
29458 * gnatdll behind the Scenes::
29459 * Using dlltool::
29460 @end menu
29462 @noindent
29463 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
29464 and non-Ada sources that make up your DLL have been compiled.
29465 @code{gnatdll} is actually in charge of two distinct tasks: build the
29466 static import library for the DLL and the actual DLL. The form of the
29467 @code{gnatdll} command is
29469 @smallexample
29470 @cartouche
29471 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29472 @c Expanding @ovar macro inline (explanation in macro def comments)
29473 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29474 @end cartouche
29475 @end smallexample
29477 @noindent
29478 where @var{list-of-files} is a list of ALI and object files. The object
29479 file list must be the exact list of objects corresponding to the non-Ada
29480 sources whose services are to be included in the DLL. The ALI file list
29481 must be the exact list of ALI files for the corresponding Ada sources
29482 whose services are to be included in the DLL. If @var{list-of-files} is
29483 missing, only the static import library is generated.
29485 @noindent
29486 You may specify any of the following switches to @code{gnatdll}:
29488 @table @code
29489 @c @item -a@ovar{address}
29490 @c Expanding @ovar macro inline (explanation in macro def comments)
29491 @item -a@r{[}@var{address}@r{]}
29492 @cindex @option{-a} (@code{gnatdll})
29493 Build a non-relocatable DLL at @var{address}. If @var{address} is not
29494 specified the default address @var{0x11000000} will be used. By default,
29495 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
29496 advise the reader to build relocatable DLL.
29498 @item -b @var{address}
29499 @cindex @option{-b} (@code{gnatdll})
29500 Set the relocatable DLL base address. By default the address is
29501 @code{0x11000000}.
29503 @item -bargs @var{opts}
29504 @cindex @option{-bargs} (@code{gnatdll})
29505 Binder options. Pass @var{opts} to the binder.
29507 @item -d @var{dllfile}
29508 @cindex @option{-d} (@code{gnatdll})
29509 @var{dllfile} is the name of the DLL. This switch must be present for
29510 @code{gnatdll} to do anything. The name of the generated import library is
29511 obtained algorithmically from @var{dllfile} as shown in the following
29512 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
29513 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
29514 by option @option{-e}) is obtained algorithmically from @var{dllfile}
29515 as shown in the following example:
29516 if @var{dllfile} is @code{xyz.dll}, the definition
29517 file used is @code{xyz.def}.
29519 @item -e @var{deffile}
29520 @cindex @option{-e} (@code{gnatdll})
29521 @var{deffile} is the name of the definition file.
29523 @item -g
29524 @cindex @option{-g} (@code{gnatdll})
29525 Generate debugging information. This information is stored in the object
29526 file and copied from there to the final DLL file by the linker,
29527 where it can be read by the debugger. You must use the
29528 @option{-g} switch if you plan on using the debugger or the symbolic
29529 stack traceback.
29531 @item -h
29532 @cindex @option{-h} (@code{gnatdll})
29533 Help mode. Displays @code{gnatdll} switch usage information.
29535 @item -Idir
29536 @cindex @option{-I} (@code{gnatdll})
29537 Direct @code{gnatdll} to search the @var{dir} directory for source and
29538 object files needed to build the DLL.
29539 (@pxref{Search Paths and the Run-Time Library (RTL)}).
29541 @item -k
29542 @cindex @option{-k} (@code{gnatdll})
29543 Removes the @code{@@}@var{nn} suffix from the import library's exported
29544 names, but keeps them for the link names. You must specify this
29545 option if you want to use a @code{Stdcall} function in a DLL for which
29546 the @code{@@}@var{nn} suffix has been removed. This is the case for most
29547 of the Windows NT DLL for example. This option has no effect when
29548 @option{-n} option is specified.
29550 @item -l @var{file}
29551 @cindex @option{-l} (@code{gnatdll})
29552 The list of ALI and object files used to build the DLL are listed in
29553 @var{file}, instead of being given in the command line. Each line in
29554 @var{file} contains the name of an ALI or object file.
29556 @item -n
29557 @cindex @option{-n} (@code{gnatdll})
29558 No Import. Do not create the import library.
29560 @item -q
29561 @cindex @option{-q} (@code{gnatdll})
29562 Quiet mode. Do not display unnecessary messages.
29564 @item -v
29565 @cindex @option{-v} (@code{gnatdll})
29566 Verbose mode. Display extra information.
29568 @item -largs @var{opts}
29569 @cindex @option{-largs} (@code{gnatdll})
29570 Linker options. Pass @var{opts} to the linker.
29571 @end table
29573 @node gnatdll Example
29574 @subsubsection @code{gnatdll} Example
29576 @noindent
29577 As an example the command to build a relocatable DLL from @file{api.adb}
29578 once @file{api.adb} has been compiled and @file{api.def} created is
29580 @smallexample
29581 $ gnatdll -d api.dll api.ali
29582 @end smallexample
29584 @noindent
29585 The above command creates two files: @file{libapi.dll.a} (the import
29586 library) and @file{api.dll} (the actual DLL). If you want to create
29587 only the DLL, just type:
29589 @smallexample
29590 $ gnatdll -d api.dll -n api.ali
29591 @end smallexample
29593 @noindent
29594 Alternatively if you want to create just the import library, type:
29596 @smallexample
29597 $ gnatdll -d api.dll
29598 @end smallexample
29600 @node gnatdll behind the Scenes
29601 @subsubsection @code{gnatdll} behind the Scenes
29603 @noindent
29604 This section details the steps involved in creating a DLL. @code{gnatdll}
29605 does these steps for you. Unless you are interested in understanding what
29606 goes on behind the scenes, you should skip this section.
29608 We use the previous example of a DLL containing the Ada package @code{API},
29609 to illustrate the steps necessary to build a DLL. The starting point is a
29610 set of objects that will make up the DLL and the corresponding ALI
29611 files. In the case of this example this means that @file{api.o} and
29612 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
29613 the following:
29615 @enumerate
29616 @item
29617 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
29618 the information necessary to generate relocation information for the
29619 DLL.
29621 @smallexample
29622 @group
29623 $ gnatbind -n api
29624 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
29625 @end group
29626 @end smallexample
29628 @noindent
29629 In addition to the base file, the @command{gnatlink} command generates an
29630 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
29631 asks @command{gnatlink} to generate the routines @code{DllMain} and
29632 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
29633 is loaded into memory.
29635 @item
29636 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
29637 export table (@file{api.exp}). The export table contains the relocation
29638 information in a form which can be used during the final link to ensure
29639 that the Windows loader is able to place the DLL anywhere in memory.
29641 @smallexample
29642 @group
29643 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29644           --output-exp api.exp
29645 @end group
29646 @end smallexample
29648 @item
29649 @code{gnatdll} builds the base file using the new export table. Note that
29650 @command{gnatbind} must be called once again since the binder generated file
29651 has been deleted during the previous call to @command{gnatlink}.
29653 @smallexample
29654 @group
29655 $ gnatbind -n api
29656 $ gnatlink api -o api.jnk api.exp -mdll
29657       -Wl,--base-file,api.base
29658 @end group
29659 @end smallexample
29661 @item
29662 @code{gnatdll} builds the new export table using the new base file and
29663 generates the DLL import library @file{libAPI.dll.a}.
29665 @smallexample
29666 @group
29667 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29668           --output-exp api.exp --output-lib libAPI.a
29669 @end group
29670 @end smallexample
29672 @item
29673 Finally @code{gnatdll} builds the relocatable DLL using the final export
29674 table.
29676 @smallexample
29677 @group
29678 $ gnatbind -n api
29679 $ gnatlink api api.exp -o api.dll -mdll
29680 @end group
29681 @end smallexample
29682 @end enumerate
29684 @node Using dlltool
29685 @subsubsection Using @code{dlltool}
29687 @noindent
29688 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
29689 DLLs and static import libraries. This section summarizes the most
29690 common @code{dlltool} switches. The form of the @code{dlltool} command
29693 @smallexample
29694 @c $ dlltool @ovar{switches}
29695 @c Expanding @ovar macro inline (explanation in macro def comments)
29696 $ dlltool @r{[}@var{switches}@r{]}
29697 @end smallexample
29699 @noindent
29700 @code{dlltool} switches include:
29702 @table @option
29703 @item --base-file @var{basefile}
29704 @cindex @option{--base-file} (@command{dlltool})
29705 Read the base file @var{basefile} generated by the linker. This switch
29706 is used to create a relocatable DLL.
29708 @item --def @var{deffile}
29709 @cindex @option{--def} (@command{dlltool})
29710 Read the definition file.
29712 @item --dllname @var{name}
29713 @cindex @option{--dllname} (@command{dlltool})
29714 Gives the name of the DLL. This switch is used to embed the name of the
29715 DLL in the static import library generated by @code{dlltool} with switch
29716 @option{--output-lib}.
29718 @item -k
29719 @cindex @option{-k} (@command{dlltool})
29720 Kill @code{@@}@var{nn} from exported names
29721 (@pxref{Windows Calling Conventions}
29722 for a discussion about @code{Stdcall}-style symbols.
29724 @item --help
29725 @cindex @option{--help} (@command{dlltool})
29726 Prints the @code{dlltool} switches with a concise description.
29728 @item --output-exp @var{exportfile}
29729 @cindex @option{--output-exp} (@command{dlltool})
29730 Generate an export file @var{exportfile}. The export file contains the
29731 export table (list of symbols in the DLL) and is used to create the DLL.
29733 @item --output-lib @var{libfile}
29734 @cindex @option{--output-lib} (@command{dlltool})
29735 Generate a static import library @var{libfile}.
29737 @item -v
29738 @cindex @option{-v} (@command{dlltool})
29739 Verbose mode.
29741 @item --as @var{assembler-name}
29742 @cindex @option{--as} (@command{dlltool})
29743 Use @var{assembler-name} as the assembler. The default is @code{as}.
29744 @end table
29746 @node GNAT and Windows Resources
29747 @section GNAT and Windows Resources
29748 @cindex Resources, windows
29750 @menu
29751 * Building Resources::
29752 * Compiling Resources::
29753 * Using Resources::
29754 @end menu
29756 @noindent
29757 Resources are an easy way to add Windows specific objects to your
29758 application. The objects that can be added as resources include:
29760 @itemize @bullet
29761 @item menus
29763 @item accelerators
29765 @item dialog boxes
29767 @item string tables
29769 @item bitmaps
29771 @item cursors
29773 @item icons
29775 @item fonts
29777 @item version information
29778 @end itemize
29780 For example, a version information resource can be defined as follow and
29781 embedded into an executable or DLL:
29783 A version information resource can be used to embed information into an
29784 executable or a DLL. These information can be viewed using the file properties
29785 from the Windows Explorer. Here is an example of a version information
29786 resource:
29788 @smallexample
29789 @group
29790 1 VERSIONINFO
29791 FILEVERSION     1,0,0,0
29792 PRODUCTVERSION  1,0,0,0
29793 BEGIN
29794   BLOCK "StringFileInfo"
29795   BEGIN
29796     BLOCK "080904E4"
29797     BEGIN
29798       VALUE "CompanyName", "My Company Name"
29799       VALUE "FileDescription", "My application"
29800       VALUE "FileVersion", "1.0"
29801       VALUE "InternalName", "my_app"
29802       VALUE "LegalCopyright", "My Name"
29803       VALUE "OriginalFilename", "my_app.exe"
29804       VALUE "ProductName", "My App"
29805       VALUE "ProductVersion", "1.0"
29806     END
29807   END
29809   BLOCK "VarFileInfo"
29810   BEGIN
29811     VALUE "Translation", 0x809, 1252
29812   END
29814 @end group
29815 @end smallexample
29817 The value @code{0809} (langID) is for the U.K English language and
29818 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
29819 multilingual.
29821 @noindent
29822 This section explains how to build, compile and use resources. Note that this
29823 section does not cover all resource objects, for a complete description see
29824 the corresponding Microsoft documentation.
29826 @node Building Resources
29827 @subsection Building Resources
29828 @cindex Resources, building
29830 @noindent
29831 A resource file is an ASCII file. By convention resource files have an
29832 @file{.rc} extension.
29833 The easiest way to build a resource file is to use Microsoft tools
29834 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
29835 @code{dlgedit.exe} to build dialogs.
29836 It is always possible to build an @file{.rc} file yourself by writing a
29837 resource script.
29839 It is not our objective to explain how to write a resource file. A
29840 complete description of the resource script language can be found in the
29841 Microsoft documentation.
29843 @node Compiling Resources
29844 @subsection Compiling Resources
29845 @findex rc
29846 @findex windres
29847 @cindex Resources, compiling
29849 @noindent
29850 This section describes how to build a GNAT-compatible (COFF) object file
29851 containing the resources. This is done using the Resource Compiler
29852 @code{windres} as follows:
29854 @smallexample
29855 $ windres -i myres.rc -o myres.o
29856 @end smallexample
29858 @noindent
29859 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
29860 file. You can specify an alternate preprocessor (usually named
29861 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
29862 parameter. A list of all possible options may be obtained by entering
29863 the command @code{windres} @option{--help}.
29865 It is also possible to use the Microsoft resource compiler @code{rc.exe}
29866 to produce a @file{.res} file (binary resource file). See the
29867 corresponding Microsoft documentation for further details. In this case
29868 you need to use @code{windres} to translate the @file{.res} file to a
29869 GNAT-compatible object file as follows:
29871 @smallexample
29872 $ windres -i myres.res -o myres.o
29873 @end smallexample
29875 @node Using Resources
29876 @subsection Using Resources
29877 @cindex Resources, using
29879 @noindent
29880 To include the resource file in your program just add the
29881 GNAT-compatible object file for the resource(s) to the linker
29882 arguments. With @command{gnatmake} this is done by using the @option{-largs}
29883 option:
29885 @smallexample
29886 $ gnatmake myprog -largs myres.o
29887 @end smallexample
29889 @node Debugging a DLL
29890 @section Debugging a DLL
29891 @cindex DLL debugging
29893 @menu
29894 * Program and DLL Both Built with GCC/GNAT::
29895 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
29896 @end menu
29898 @noindent
29899 Debugging a DLL is similar to debugging a standard program. But
29900 we have to deal with two different executable parts: the DLL and the
29901 program that uses it. We have the following four possibilities:
29903 @enumerate 1
29904 @item
29905 The program and the DLL are built with @code{GCC/GNAT}.
29906 @item
29907 The program is built with foreign tools and the DLL is built with
29908 @code{GCC/GNAT}.
29909 @item
29910 The program is built with @code{GCC/GNAT} and the DLL is built with
29911 foreign tools.
29912 @end enumerate
29914 @noindent
29915 In this section we address only cases one and two above.
29916 There is no point in trying to debug
29917 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
29918 information in it. To do so you must use a debugger compatible with the
29919 tools suite used to build the DLL.
29921 @node Program and DLL Both Built with GCC/GNAT
29922 @subsection Program and DLL Both Built with GCC/GNAT
29924 @noindent
29925 This is the simplest case. Both the DLL and the program have @code{GDB}
29926 compatible debugging information. It is then possible to break anywhere in
29927 the process. Let's suppose here that the main procedure is named
29928 @code{ada_main} and that in the DLL there is an entry point named
29929 @code{ada_dll}.
29931 @noindent
29932 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29933 program must have been built with the debugging information (see GNAT -g
29934 switch). Here are the step-by-step instructions for debugging it:
29936 @enumerate 1
29937 @item Launch @code{GDB} on the main program.
29939 @smallexample
29940 $ gdb -nw ada_main
29941 @end smallexample
29943 @item Start the program and stop at the beginning of the main procedure
29945 @smallexample
29946 (gdb) start
29947 @end smallexample
29949 @noindent
29950 This step is required to be able to set a breakpoint inside the DLL. As long
29951 as the program is not run, the DLL is not loaded. This has the
29952 consequence that the DLL debugging information is also not loaded, so it is not
29953 possible to set a breakpoint in the DLL.
29955 @item Set a breakpoint inside the DLL
29957 @smallexample
29958 (gdb) break ada_dll
29959 (gdb) cont
29960 @end smallexample
29962 @end enumerate
29964 @noindent
29965 At this stage a breakpoint is set inside the DLL. From there on
29966 you can use the standard approach to debug the whole program
29967 (@pxref{Running and Debugging Ada Programs}).
29969 @ignore
29970 @c This used to work, probably because the DLLs were non-relocatable
29971 @c keep this section around until the problem is sorted out.
29973 To break on the @code{DllMain} routine it is not possible to follow
29974 the procedure above. At the time the program stop on @code{ada_main}
29975 the @code{DllMain} routine as already been called. Either you can use
29976 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29978 @enumerate 1
29979 @item Launch @code{GDB} on the main program.
29981 @smallexample
29982 $ gdb ada_main
29983 @end smallexample
29985 @item Load DLL symbols
29987 @smallexample
29988 (gdb) add-sym api.dll
29989 @end smallexample
29991 @item Set a breakpoint inside the DLL
29993 @smallexample
29994 (gdb) break ada_dll.adb:45
29995 @end smallexample
29997 Note that at this point it is not possible to break using the routine symbol
29998 directly as the program is not yet running. The solution is to break
29999 on the proper line (break in @file{ada_dll.adb} line 45).
30001 @item Start the program
30003 @smallexample
30004 (gdb) run
30005 @end smallexample
30007 @end enumerate
30008 @end ignore
30010 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
30011 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
30013 @menu
30014 * Debugging the DLL Directly::
30015 * Attaching to a Running Process::
30016 @end menu
30018 @noindent
30019 In this case things are slightly more complex because it is not possible to
30020 start the main program and then break at the beginning to load the DLL and the
30021 associated DLL debugging information. It is not possible to break at the
30022 beginning of the program because there is no @code{GDB} debugging information,
30023 and therefore there is no direct way of getting initial control. This
30024 section addresses this issue by describing some methods that can be used
30025 to break somewhere in the DLL to debug it.
30027 @noindent
30028 First suppose that the main procedure is named @code{main} (this is for
30029 example some C code built with Microsoft Visual C) and that there is a
30030 DLL named @code{test.dll} containing an Ada entry point named
30031 @code{ada_dll}.
30033 @noindent
30034 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
30035 been built with debugging information (see GNAT -g option).
30037 @node Debugging the DLL Directly
30038 @subsubsection Debugging the DLL Directly
30040 @enumerate 1
30041 @item
30042 Find out the executable starting address
30044 @smallexample
30045 $ objdump --file-header main.exe
30046 @end smallexample
30048 The starting address is reported on the last line. For example:
30050 @smallexample
30051 main.exe:     file format pei-i386
30052 architecture: i386, flags 0x0000010a:
30053 EXEC_P, HAS_DEBUG, D_PAGED
30054 start address 0x00401010
30055 @end smallexample
30057 @item
30058 Launch the debugger on the executable.
30060 @smallexample
30061 $ gdb main.exe
30062 @end smallexample
30064 @item
30065 Set a breakpoint at the starting address, and launch the program.
30067 @smallexample
30068 $ (gdb) break *0x00401010
30069 $ (gdb) run
30070 @end smallexample
30072 The program will stop at the given address.
30074 @item
30075 Set a breakpoint on a DLL subroutine.
30077 @smallexample
30078 (gdb) break ada_dll.adb:45
30079 @end smallexample
30081 Or if you want to break using a symbol on the DLL, you need first to
30082 select the Ada language (language used by the DLL).
30084 @smallexample
30085 (gdb) set language ada
30086 (gdb) break ada_dll
30087 @end smallexample
30089 @item
30090 Continue the program.
30092 @smallexample
30093 (gdb) cont
30094 @end smallexample
30096 @noindent
30097 This will run the program until it reaches the breakpoint that has been
30098 set. From that point you can use the standard way to debug a program
30099 as described in (@pxref{Running and Debugging Ada Programs}).
30101 @end enumerate
30103 @noindent
30104 It is also possible to debug the DLL by attaching to a running process.
30106 @node Attaching to a Running Process
30107 @subsubsection Attaching to a Running Process
30108 @cindex DLL debugging, attach to process
30110 @noindent
30111 With @code{GDB} it is always possible to debug a running process by
30112 attaching to it. It is possible to debug a DLL this way. The limitation
30113 of this approach is that the DLL must run long enough to perform the
30114 attach operation. It may be useful for instance to insert a time wasting
30115 loop in the code of the DLL to meet this criterion.
30117 @enumerate 1
30119 @item Launch the main program @file{main.exe}.
30121 @smallexample
30122 $ main
30123 @end smallexample
30125 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
30126 that the process PID for @file{main.exe} is 208.
30128 @item Launch gdb.
30130 @smallexample
30131 $ gdb
30132 @end smallexample
30134 @item Attach to the running process to be debugged.
30136 @smallexample
30137 (gdb) attach 208
30138 @end smallexample
30140 @item Load the process debugging information.
30142 @smallexample
30143 (gdb) symbol-file main.exe
30144 @end smallexample
30146 @item Break somewhere in the DLL.
30148 @smallexample
30149 (gdb) break ada_dll
30150 @end smallexample
30152 @item Continue process execution.
30154 @smallexample
30155 (gdb) cont
30156 @end smallexample
30158 @end enumerate
30160 @noindent
30161 This last step will resume the process execution, and stop at
30162 the breakpoint we have set. From there you can use the standard
30163 approach to debug a program as described in
30164 (@pxref{Running and Debugging Ada Programs}).
30166 @node Setting Stack Size from gnatlink
30167 @section Setting Stack Size from @command{gnatlink}
30169 @noindent
30170 It is possible to specify the program stack size at link time. On modern
30171 versions of Windows, starting with XP, this is mostly useful to set the size of
30172 the main stack (environment task). The other task stacks are set with pragma
30173 Storage_Size or with the @command{gnatbind -d} command.
30175 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
30176 reserve size of individual tasks, the link-time stack size applies to all
30177 tasks, and pragma Storage_Size has no effect.
30178 In particular, Stack Overflow checks are made against this
30179 link-time specified size.
30181 This setting can be done with
30182 @command{gnatlink} using either:
30184 @itemize @bullet
30186 @item using @option{-Xlinker} linker option
30188 @smallexample
30189 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
30190 @end smallexample
30192 This sets the stack reserve size to 0x10000 bytes and the stack commit
30193 size to 0x1000 bytes.
30195 @item using @option{-Wl} linker option
30197 @smallexample
30198 $ gnatlink hello -Wl,--stack=0x1000000
30199 @end smallexample
30201 This sets the stack reserve size to 0x1000000 bytes. Note that with
30202 @option{-Wl} option it is not possible to set the stack commit size
30203 because the coma is a separator for this option.
30205 @end itemize
30207 @node Setting Heap Size from gnatlink
30208 @section Setting Heap Size from @command{gnatlink}
30210 @noindent
30211 Under Windows systems, it is possible to specify the program heap size from
30212 @command{gnatlink} using either:
30214 @itemize @bullet
30216 @item using @option{-Xlinker} linker option
30218 @smallexample
30219 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
30220 @end smallexample
30222 This sets the heap reserve size to 0x10000 bytes and the heap commit
30223 size to 0x1000 bytes.
30225 @item using @option{-Wl} linker option
30227 @smallexample
30228 $ gnatlink hello -Wl,--heap=0x1000000
30229 @end smallexample
30231 This sets the heap reserve size to 0x1000000 bytes. Note that with
30232 @option{-Wl} option it is not possible to set the heap commit size
30233 because the coma is a separator for this option.
30235 @end itemize
30237 @node Mac OS Topics
30238 @appendix Mac OS Topics
30239 @cindex OS X
30241 @noindent
30242 This chapter describes topics that are specific to Apple's OS X
30243 platform.
30245 @menu
30246 * Codesigning the Debugger::
30247 @end menu
30249 @node Codesigning the Debugger
30250 @section Codesigning the Debugger
30252 @noindent
30253 The Darwin Kernel requires the debugger to have special permissions
30254 before it is allowed to control other processes. These permissions
30255 are granted by codesigning the GDB executable. Without these
30256 permissions, the debugger will report error messages such as:
30258 @smallexample
30259 Starting program: /x/y/foo
30260 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
30261  (please check gdb is codesigned - see taskgated(8))
30262 @end smallexample
30264 Codesigning requires a certificate.  The following procedure explains
30265 how to create one:
30267 @itemize @bullet
30268 @item Start the Keychain Access application (in
30269 /Applications/Utilities/Keychain Access.app)
30271 @item Select the Keychain Access -> Certificate Assistant ->
30272 Create a Certificate... menu
30274 @item Then:
30276 @itemize @bullet
30277 @item Choose a name for the new certificate (this procedure will use
30278 "gdb-cert" as an example)
30280 @item Set "Identity Type" to "Self Signed Root"
30282 @item Set "Certificate Type" to "Code Signing"
30284 @item Activate the "Let me override defaults" option
30286 @end itemize
30288 @item Click several times on "Continue" until the "Specify a Location
30289 For The Certificate" screen appears, then set "Keychain" to "System"
30291 @item Click on "Continue" until the certificate is created
30293 @item Finally, in the view, double-click on the new certificate,
30294 and set "When using this certificate" to "Always Trust"
30296 @item Exit the Keychain Access application and restart the computer
30297 (this is unfortunately required)
30299 @end itemize
30301 Once a certificate has been created, the debugger can be codesigned
30302 as follow. In a Terminal, run the following command...
30304 @smallexample
30305 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
30306 @end smallexample
30308 ... where "gdb-cert" should be replaced by the actual certificate
30309 name chosen above, and <gnat_install_prefix> should be replaced by
30310 the location where you installed GNAT.
30312 @end ifset
30314 @c **********************************
30315 @c * GNU Free Documentation License *
30316 @c **********************************
30317 @include fdl.texi
30318 @c GNU Free Documentation License
30320 @node Index,,GNU Free Documentation License, Top
30321 @unnumbered Index
30323 @printindex cp
30325 @contents
30326 @c Put table of contents at end, otherwise it precedes the "title page" in
30327 @c the .txt version
30328 @c Edit the pdf file to move the contents to the beginning, after the title
30329 @c page
30331 @bye