Merged revisions 195901,195904,196012 via svnmerge from
[official-gcc.git] / main / gcc / ada / gnat_ugn.texi
blob1af8a943ef789c623914fc6f11faccddd8b0c636
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c           Copyright (C) 1992-2013, Free Software Foundation, Inc.          o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
30 @c                           GNAT_UGN Style Guide
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
95 @ifset unw
96 @set PLATFORM
97 @set TITLESUFFIX
98 @end ifset
100 @ifset vms
101 @set PLATFORM OpenVMS
102 @set TITLESUFFIX for OpenVMS
103 @end ifset
105 @c @ovar(ARG)
106 @c ----------
107 @c The ARG is an optional argument.  To be used for macro arguments in
108 @c their documentation (@defmac).
109 @macro ovar{varname}
110 @r{[}@var{\varname\}@r{]}@c
111 @end macro
112 @c Status as of November 2009:
113 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
114 @c differently, and faulty output is produced by one or the other
115 @c depending on whether the "@c" is present or absent.
116 @c As a result, the @ovar macro is not used, and all invocations
117 @c of the @ovar macro have been expanded inline.
120 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
121 @dircategory GNU Ada tools
122 @direntry
123 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
124 @end direntry
126 @include gcc-common.texi
128 @setchapternewpage odd
129 @syncodeindex fn cp
130 @c %**end of header
132 @titlepage
133 @title @value{EDITION} User's Guide
134 @ifset vms
135 @sp 1
136 @flushright
137 @titlefont{@i{@value{PLATFORM}}}
138 @end flushright
139 @end ifset
141 @sp 2
143 @subtitle GNAT, The GNU Ada Compiler
144 @versionsubtitle
145 @author AdaCore
147 @page
148 @vskip 0pt plus 1filll
150 @insertcopying
152 @end titlepage
154 @ifnottex
155 @node Top, About This Guide, (dir), (dir)
156 @top @value{EDITION} User's Guide
158 @noindent
159 @value{EDITION} User's Guide @value{PLATFORM}
161 @noindent
162 GNAT, The GNU Ada Compiler@*
163 GCC version @value{version-GCC}@*
165 @noindent
166 AdaCore@*
168 @menu
169 * About This Guide::
170 * Getting Started with GNAT::
171 * The GNAT Compilation Model::
172 * Compiling Using gcc::
173 * Binding Using gnatbind::
174 * Linking Using gnatlink::
175 * The GNAT Make Program gnatmake::
176 * Improving Performance::
177 * Renaming Files Using gnatchop::
178 * Configuration Pragmas::
179 * Handling Arbitrary File Naming Conventions Using gnatname::
180 * GNAT Project Manager::
181 * Tools Supporting Project Files::
182 * The Cross-Referencing Tools gnatxref and gnatfind::
183 * The GNAT Pretty-Printer gnatpp::
184 * The GNAT Metric Tool gnatmetric::
185 * File Name Krunching Using gnatkr::
186 * Preprocessing Using gnatprep::
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Memory Management Issues::
194 * Stack Related Facilities::
195 * Verifying Properties Using gnatcheck::
196 * Creating Sample Bodies Using gnatstub::
197 * Creating Unit Tests Using gnattest::
198 * Performing Dimensionality Analysis in GNAT::
199 * Generating Ada Bindings for C and C++ headers::
200 * Other Utility Programs::
201 * Running and Debugging Ada Programs::
202 @ifclear vms
203 * Code Coverage and Profiling::
204 @end ifclear
205 @ifset vms
206 * Compatibility with HP Ada::
207 @end ifset
208 * Platform-Specific Information for the Run-Time Libraries::
209 * Example of Binder Output File::
210 * Elaboration Order Handling in GNAT::
211 * Overflow Check Handling in GNAT::
212 * Conditional Compilation::
213 * Inline Assembler::
214 * Compatibility and Porting Guide::
215 @ifset unw
216 * Microsoft Windows Topics::
217 * Mac OS Topics::
218 @end ifset
219 * GNU Free Documentation License::
220 * Index::
222  --- The Detailed Node Listing ---
224 About This Guide
226 * What This Guide Contains::
227 * What You Should Know before Reading This Guide::
228 * Related Information::
229 * Conventions::
231 Getting Started with GNAT
233 * Running GNAT::
234 * Running a Simple Ada Program::
235 * Running a Program with Multiple Units::
236 * Using the gnatmake Utility::
237 @ifset vms
238 * Editing with Emacs::
239 @end ifset
240 @ifclear vms
241 * Introduction to GPS::
242 @end ifclear
244 The GNAT Compilation Model
246 * Source Representation::
247 * Foreign Language Representation::
248 * File Naming Rules::
249 * Using Other File Names::
250 * Alternative File Naming Schemes::
251 * Generating Object Files::
252 * Source Dependencies::
253 * The Ada Library Information Files::
254 * Binding an Ada Program::
255 * Mixed Language Programming::
256 @ifclear vms
257 * Building Mixed Ada & C++ Programs::
258 * Comparison between GNAT and C/C++ Compilation Models::
259 @end ifclear
260 * Comparison between GNAT and Conventional Ada Library Models::
261 @ifset vms
262 * Placement of temporary files::
263 @end ifset
265 Foreign Language Representation
267 * Latin-1::
268 * Other 8-Bit Codes::
269 * Wide Character Encodings::
271 Compiling Ada Programs With gcc
273 * Compiling Programs::
274 * Switches for gcc::
275 * Search Paths and the Run-Time Library (RTL)::
276 * Order of Compilation Issues::
277 * Examples::
279 Switches for gcc
281 * Output and Error Message Control::
282 * Warning Message Control::
283 * Debugging and Assertion Control::
284 * Validity Checking::
285 * Style Checking::
286 * Run-Time Checks::
287 * Using gcc for Syntax Checking::
288 * Using gcc for Semantic Checking::
289 * Compiling Different Versions of Ada::
290 * Character Set Control::
291 * File Naming Control::
292 * Subprogram Inlining Control::
293 * Auxiliary Output Control::
294 * Debugging Control::
295 * Exception Handling Control::
296 * Units to Sources Mapping Files::
297 * Integrated Preprocessing::
298 @ifset vms
299 * Return Codes::
300 @end ifset
302 Binding Ada Programs With gnatbind
304 * Running gnatbind::
305 * Switches for gnatbind::
306 * Command-Line Access::
307 * Search Paths for gnatbind::
308 * Examples of gnatbind Usage::
310 Switches for gnatbind
312 * Consistency-Checking Modes::
313 * Binder Error Message Control::
314 * Elaboration Control::
315 * Output Control::
316 * Binding with Non-Ada Main Programs::
317 * Binding Programs with No Main Subprogram::
319 Linking Using gnatlink
321 * Running gnatlink::
322 * Switches for gnatlink::
324 The GNAT Make Program gnatmake
326 * Running gnatmake::
327 * Switches for gnatmake::
328 * Mode Switches for gnatmake::
329 * Notes on the Command Line::
330 * How gnatmake Works::
331 * Examples of gnatmake Usage::
333 Improving Performance
334 * Performance Considerations::
335 * Text_IO Suggestions::
336 * Reducing Size of Ada Executables with gnatelim::
337 * Reducing Size of Executables with unused subprogram/data elimination::
339 Performance Considerations
340 * Controlling Run-Time Checks::
341 * Use of Restrictions::
342 * Optimization Levels::
343 * Debugging Optimized Code::
344 * Inlining of Subprograms::
345 * Vectorization of loops::
346 * Other Optimization Switches::
347 * Optimization and Strict Aliasing::
348 @ifset vms
349 * Coverage Analysis::
350 @end ifset
352 Reducing Size of Ada Executables with gnatelim
353 * About gnatelim::
354 * Running gnatelim::
355 * Processing Precompiled Libraries::
356 * Correcting the List of Eliminate Pragmas::
357 * Making Your Executables Smaller::
358 * Summary of the gnatelim Usage Cycle::
360 Reducing Size of Executables with unused subprogram/data elimination
361 * About unused subprogram/data elimination::
362 * Compilation options::
364 Renaming Files Using gnatchop
366 * Handling Files with Multiple Units::
367 * Operating gnatchop in Compilation Mode::
368 * Command Line for gnatchop::
369 * Switches for gnatchop::
370 * Examples of gnatchop Usage::
372 Configuration Pragmas
374 * Handling of Configuration Pragmas::
375 * The Configuration Pragmas Files::
377 Handling Arbitrary File Naming Conventions Using gnatname
379 * Arbitrary File Naming Conventions::
380 * Running gnatname::
381 * Switches for gnatname::
382 * Examples of gnatname Usage::
384 The Cross-Referencing Tools gnatxref and gnatfind
386 * Switches for gnatxref::
387 * Switches for gnatfind::
388 * Project Files for gnatxref and gnatfind::
389 * Regular Expressions in gnatfind and gnatxref::
390 * Examples of gnatxref Usage::
391 * Examples of gnatfind Usage::
393 The GNAT Pretty-Printer gnatpp
395 * Switches for gnatpp::
396 * Formatting Rules::
398 The GNAT Metrics Tool gnatmetric
400 * Switches for gnatmetric::
402 File Name Krunching Using gnatkr
404 * About gnatkr::
405 * Using gnatkr::
406 * Krunching Method::
407 * Examples of gnatkr Usage::
409 Preprocessing Using gnatprep
410 * Preprocessing Symbols::
411 * Using gnatprep::
412 * Switches for gnatprep::
413 * Form of Definitions File::
414 * Form of Input Text for gnatprep::
416 The GNAT Library Browser gnatls
418 * Running gnatls::
419 * Switches for gnatls::
420 * Examples of gnatls Usage::
422 Cleaning Up Using gnatclean
424 * Running gnatclean::
425 * Switches for gnatclean::
426 @c * Examples of gnatclean Usage::
428 @ifclear vms
430 GNAT and Libraries
432 * Introduction to Libraries in GNAT::
433 * General Ada Libraries::
434 * Stand-alone Ada Libraries::
435 * Rebuilding the GNAT Run-Time Library::
437 Using the GNU make Utility
439 * Using gnatmake in a Makefile::
440 * Automatically Creating a List of Directories::
441 * Generating the Command Line Switches::
442 * Overcoming Command Line Length Limits::
443 @end ifclear
445 Memory Management Issues
447 * Some Useful Memory Pools::
448 * The GNAT Debug Pool Facility::
449 @ifclear vms
450 * The gnatmem Tool::
451 @end ifclear
453 Stack Related Facilities
455 * Stack Overflow Checking::
456 * Static Stack Usage Analysis::
457 * Dynamic Stack Usage Analysis::
459 Some Useful Memory Pools
461 The GNAT Debug Pool Facility
463 @ifclear vms
464 The gnatmem Tool
466 * Running gnatmem::
467 * Switches for gnatmem::
468 * Example of gnatmem Usage::
469 @end ifclear
471 Verifying Properties Using gnatcheck
473 Sample Bodies Using gnatstub
475 * Running gnatstub::
476 * Switches for gnatstub::
478 Creating Unit Tests Using gnattest
480 * Running gnattest::
481 * Switches for gnattest::
482 * Project Attributes for gnattest::
483 * Simple Example::
484 * Setting Up and Tearing Down the Testing Environment::
485 * Regenerating Tests::
486 * Default Test Behavior::
487 * Testing Primitive Operations of Tagged Types::
488 * Testing Inheritance::
489 * Tagged Types Substitutability Testing::
490 * Testing with Contracts::
491 * Additional Tests::
492 @ifclear vms
493 * Support for other platforms/run-times::
494 @end ifclear
495 * Current Limitations::
497 Other Utility Programs
499 * Using Other Utility Programs with GNAT::
500 * The External Symbol Naming Scheme of GNAT::
501 * Converting Ada Files to html with gnathtml::
503 @ifclear vms
504 Code Coverage and Profiling
506 * Code Coverage of Ada Programs using gcov::
507 * Profiling an Ada Program using gprof::
508 @end ifclear
510 Running and Debugging Ada Programs
512 * The GNAT Debugger GDB::
513 * Running GDB::
514 * Introduction to GDB Commands::
515 * Using Ada Expressions::
516 * Calling User-Defined Subprograms::
517 * Using the Next Command in a Function::
518 * Ada Exceptions::
519 * Ada Tasks::
520 * Debugging Generic Units::
521 * Remote Debugging using gdbserver::
522 * GNAT Abnormal Termination or Failure to Terminate::
523 * Naming Conventions for GNAT Source Files::
524 * Getting Internal Debugging Information::
525 * Stack Traceback::
527 @ifset vms
528 * LSE::
529 @end ifset
531 @ifset vms
532 Compatibility with HP Ada
534 * Ada Language Compatibility::
535 * Differences in the Definition of Package System::
536 * Language-Related Features::
537 * The Package STANDARD::
538 * The Package SYSTEM::
539 * Tasking and Task-Related Features::
540 * Pragmas and Pragma-Related Features::
541 * Library of Predefined Units::
542 * Bindings::
543 * Main Program Definition::
544 * Implementation-Defined Attributes::
545 * Compiler and Run-Time Interfacing::
546 * Program Compilation and Library Management::
547 * Input-Output::
548 * Implementation Limits::
549 * Tools and Utilities::
551 Language-Related Features
553 * Integer Types and Representations::
554 * Floating-Point Types and Representations::
555 * Pragmas Float_Representation and Long_Float::
556 * Fixed-Point Types and Representations::
557 * Record and Array Component Alignment::
558 * Address Clauses::
559 * Other Representation Clauses::
561 Tasking and Task-Related Features
563 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
564 * Assigning Task IDs::
565 * Task IDs and Delays::
566 * Task-Related Pragmas::
567 * Scheduling and Task Priority::
568 * The Task Stack::
569 * External Interrupts::
571 Pragmas and Pragma-Related Features
573 * Restrictions on the Pragma INLINE::
574 * Restrictions on the Pragma INTERFACE::
575 * Restrictions on the Pragma SYSTEM_NAME::
577 Library of Predefined Units
579 * Changes to DECLIB::
581 Bindings
583 * Shared Libraries and Options Files::
584 * Interfaces to C::
585 @end ifset
587 Platform-Specific Information for the Run-Time Libraries
589 * Summary of Run-Time Configurations::
590 * Specifying a Run-Time Library::
591 * Choosing the Scheduling Policy::
592 * Solaris-Specific Considerations::
593 * Linux-Specific Considerations::
594 * AIX-Specific Considerations::
595 * RTX-Specific Considerations::
596 * HP-UX-Specific Considerations::
598 Example of Binder Output File
600 Elaboration Order Handling in GNAT
602 * Elaboration Code::
603 * Checking the Elaboration Order::
604 * Controlling the Elaboration Order::
605 * Controlling Elaboration in GNAT - Internal Calls::
606 * Controlling Elaboration in GNAT - External Calls::
607 * Default Behavior in GNAT - Ensuring Safety::
608 * Treatment of Pragma Elaborate::
609 * Elaboration Issues for Library Tasks::
610 * Mixing Elaboration Models::
611 * What to Do If the Default Elaboration Behavior Fails::
612 * Elaboration for Dispatching Calls::
613 * Summary of Procedures for Elaboration Control::
614 * Other Elaboration Order Considerations::
616 Overflow Check Handling in GNAT
617 * Background::
618 * Overflow Checking Modes in GNAT::
619 * Specifying the Desired Mode::
620 * Default Settings::
621 * Implementation Notes::
623 Conditional Compilation
624 * Use of Boolean Constants::
625 * Debugging - A Special Case::
626 * Conditionalizing Declarations::
627 * Use of Alternative Implementations::
628 * Preprocessing::
630 Inline Assembler
632 * Basic Assembler Syntax::
633 * A Simple Example of Inline Assembler::
634 * Output Variables in Inline Assembler::
635 * Input Variables in Inline Assembler::
636 * Inlining Inline Assembler Code::
637 * Other Asm Functionality::
639 Compatibility and Porting Guide
641 * Compatibility with Ada 83::
642 * Compatibility between Ada 95 and Ada 2005::
643 * Implementation-dependent characteristics::
644 @ifclear vms
645 @c This brief section is only in the non-VMS version
646 @c The complete chapter on HP Ada issues is in the VMS version
647 * Compatibility with HP Ada 83::
648 @end ifclear
649 * Compatibility with Other Ada Systems::
650 * Representation Clauses::
651 @ifset vms
652 * Transitioning to 64-Bit GNAT for OpenVMS::
653 @end ifset
655 @ifset unw
656 Microsoft Windows Topics
658 * Using GNAT on Windows::
659 * CONSOLE and WINDOWS subsystems::
660 * Temporary Files::
661 * Mixed-Language Programming on Windows::
662 * Windows Calling Conventions::
663 * Introduction to Dynamic Link Libraries (DLLs)::
664 * Using DLLs with GNAT::
665 * Building DLLs with GNAT::
666 * GNAT and Windows Resources::
667 * Debugging a DLL::
668 * Setting Stack Size from gnatlink::
669 * Setting Heap Size from gnatlink::
671 Mac OS Topics
673 * Codesigning the Debugger::
674 @end ifset
676 * Index::
677 @end menu
678 @end ifnottex
680 @node About This Guide
681 @unnumbered About This Guide
683 @noindent
684 @ifset vms
685 This guide describes the use of @value{EDITION},
686 a compiler and software development toolset for the full Ada
687 programming language, implemented on OpenVMS for HP's Alpha and
688 Integrity server (I64) platforms.
689 @end ifset
690 @ifclear vms
691 This guide describes the use of @value{EDITION},
692 a compiler and software development
693 toolset for the full Ada programming language.
694 @end ifclear
695 It documents the features of the compiler and tools, and explains
696 how to use them to build Ada applications.
698 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
699 Ada 83 compatibility mode.
700 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
701 but you can override with a compiler switch
702 (@pxref{Compiling Different Versions of Ada})
703 to explicitly specify the language version.
704 Throughout this manual, references to ``Ada'' without a year suffix
705 apply to both the Ada 95 and Ada 2005 versions of the language.
708 @ifclear FSFEDITION
709 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
710 ``GNAT'' in the remainder of this document.
711 @end ifclear
716 @menu
717 * What This Guide Contains::
718 * What You Should Know before Reading This Guide::
719 * Related Information::
720 * Conventions::
721 @end menu
723 @node What This Guide Contains
724 @unnumberedsec What This Guide Contains
726 @noindent
727 This guide contains the following chapters:
728 @itemize @bullet
730 @item
731 @ref{Getting Started with GNAT}, describes how to get started compiling
732 and running Ada programs with the GNAT Ada programming environment.
733 @item
734 @ref{The GNAT Compilation Model}, describes the compilation model used
735 by GNAT.
737 @item
738 @ref{Compiling Using gcc}, describes how to compile
739 Ada programs with @command{gcc}, the Ada compiler.
741 @item
742 @ref{Binding Using gnatbind}, describes how to
743 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
744 utility.
746 @item
747 @ref{Linking Using gnatlink},
748 describes @command{gnatlink}, a
749 program that provides for linking using the GNAT run-time library to
750 construct a program. @command{gnatlink} can also incorporate foreign language
751 object units into the executable.
753 @item
754 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
755 utility that automatically determines the set of sources
756 needed by an Ada compilation unit, and executes the necessary compilations
757 binding and link.
759 @item
760 @ref{Improving Performance}, shows various techniques for making your
761 Ada program run faster or take less space.
762 It discusses the effect of the compiler's optimization switch and
763 also describes the @command{gnatelim} tool and unused subprogram/data
764 elimination.
766 @item
767 @ref{Renaming Files Using gnatchop}, describes
768 @code{gnatchop}, a utility that allows you to preprocess a file that
769 contains Ada source code, and split it into one or more new files, one
770 for each compilation unit.
772 @item
773 @ref{Configuration Pragmas}, describes the configuration pragmas
774 handled by GNAT.
776 @item
777 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
778 shows how to override the default GNAT file naming conventions,
779 either for an individual unit or globally.
781 @item
782 @ref{GNAT Project Manager}, describes how to use project files
783 to organize large projects.
785 @item
786 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
787 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
788 way to navigate through sources.
790 @item
791 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
792 version of an Ada source file with control over casing, indentation,
793 comment placement, and other elements of program presentation style.
795 @item
796 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
797 metrics for an Ada source file, such as the number of types and subprograms,
798 and assorted complexity measures.
800 @item
801 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
802 file name krunching utility, used to handle shortened
803 file names on operating systems with a limit on the length of names.
805 @item
806 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
807 preprocessor utility that allows a single source file to be used to
808 generate multiple or parameterized source files by means of macro
809 substitution.
811 @item
812 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
813 utility that displays information about compiled units, including dependences
814 on the corresponding sources files, and consistency of compilations.
816 @item
817 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
818 to delete files that are produced by the compiler, binder and linker.
820 @ifclear vms
821 @item
822 @ref{GNAT and Libraries}, describes the process of creating and using
823 Libraries with GNAT. It also describes how to recompile the GNAT run-time
824 library.
826 @item
827 @ref{Using the GNU make Utility}, describes some techniques for using
828 the GNAT toolset in Makefiles.
829 @end ifclear
831 @item
832 @ref{Memory Management Issues}, describes some useful predefined storage pools
833 and in particular the GNAT Debug Pool facility, which helps detect incorrect
834 memory references.
835 @ifclear vms
836 It also describes @command{gnatmem}, a utility that monitors dynamic
837 allocation and deallocation and helps detect ``memory leaks''.
838 @end ifclear
840 @item
841 @ref{Stack Related Facilities}, describes some useful tools associated with
842 stack checking and analysis.
844 @item
845 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
846 a utility that checks Ada code against a set of rules.
848 @item
849 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
850 a utility that generates empty but compilable bodies for library units.
852 @item
853 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
854 a utility that generates unit testing templates for library units.
856 @item
857 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
858 facilities used in GNAT to declare dimensioned objects, and to verify that
859 uses of these objects are consistent with their given physical dimensions
860 (so that meters cannot be assigned to kilograms, and so on).
862 @item
863 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
864 generate automatically Ada bindings from C and C++ headers.
866 @item
867 @ref{Other Utility Programs}, discusses several other GNAT utilities,
868 including @code{gnathtml}.
870 @ifclear vms
871 @item
872 @ref{Code Coverage and Profiling}, describes how to perform a structural
873 coverage and profile the execution of Ada programs.
874 @end ifclear
876 @item
877 @ref{Running and Debugging Ada Programs}, describes how to run and debug
878 Ada programs.
880 @ifset vms
881 @item
882 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
883 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
884 developed by Digital Equipment Corporation and currently supported by HP.}
885 for OpenVMS Alpha. This product was formerly known as DEC Ada,
886 @cindex DEC Ada
887 and for
888 historical compatibility reasons, the relevant libraries still use the
889 DEC prefix.
890 @end ifset
892 @item
893 @ref{Platform-Specific Information for the Run-Time Libraries},
894 describes the various run-time
895 libraries supported by GNAT on various platforms and explains how to
896 choose a particular library.
898 @item
899 @ref{Example of Binder Output File}, shows the source code for the binder
900 output file for a sample program.
902 @item
903 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
904 you deal with elaboration order issues.
906 @item
907 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
908 you deal with arithmetic overflow issues.
910 @item
911 @ref{Conditional Compilation}, describes how to model conditional compilation,
912 both with Ada in general and with GNAT facilities in particular.
914 @item
915 @ref{Inline Assembler}, shows how to use the inline assembly facility
916 in an Ada program.
918 @item
919 @ref{Compatibility and Porting Guide}, contains sections on compatibility
920 of GNAT with other Ada development environments (including Ada 83 systems),
921 to assist in porting code from those environments.
923 @ifset unw
924 @item
925 @ref{Microsoft Windows Topics}, presents information relevant to the
926 Microsoft Windows platform.
928 @item
929 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
930 platform.
931 @end ifset
932 @end itemize
934 @c *************************************************
935 @node What You Should Know before Reading This Guide
936 @c *************************************************
937 @unnumberedsec What You Should Know before Reading This Guide
939 @cindex Ada 95 Language Reference Manual
940 @cindex Ada 2005 Language Reference Manual
941 @noindent
942 This guide assumes a basic familiarity with the Ada 95 language, as
943 described in the International Standard ANSI/ISO/IEC-8652:1995, January
944 1995.
945 It does not require knowledge of the new features introduced by Ada 2005,
946 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
947 and Amendment 1).
948 Both reference manuals are included in the GNAT documentation
949 package.
951 @node Related Information
952 @unnumberedsec Related Information
954 @noindent
955 For further information about related tools, refer to the following
956 documents:
958 @itemize @bullet
959 @item
960 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
961 Reference Manual}, which contains all reference material for the GNAT
962 implementation of Ada.
964 @ifset unw
965 @item
966 @cite{Using the GNAT Programming Studio}, which describes the GPS
967 Integrated Development Environment.
969 @item
970 @cite{GNAT Programming Studio Tutorial}, which introduces the
971 main GPS features through examples.
972 @end ifset
974 @item
975 @cite{Ada 95 Reference Manual}, which contains reference
976 material for the Ada 95 programming language.
978 @item
979 @cite{Ada 2005 Reference Manual}, which contains reference
980 material for the Ada 2005 programming language.
982 @item
983 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
984 @ifset vms
985 in the GNU:[DOCS] directory,
986 @end ifset
987 for all details on the use of the GNU source-level debugger.
989 @item
990 @xref{Top,, The extensible self-documenting text editor, emacs,
991 GNU Emacs Manual},
992 @ifset vms
993 located in the GNU:[DOCS] directory if the EMACS kit is installed,
994 @end ifset
995 for full information on the extensible editor and programming
996 environment Emacs.
998 @end itemize
1000 @c **************
1001 @node Conventions
1002 @unnumberedsec Conventions
1003 @cindex Conventions
1004 @cindex Typographical conventions
1006 @noindent
1007 Following are examples of the typographical and graphic conventions used
1008 in this guide:
1010 @itemize @bullet
1011 @item
1012 @code{Functions}, @command{utility program names}, @code{standard names},
1013 and @code{classes}.
1015 @item
1016 @option{Option flags}
1018 @item
1019 @file{File names}, @samp{button names}, and @samp{field names}.
1021 @item
1022 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1023 variables}.
1025 @item
1026 @emph{Emphasis}.
1028 @item
1029 @r{[}optional information or parameters@r{]}
1031 @item
1032 Examples are described by text
1033 @smallexample
1034 and then shown this way.
1035 @end smallexample
1036 @end itemize
1038 @noindent
1039 Commands that are entered by the user are preceded in this manual by the
1040 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1041 uses this sequence as a prompt, then the commands will appear exactly as
1042 you see them in the manual. If your system uses some other prompt, then
1043 the command will appear with the @code{$} replaced by whatever prompt
1044 character you are using.
1046 @ifset unw
1047 Full file names are shown with the ``@code{/}'' character
1048 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1049 If you are using GNAT on a Windows platform, please note that
1050 the ``@code{\}'' character should be used instead.
1051 @end ifset
1053 @c ****************************
1054 @node Getting Started with GNAT
1055 @chapter Getting Started with GNAT
1057 @noindent
1058 This chapter describes some simple ways of using GNAT to build
1059 executable Ada programs.
1060 @ifset unw
1061 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1062 show how to use the command line environment.
1063 @ref{Introduction to GPS}, provides a brief
1064 introduction to the GNAT Programming Studio, a visually-oriented
1065 Integrated Development Environment for GNAT.
1066 GPS offers a graphical ``look and feel'', support for development in
1067 other programming languages, comprehensive browsing features, and
1068 many other capabilities.
1069 For information on GPS please refer to
1070 @cite{Using the GNAT Programming Studio}.
1071 @end ifset
1073 @menu
1074 * Running GNAT::
1075 * Running a Simple Ada Program::
1076 * Running a Program with Multiple Units::
1077 * Using the gnatmake Utility::
1078 @ifset vms
1079 * Editing with Emacs::
1080 @end ifset
1081 @ifclear vms
1082 * Introduction to GPS::
1083 @end ifclear
1084 @end menu
1086 @node Running GNAT
1087 @section Running GNAT
1089 @noindent
1090 Three steps are needed to create an executable file from an Ada source
1091 file:
1093 @enumerate
1094 @item
1095 The source file(s) must be compiled.
1096 @item
1097 The file(s) must be bound using the GNAT binder.
1098 @item
1099 All appropriate object files must be linked to produce an executable.
1100 @end enumerate
1102 @noindent
1103 All three steps are most commonly handled by using the @command{gnatmake}
1104 utility program that, given the name of the main program, automatically
1105 performs the necessary compilation, binding and linking steps.
1107 @node Running a Simple Ada Program
1108 @section Running a Simple Ada Program
1110 @noindent
1111 Any text editor may be used to prepare an Ada program.
1112 (If @code{Emacs} is
1113 used, the optional Ada mode may be helpful in laying out the program.)
1115 program text is a normal text file. We will assume in our initial
1116 example that you have used your editor to prepare the following
1117 standard format text file:
1119 @smallexample @c ada
1120 @cartouche
1121 with Ada.Text_IO; use Ada.Text_IO;
1122 procedure Hello is
1123 begin
1124    Put_Line ("Hello WORLD!");
1125 end Hello;
1126 @end cartouche
1127 @end smallexample
1129 @noindent
1130 This file should be named @file{hello.adb}.
1131 With the normal default file naming conventions, GNAT requires
1132 that each file
1133 contain a single compilation unit whose file name is the
1134 unit name,
1135 with periods replaced by hyphens; the
1136 extension is @file{ads} for a
1137 spec and @file{adb} for a body.
1138 You can override this default file naming convention by use of the
1139 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1140 Alternatively, if you want to rename your files according to this default
1141 convention, which is probably more convenient if you will be using GNAT
1142 for all your compilations, then the @code{gnatchop} utility
1143 can be used to generate correctly-named source files
1144 (@pxref{Renaming Files Using gnatchop}).
1146 You can compile the program using the following command (@code{$} is used
1147 as the command prompt in the examples in this document):
1149 @smallexample
1150 $ gcc -c hello.adb
1151 @end smallexample
1153 @noindent
1154 @command{gcc} is the command used to run the compiler. This compiler is
1155 capable of compiling programs in several languages, including Ada and
1156 C. It assumes that you have given it an Ada program if the file extension is
1157 either @file{.ads} or @file{.adb}, and it will then call
1158 the GNAT compiler to compile the specified file.
1160 @ifclear vms
1161 The @option{-c} switch is required. It tells @command{gcc} to only do a
1162 compilation. (For C programs, @command{gcc} can also do linking, but this
1163 capability is not used directly for Ada programs, so the @option{-c}
1164 switch must always be present.)
1165 @end ifclear
1167 This compile command generates a file
1168 @file{hello.o}, which is the object
1169 file corresponding to your Ada program. It also generates
1170 an ``Ada Library Information'' file @file{hello.ali},
1171 which contains additional information used to check
1172 that an Ada program is consistent.
1173 To build an executable file,
1174 use @code{gnatbind} to bind the program
1175 and @command{gnatlink} to link it. The
1176 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1177 @file{ALI} file, but the default extension of @file{.ali} can
1178 be omitted. This means that in the most common case, the argument
1179 is simply the name of the main program:
1181 @smallexample
1182 $ gnatbind hello
1183 $ gnatlink hello
1184 @end smallexample
1186 @noindent
1187 A simpler method of carrying out these steps is to use
1188 @command{gnatmake},
1189 a master program that invokes all the required
1190 compilation, binding and linking tools in the correct order. In particular,
1191 @command{gnatmake} automatically recompiles any sources that have been
1192 modified since they were last compiled, or sources that depend
1193 on such modified sources, so that ``version skew'' is avoided.
1194 @cindex Version skew (avoided by @command{gnatmake})
1196 @smallexample
1197 $ gnatmake hello.adb
1198 @end smallexample
1200 @noindent
1201 The result is an executable program called @file{hello}, which can be
1202 run by entering:
1204 @smallexample
1205 $ ^hello^RUN HELLO^
1206 @end smallexample
1208 @noindent
1209 assuming that the current directory is on the search path
1210 for executable programs.
1212 @noindent
1213 and, if all has gone well, you will see
1215 @smallexample
1216 Hello WORLD!
1217 @end smallexample
1219 @noindent
1220 appear in response to this command.
1222 @c ****************************************
1223 @node Running a Program with Multiple Units
1224 @section Running a Program with Multiple Units
1226 @noindent
1227 Consider a slightly more complicated example that has three files: a
1228 main program, and the spec and body of a package:
1230 @smallexample @c ada
1231 @cartouche
1232 @group
1233 package Greetings is
1234    procedure Hello;
1235    procedure Goodbye;
1236 end Greetings;
1238 with Ada.Text_IO; use Ada.Text_IO;
1239 package body Greetings is
1240    procedure Hello is
1241    begin
1242       Put_Line ("Hello WORLD!");
1243    end Hello;
1245    procedure Goodbye is
1246    begin
1247       Put_Line ("Goodbye WORLD!");
1248    end Goodbye;
1249 end Greetings;
1250 @end group
1252 @group
1253 with Greetings;
1254 procedure Gmain is
1255 begin
1256    Greetings.Hello;
1257    Greetings.Goodbye;
1258 end Gmain;
1259 @end group
1260 @end cartouche
1261 @end smallexample
1263 @noindent
1264 Following the one-unit-per-file rule, place this program in the
1265 following three separate files:
1267 @table @file
1268 @item greetings.ads
1269 spec of package @code{Greetings}
1271 @item greetings.adb
1272 body of package @code{Greetings}
1274 @item gmain.adb
1275 body of main program
1276 @end table
1278 @noindent
1279 To build an executable version of
1280 this program, we could use four separate steps to compile, bind, and link
1281 the program, as follows:
1283 @smallexample
1284 $ gcc -c gmain.adb
1285 $ gcc -c greetings.adb
1286 $ gnatbind gmain
1287 $ gnatlink gmain
1288 @end smallexample
1290 @noindent
1291 Note that there is no required order of compilation when using GNAT.
1292 In particular it is perfectly fine to compile the main program first.
1293 Also, it is not necessary to compile package specs in the case where
1294 there is an accompanying body; you only need to compile the body. If you want
1295 to submit these files to the compiler for semantic checking and not code
1296 generation, then use the
1297 @option{-gnatc} switch:
1299 @smallexample
1300 $ gcc -c greetings.ads -gnatc
1301 @end smallexample
1303 @noindent
1304 Although the compilation can be done in separate steps as in the
1305 above example, in practice it is almost always more convenient
1306 to use the @command{gnatmake} tool. All you need to know in this case
1307 is the name of the main program's source file. The effect of the above four
1308 commands can be achieved with a single one:
1310 @smallexample
1311 $ gnatmake gmain.adb
1312 @end smallexample
1314 @noindent
1315 In the next section we discuss the advantages of using @command{gnatmake} in
1316 more detail.
1318 @c *****************************
1319 @node Using the gnatmake Utility
1320 @section Using the @command{gnatmake} Utility
1322 @noindent
1323 If you work on a program by compiling single components at a time using
1324 @command{gcc}, you typically keep track of the units you modify. In order to
1325 build a consistent system, you compile not only these units, but also any
1326 units that depend on the units you have modified.
1327 For example, in the preceding case,
1328 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1329 you edit @file{greetings.ads}, you must recompile both
1330 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1331 units that depend on @file{greetings.ads}.
1333 @code{gnatbind} will warn you if you forget one of these compilation
1334 steps, so that it is impossible to generate an inconsistent program as a
1335 result of forgetting to do a compilation. Nevertheless it is tedious and
1336 error-prone to keep track of dependencies among units.
1337 One approach to handle the dependency-bookkeeping is to use a
1338 makefile. However, makefiles present maintenance problems of their own:
1339 if the dependencies change as you change the program, you must make
1340 sure that the makefile is kept up-to-date manually, which is also an
1341 error-prone process.
1343 The @command{gnatmake} utility takes care of these details automatically.
1344 Invoke it using either one of the following forms:
1346 @smallexample
1347 $ gnatmake gmain.adb
1348 $ gnatmake ^gmain^GMAIN^
1349 @end smallexample
1351 @noindent
1352 The argument is the name of the file containing the main program;
1353 you may omit the extension. @command{gnatmake}
1354 examines the environment, automatically recompiles any files that need
1355 recompiling, and binds and links the resulting set of object files,
1356 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1357 In a large program, it
1358 can be extremely helpful to use @command{gnatmake}, because working out by hand
1359 what needs to be recompiled can be difficult.
1361 Note that @command{gnatmake}
1362 takes into account all the Ada rules that
1363 establish dependencies among units. These include dependencies that result
1364 from inlining subprogram bodies, and from
1365 generic instantiation. Unlike some other
1366 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1367 found by the compiler on a previous compilation, which may possibly
1368 be wrong when sources change. @command{gnatmake} determines the exact set of
1369 dependencies from scratch each time it is run.
1371 @ifset vms
1372 @node Editing with Emacs
1373 @section Editing with Emacs
1374 @cindex Emacs
1376 @noindent
1377 Emacs is an extensible self-documenting text editor that is available in a
1378 separate VMSINSTAL kit.
1380 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1381 click on the Emacs Help menu and run the Emacs Tutorial.
1382 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1383 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1385 Documentation on Emacs and other tools is available in Emacs under the
1386 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1387 use the middle mouse button to select a topic (e.g.@: Emacs).
1389 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1390 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1391 get to the Emacs manual.
1392 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1393 prompt.
1395 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1396 which is sufficiently extensible to provide for a complete programming
1397 environment and shell for the sophisticated user.
1398 @end ifset
1400 @ifclear vms
1401 @node Introduction to GPS
1402 @section Introduction to GPS
1403 @cindex GPS (GNAT Programming Studio)
1404 @cindex GNAT Programming Studio (GPS)
1405 @noindent
1406 Although the command line interface (@command{gnatmake}, etc.) alone
1407 is sufficient, a graphical Interactive Development
1408 Environment can make it easier for you to compose, navigate, and debug
1409 programs.  This section describes the main features of GPS
1410 (``GNAT Programming Studio''), the GNAT graphical IDE.
1411 You will see how to use GPS to build and debug an executable, and
1412 you will also learn some of the basics of the GNAT ``project'' facility.
1414 GPS enables you to do much more than is presented here;
1415 e.g., you can produce a call graph, interface to a third-party
1416 Version Control System, and inspect the generated assembly language
1417 for a program.
1418 Indeed, GPS also supports languages other than Ada.
1419 Such additional information, and an explanation of all of the GPS menu
1420 items. may be found in the on-line help, which includes
1421 a user's guide and a tutorial (these are also accessible from the GNAT
1422 startup menu).
1424 @menu
1425 * Building a New Program with GPS::
1426 * Simple Debugging with GPS::
1427 @end menu
1429 @node Building a New Program with GPS
1430 @subsection Building a New Program with GPS
1431 @noindent
1432 GPS invokes the GNAT compilation tools using information
1433 contained in a @emph{project} (also known as a @emph{project file}):
1434 a collection of properties such
1435 as source directories, identities of main subprograms, tool switches, etc.,
1436 and their associated values.
1437 See @ref{GNAT Project Manager} for details.
1438 In order to run GPS, you will need to either create a new project
1439 or else open an existing one.
1441 This section will explain how you can use GPS to create a project,
1442 to associate Ada source files with a project, and to build and run
1443 programs.
1445 @enumerate
1446 @item @emph{Creating a project}
1448 Invoke GPS, either from the command line or the platform's IDE.
1449 After it starts, GPS will display a ``Welcome'' screen with three
1450 radio buttons:
1452 @itemize @bullet
1453 @item
1454 @code{Start with default project in directory}
1456 @item
1457 @code{Create new project with wizard}
1459 @item
1460 @code{Open existing project}
1461 @end itemize
1463 @noindent
1464 Select @code{Create new project with wizard} and press @code{OK}.
1465 A new window will appear.  In the text box labeled with
1466 @code{Enter the name of the project to create}, type @file{sample}
1467 as the project name.
1468 In the next box, browse to choose the directory in which you
1469 would like to create the project file.
1470 After selecting an appropriate directory, press @code{Forward}.
1472 A window will appear with the title
1473 @code{Version Control System Configuration}.
1474 Simply press @code{Forward}.
1476 A window will appear with the title
1477 @code{Please select the source directories for this project}.
1478 The directory that you specified for the project file will be selected
1479 by default as the one to use for sources; simply press @code{Forward}.
1481 A window will appear with the title
1482 @code{Please select the build directory for this project}.
1483 The directory that you specified for the project file will be selected
1484 by default for object files and executables;
1485 simply press @code{Forward}.
1487 A window will appear with the title
1488 @code{Please select the main units for this project}.
1489 You will supply this information later, after creating the source file.
1490 Simply press @code{Forward} for now.
1492 A window will appear with the title
1493 @code{Please select the switches to build the project}.
1494 Press @code{Apply}.  This will create a project file named
1495 @file{sample.prj} in the directory that you had specified.
1497 @item @emph{Creating and saving the source file}
1499 After you create the new project, a GPS window will appear, which is
1500 partitioned into two main sections:
1502 @itemize @bullet
1503 @item
1504 A @emph{Workspace area}, initially greyed out, which you will use for
1505 creating and editing source files
1507 @item
1508 Directly below, a @emph{Messages area}, which initially displays a
1509 ``Welcome'' message.
1510 (If the Messages area is not visible, drag its border upward to expand it.)
1511 @end itemize
1513 @noindent
1514 Select @code{File} on the menu bar, and then the @code{New} command.
1515 The Workspace area will become white, and you can now
1516 enter the source program explicitly.
1517 Type the following text
1519 @smallexample @c ada
1520 @group
1521 with Ada.Text_IO; use Ada.Text_IO;
1522 procedure Hello is
1523 begin
1524   Put_Line("Hello from GPS!");
1525 end Hello;
1526 @end group
1527 @end smallexample
1529 @noindent
1530 Select @code{File}, then @code{Save As}, and enter the source file name
1531 @file{hello.adb}.
1532 The file will be saved in the same directory you specified as the
1533 location of the default project file.
1535 @item @emph{Updating the project file}
1537 You need to add the new source file to the project.
1538 To do this, select
1539 the @code{Project} menu and then @code{Edit project properties}.
1540 Click the @code{Main files} tab on the left, and then the
1541 @code{Add} button.
1542 Choose @file{hello.adb} from the list, and press @code{Open}.
1543 The project settings window will reflect this action.
1544 Click @code{OK}.
1546 @item @emph{Building and running the program}
1548 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1549 and select @file{hello.adb}.
1550 The Messages window will display the resulting invocations of @command{gcc},
1551 @command{gnatbind}, and @command{gnatlink}
1552 (reflecting the default switch settings from the
1553 project file that you created) and then a ``successful compilation/build''
1554 message.
1556 To run the program, choose the @code{Build} menu, then @code{Run}, and
1557 select @command{hello}.
1558 An @emph{Arguments Selection} window will appear.
1559 There are no command line arguments, so just click @code{OK}.
1561 The Messages window will now display the program's output (the string
1562 @code{Hello from GPS}), and at the bottom of the GPS window a status
1563 update is displayed (@code{Run: hello}).
1564 Close the GPS window (or select @code{File}, then @code{Exit}) to
1565 terminate this GPS session.
1566 @end enumerate
1568 @node Simple Debugging with GPS
1569 @subsection Simple Debugging with GPS
1570 @noindent
1571 This section illustrates basic debugging techniques (setting breakpoints,
1572 examining/modifying variables, single stepping).
1574 @enumerate
1575 @item @emph{Opening a project}
1577 Start GPS and select @code{Open existing project}; browse to
1578 specify the project file @file{sample.prj} that you had created in the
1579 earlier example.
1581 @item @emph{Creating a source file}
1583 Select @code{File}, then @code{New}, and type in the following program:
1585 @smallexample @c ada
1586 @group
1587 with Ada.Text_IO; use Ada.Text_IO;
1588 procedure Example is
1589    Line : String (1..80);
1590    N    : Natural;
1591 begin
1592    Put_Line("Type a line of text at each prompt; an empty line to exit");
1593    loop
1594       Put(": ");
1595       Get_Line (Line, N);
1596       Put_Line (Line (1..N) );
1597       exit when N=0;
1598    end loop;
1599 end Example;
1600 @end group
1601 @end smallexample
1603 @noindent
1604 Select @code{File}, then @code{Save as}, and enter the file name
1605 @file{example.adb}.
1607 @item @emph{Updating the project file}
1609 Add @code{Example} as a new main unit for the project:
1610 @enumerate a
1611 @item
1612 Select @code{Project}, then @code{Edit Project Properties}.
1614 @item
1615 Select the @code{Main files} tab, click @code{Add}, then
1616 select the file @file{example.adb} from the list, and
1617 click @code{Open}.
1618 You will see the file name appear in the list of main units
1620 @item
1621 Click @code{OK}
1622 @end enumerate
1624 @item @emph{Building/running the executable}
1626 To build the executable
1627 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1629 Run the program to see its effect (in the Messages area).
1630 Each line that you enter is displayed; an empty line will
1631 cause the loop to exit and the program to terminate.
1633 @item @emph{Debugging the program}
1635 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1636 which are required for debugging, are on by default when you create
1637 a new project.
1638 Thus unless you intentionally remove these settings, you will be able
1639 to debug any program that you develop using GPS.
1641 @enumerate a
1642 @item @emph{Initializing}
1644 Select @code{Debug}, then @code{Initialize}, then @file{example}
1646 @item @emph{Setting a breakpoint}
1648 After performing the initialization step, you will observe a small
1649 icon to the right of each line number.
1650 This serves as a toggle for breakpoints; clicking the icon will
1651 set a breakpoint at the corresponding line (the icon will change to
1652 a red circle with an ``x''), and clicking it again
1653 will remove the breakpoint / reset the icon.
1655 For purposes of this example, set a breakpoint at line 10 (the
1656 statement @code{Put_Line@ (Line@ (1..N));}
1658 @item @emph{Starting program execution}
1660 Select @code{Debug}, then @code{Run}.  When the
1661 @code{Program Arguments} window appears, click @code{OK}.
1662 A console window will appear; enter some line of text,
1663 e.g.@: @code{abcde}, at the prompt.
1664 The program will pause execution when it gets to the
1665 breakpoint, and the corresponding line is highlighted.
1667 @item @emph{Examining a variable}
1669 Move the mouse over one of the occurrences of the variable @code{N}.
1670 You will see the value (5) displayed, in ``tool tip'' fashion.
1671 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1672 You will see information about @code{N} appear in the @code{Debugger Data}
1673 pane, showing the value as 5.
1675 @item @emph{Assigning a new value to a variable}
1677 Right click on the @code{N} in the @code{Debugger Data} pane, and
1678 select @code{Set value of N}.
1679 When the input window appears, enter the value @code{4} and click
1680 @code{OK}.
1681 This value does not automatically appear in the @code{Debugger Data}
1682 pane; to see it, right click again on the @code{N} in the
1683 @code{Debugger Data} pane and select @code{Update value}.
1684 The new value, 4, will appear in red.
1686 @item @emph{Single stepping}
1688 Select @code{Debug}, then @code{Next}.
1689 This will cause the next statement to be executed, in this case the
1690 call of @code{Put_Line} with the string slice.
1691 Notice in the console window that the displayed string is simply
1692 @code{abcd} and not @code{abcde} which you had entered.
1693 This is because the upper bound of the slice is now 4 rather than 5.
1695 @item @emph{Removing a breakpoint}
1697 Toggle the breakpoint icon at line 10.
1699 @item @emph{Resuming execution from a breakpoint}
1701 Select @code{Debug}, then @code{Continue}.
1702 The program will reach the next iteration of the loop, and
1703 wait for input after displaying the prompt.
1704 This time, just hit the @kbd{Enter} key.
1705 The value of @code{N} will be 0, and the program will terminate.
1706 The console window will disappear.
1707 @end enumerate
1708 @end enumerate
1709 @end ifclear
1711 @node The GNAT Compilation Model
1712 @chapter The GNAT Compilation Model
1713 @cindex GNAT compilation model
1714 @cindex Compilation model
1716 @menu
1717 * Source Representation::
1718 * Foreign Language Representation::
1719 * File Naming Rules::
1720 * Using Other File Names::
1721 * Alternative File Naming Schemes::
1722 * Generating Object Files::
1723 * Source Dependencies::
1724 * The Ada Library Information Files::
1725 * Binding an Ada Program::
1726 * Mixed Language Programming::
1727 @ifclear vms
1728 * Building Mixed Ada & C++ Programs::
1729 * Comparison between GNAT and C/C++ Compilation Models::
1730 @end ifclear
1731 * Comparison between GNAT and Conventional Ada Library Models::
1732 @ifset vms
1733 * Placement of temporary files::
1734 @end ifset
1735 @end menu
1737 @noindent
1738 This chapter describes the compilation model used by GNAT. Although
1739 similar to that used by other languages, such as C and C++, this model
1740 is substantially different from the traditional Ada compilation models,
1741 which are based on a library. The model is initially described without
1742 reference to the library-based model. If you have not previously used an
1743 Ada compiler, you need only read the first part of this chapter. The
1744 last section describes and discusses the differences between the GNAT
1745 model and the traditional Ada compiler models. If you have used other
1746 Ada compilers, this section will help you to understand those
1747 differences, and the advantages of the GNAT model.
1749 @node Source Representation
1750 @section Source Representation
1751 @cindex Latin-1
1753 @noindent
1754 Ada source programs are represented in standard text files, using
1755 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1756 7-bit ASCII set, plus additional characters used for
1757 representing foreign languages (@pxref{Foreign Language Representation}
1758 for support of non-USA character sets). The format effector characters
1759 are represented using their standard ASCII encodings, as follows:
1761 @table @code
1762 @item VT
1763 @findex VT
1764 Vertical tab, @code{16#0B#}
1766 @item HT
1767 @findex HT
1768 Horizontal tab, @code{16#09#}
1770 @item CR
1771 @findex CR
1772 Carriage return, @code{16#0D#}
1774 @item LF
1775 @findex LF
1776 Line feed, @code{16#0A#}
1778 @item FF
1779 @findex FF
1780 Form feed, @code{16#0C#}
1781 @end table
1783 @noindent
1784 Source files are in standard text file format. In addition, GNAT will
1785 recognize a wide variety of stream formats, in which the end of
1786 physical lines is marked by any of the following sequences:
1787 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1788 in accommodating files that are imported from other operating systems.
1790 @cindex End of source file
1791 @cindex Source file, end
1792 @findex SUB
1793 The end of a source file is normally represented by the physical end of
1794 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1795 recognized as signalling the end of the source file. Again, this is
1796 provided for compatibility with other operating systems where this
1797 code is used to represent the end of file.
1799 Each file contains a single Ada compilation unit, including any pragmas
1800 associated with the unit. For example, this means you must place a
1801 package declaration (a package @dfn{spec}) and the corresponding body in
1802 separate files. An Ada @dfn{compilation} (which is a sequence of
1803 compilation units) is represented using a sequence of files. Similarly,
1804 you will place each subunit or child unit in a separate file.
1806 @node Foreign Language Representation
1807 @section Foreign Language Representation
1809 @noindent
1810 GNAT supports the standard character sets defined in Ada as well as
1811 several other non-standard character sets for use in localized versions
1812 of the compiler (@pxref{Character Set Control}).
1813 @menu
1814 * Latin-1::
1815 * Other 8-Bit Codes::
1816 * Wide Character Encodings::
1817 @end menu
1819 @node Latin-1
1820 @subsection Latin-1
1821 @cindex Latin-1
1823 @noindent
1824 The basic character set is Latin-1. This character set is defined by ISO
1825 standard 8859, part 1. The lower half (character codes @code{16#00#}
1826 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1827 half is used to represent additional characters. These include extended letters
1828 used by European languages, such as French accents, the vowels with umlauts
1829 used in German, and the extra letter A-ring used in Swedish.
1831 @findex Ada.Characters.Latin_1
1832 For a complete list of Latin-1 codes and their encodings, see the source
1833 file of library unit @code{Ada.Characters.Latin_1} in file
1834 @file{a-chlat1.ads}.
1835 You may use any of these extended characters freely in character or
1836 string literals. In addition, the extended characters that represent
1837 letters can be used in identifiers.
1839 @node Other 8-Bit Codes
1840 @subsection Other 8-Bit Codes
1842 @noindent
1843 GNAT also supports several other 8-bit coding schemes:
1845 @table @asis
1846 @item ISO 8859-2 (Latin-2)
1847 @cindex Latin-2
1848 @cindex ISO 8859-2
1849 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1850 equivalence.
1852 @item ISO 8859-3 (Latin-3)
1853 @cindex Latin-3
1854 @cindex ISO 8859-3
1855 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1856 equivalence.
1858 @item ISO 8859-4 (Latin-4)
1859 @cindex Latin-4
1860 @cindex ISO 8859-4
1861 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1862 equivalence.
1864 @item ISO 8859-5 (Cyrillic)
1865 @cindex ISO 8859-5
1866 @cindex Cyrillic
1867 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1868 lowercase equivalence.
1870 @item ISO 8859-15 (Latin-9)
1871 @cindex ISO 8859-15
1872 @cindex Latin-9
1873 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1874 lowercase equivalence
1876 @item IBM PC (code page 437)
1877 @cindex code page 437
1878 This code page is the normal default for PCs in the U.S. It corresponds
1879 to the original IBM PC character set. This set has some, but not all, of
1880 the extended Latin-1 letters, but these letters do not have the same
1881 encoding as Latin-1. In this mode, these letters are allowed in
1882 identifiers with uppercase and lowercase equivalence.
1884 @item IBM PC (code page 850)
1885 @cindex code page 850
1886 This code page is a modification of 437 extended to include all the
1887 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1888 mode, all these letters are allowed in identifiers with uppercase and
1889 lowercase equivalence.
1891 @item Full Upper 8-bit
1892 Any character in the range 80-FF allowed in identifiers, and all are
1893 considered distinct. In other words, there are no uppercase and lowercase
1894 equivalences in this range. This is useful in conjunction with
1895 certain encoding schemes used for some foreign character sets (e.g.,
1896 the typical method of representing Chinese characters on the PC).
1898 @item No Upper-Half
1899 No upper-half characters in the range 80-FF are allowed in identifiers.
1900 This gives Ada 83 compatibility for identifier names.
1901 @end table
1903 @noindent
1904 For precise data on the encodings permitted, and the uppercase and lowercase
1905 equivalences that are recognized, see the file @file{csets.adb} in
1906 the GNAT compiler sources. You will need to obtain a full source release
1907 of GNAT to obtain this file.
1909 @node Wide Character Encodings
1910 @subsection Wide Character Encodings
1912 @noindent
1913 GNAT allows wide character codes to appear in character and string
1914 literals, and also optionally in identifiers, by means of the following
1915 possible encoding schemes:
1917 @table @asis
1919 @item Hex Coding
1920 In this encoding, a wide character is represented by the following five
1921 character sequence:
1923 @smallexample
1924 ESC a b c d
1925 @end smallexample
1927 @noindent
1928 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1929 characters (using uppercase letters) of the wide character code. For
1930 example, ESC A345 is used to represent the wide character with code
1931 @code{16#A345#}.
1932 This scheme is compatible with use of the full Wide_Character set.
1934 @item Upper-Half Coding
1935 @cindex Upper-Half Coding
1936 The wide character with encoding @code{16#abcd#} where the upper bit is on
1937 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1938 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1939 character, but is not required to be in the upper half. This method can
1940 be also used for shift-JIS or EUC, where the internal coding matches the
1941 external coding.
1943 @item Shift JIS Coding
1944 @cindex Shift JIS Coding
1945 A wide character is represented by a two-character sequence,
1946 @code{16#ab#} and
1947 @code{16#cd#}, with the restrictions described for upper-half encoding as
1948 described above. The internal character code is the corresponding JIS
1949 character according to the standard algorithm for Shift-JIS
1950 conversion. Only characters defined in the JIS code set table can be
1951 used with this encoding method.
1953 @item EUC Coding
1954 @cindex EUC Coding
1955 A wide character is represented by a two-character sequence
1956 @code{16#ab#} and
1957 @code{16#cd#}, with both characters being in the upper half. The internal
1958 character code is the corresponding JIS character according to the EUC
1959 encoding algorithm. Only characters defined in the JIS code set table
1960 can be used with this encoding method.
1962 @item UTF-8 Coding
1963 A wide character is represented using
1964 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1965 10646-1/Am.2. Depending on the character value, the representation
1966 is a one, two, or three byte sequence:
1967 @smallexample
1968 @iftex
1969 @leftskip=.7cm
1970 @end iftex
1971 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1972 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1973 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1975 @end smallexample
1977 @noindent
1978 where the @var{xxx} bits correspond to the left-padded bits of the
1979 16-bit character value. Note that all lower half ASCII characters
1980 are represented as ASCII bytes and all upper half characters and
1981 other wide characters are represented as sequences of upper-half
1982 (The full UTF-8 scheme allows for encoding 31-bit characters as
1983 6-byte sequences, but in this implementation, all UTF-8 sequences
1984 of four or more bytes length will be treated as illegal).
1985 @item Brackets Coding
1986 In this encoding, a wide character is represented by the following eight
1987 character sequence:
1989 @smallexample
1990 [ " a b c d " ]
1991 @end smallexample
1993 @noindent
1994 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1995 characters (using uppercase letters) of the wide character code. For
1996 example, [``A345''] is used to represent the wide character with code
1997 @code{16#A345#}. It is also possible (though not required) to use the
1998 Brackets coding for upper half characters. For example, the code
1999 @code{16#A3#} can be represented as @code{[``A3'']}.
2001 This scheme is compatible with use of the full Wide_Character set,
2002 and is also the method used for wide character encoding in the standard
2003 ACVC (Ada Compiler Validation Capability) test suite distributions.
2005 @end table
2007 @noindent
2008 Note: Some of these coding schemes do not permit the full use of the
2009 Ada character set. For example, neither Shift JIS, nor EUC allow the
2010 use of the upper half of the Latin-1 set.
2012 @node File Naming Rules
2013 @section File Naming Rules
2015 @noindent
2016 The default file name is determined by the name of the unit that the
2017 file contains. The name is formed by taking the full expanded name of
2018 the unit and replacing the separating dots with hyphens and using
2019 ^lowercase^uppercase^ for all letters.
2021 An exception arises if the file name generated by the above rules starts
2022 with one of the characters
2023 @ifset vms
2024 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2025 @end ifset
2026 @ifclear vms
2027 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2028 @end ifclear
2029 and the second character is a
2030 minus. In this case, the character ^tilde^dollar sign^ is used in place
2031 of the minus. The reason for this special rule is to avoid clashes with
2032 the standard names for child units of the packages System, Ada,
2033 Interfaces, and GNAT, which use the prefixes
2034 @ifset vms
2035 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2036 @end ifset
2037 @ifclear vms
2038 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2039 @end ifclear
2040 respectively.
2042 The file extension is @file{.ads} for a spec and
2043 @file{.adb} for a body. The following list shows some
2044 examples of these rules.
2046 @table @file
2047 @item main.ads
2048 Main (spec)
2049 @item main.adb
2050 Main (body)
2051 @item arith_functions.ads
2052 Arith_Functions (package spec)
2053 @item arith_functions.adb
2054 Arith_Functions (package body)
2055 @item func-spec.ads
2056 Func.Spec (child package spec)
2057 @item func-spec.adb
2058 Func.Spec (child package body)
2059 @item main-sub.adb
2060 Sub (subunit of Main)
2061 @item ^a~bad.adb^A$BAD.ADB^
2062 A.Bad (child package body)
2063 @end table
2065 @noindent
2066 Following these rules can result in excessively long
2067 file names if corresponding
2068 unit names are long (for example, if child units or subunits are
2069 heavily nested). An option is available to shorten such long file names
2070 (called file name ``krunching''). This may be particularly useful when
2071 programs being developed with GNAT are to be used on operating systems
2072 with limited file name lengths. @xref{Using gnatkr}.
2074 Of course, no file shortening algorithm can guarantee uniqueness over
2075 all possible unit names; if file name krunching is used, it is your
2076 responsibility to ensure no name clashes occur. Alternatively you
2077 can specify the exact file names that you want used, as described
2078 in the next section. Finally, if your Ada programs are migrating from a
2079 compiler with a different naming convention, you can use the gnatchop
2080 utility to produce source files that follow the GNAT naming conventions.
2081 (For details @pxref{Renaming Files Using gnatchop}.)
2083 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2084 systems, case is not significant. So for example on @code{Windows XP}
2085 if the canonical name is @code{main-sub.adb}, you can use the file name
2086 @code{Main-Sub.adb} instead. However, case is significant for other
2087 operating systems, so for example, if you want to use other than
2088 canonically cased file names on a Unix system, you need to follow
2089 the procedures described in the next section.
2091 @node Using Other File Names
2092 @section Using Other File Names
2093 @cindex File names
2095 @noindent
2096 In the previous section, we have described the default rules used by
2097 GNAT to determine the file name in which a given unit resides. It is
2098 often convenient to follow these default rules, and if you follow them,
2099 the compiler knows without being explicitly told where to find all
2100 the files it needs.
2102 However, in some cases, particularly when a program is imported from
2103 another Ada compiler environment, it may be more convenient for the
2104 programmer to specify which file names contain which units. GNAT allows
2105 arbitrary file names to be used by means of the Source_File_Name pragma.
2106 The form of this pragma is as shown in the following examples:
2107 @cindex Source_File_Name pragma
2109 @smallexample @c ada
2110 @cartouche
2111 pragma Source_File_Name (My_Utilities.Stacks,
2112   Spec_File_Name => "myutilst_a.ada");
2113 pragma Source_File_name (My_Utilities.Stacks,
2114   Body_File_Name => "myutilst.ada");
2115 @end cartouche
2116 @end smallexample
2118 @noindent
2119 As shown in this example, the first argument for the pragma is the unit
2120 name (in this example a child unit). The second argument has the form
2121 of a named association. The identifier
2122 indicates whether the file name is for a spec or a body;
2123 the file name itself is given by a string literal.
2125 The source file name pragma is a configuration pragma, which means that
2126 normally it will be placed in the @file{gnat.adc}
2127 file used to hold configuration
2128 pragmas that apply to a complete compilation environment.
2129 For more details on how the @file{gnat.adc} file is created and used
2130 see @ref{Handling of Configuration Pragmas}.
2131 @cindex @file{gnat.adc}
2133 @ifclear vms
2134 GNAT allows completely arbitrary file names to be specified using the
2135 source file name pragma. However, if the file name specified has an
2136 extension other than @file{.ads} or @file{.adb} it is necessary to use
2137 a special syntax when compiling the file. The name in this case must be
2138 preceded by the special sequence @option{-x} followed by a space and the name
2139 of the language, here @code{ada}, as in:
2141 @smallexample
2142 $ gcc -c -x ada peculiar_file_name.sim
2143 @end smallexample
2144 @end ifclear
2146 @noindent
2147 @command{gnatmake} handles non-standard file names in the usual manner (the
2148 non-standard file name for the main program is simply used as the
2149 argument to gnatmake). Note that if the extension is also non-standard,
2150 then it must be included in the @command{gnatmake} command, it may not
2151 be omitted.
2153 @node Alternative File Naming Schemes
2154 @section Alternative File Naming Schemes
2155 @cindex File naming schemes, alternative
2156 @cindex File names
2158 In the previous section, we described the use of the @code{Source_File_Name}
2159 pragma to allow arbitrary names to be assigned to individual source files.
2160 However, this approach requires one pragma for each file, and especially in
2161 large systems can result in very long @file{gnat.adc} files, and also create
2162 a maintenance problem.
2164 GNAT also provides a facility for specifying systematic file naming schemes
2165 other than the standard default naming scheme previously described. An
2166 alternative scheme for naming is specified by the use of
2167 @code{Source_File_Name} pragmas having the following format:
2168 @cindex Source_File_Name pragma
2170 @smallexample @c ada
2171 pragma Source_File_Name (
2172    Spec_File_Name  => FILE_NAME_PATTERN
2173  @r{[},Casing          => CASING_SPEC@r{]}
2174  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2176 pragma Source_File_Name (
2177    Body_File_Name  => FILE_NAME_PATTERN
2178  @r{[},Casing          => CASING_SPEC@r{]}
2179  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2181 pragma Source_File_Name (
2182    Subunit_File_Name  => FILE_NAME_PATTERN
2183  @r{[},Casing             => CASING_SPEC@r{]}
2184  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2186 FILE_NAME_PATTERN ::= STRING_LITERAL
2187 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2188 @end smallexample
2190 @noindent
2191 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2192 It contains a single asterisk character, and the unit name is substituted
2193 systematically for this asterisk. The optional parameter
2194 @code{Casing} indicates
2195 whether the unit name is to be all upper-case letters, all lower-case letters,
2196 or mixed-case. If no
2197 @code{Casing} parameter is used, then the default is all
2198 ^lower-case^upper-case^.
2200 The optional @code{Dot_Replacement} string is used to replace any periods
2201 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2202 argument is used then separating dots appear unchanged in the resulting
2203 file name.
2204 Although the above syntax indicates that the
2205 @code{Casing} argument must appear
2206 before the @code{Dot_Replacement} argument, but it
2207 is also permissible to write these arguments in the opposite order.
2209 As indicated, it is possible to specify different naming schemes for
2210 bodies, specs, and subunits. Quite often the rule for subunits is the
2211 same as the rule for bodies, in which case, there is no need to give
2212 a separate @code{Subunit_File_Name} rule, and in this case the
2213 @code{Body_File_name} rule is used for subunits as well.
2215 The separate rule for subunits can also be used to implement the rather
2216 unusual case of a compilation environment (e.g.@: a single directory) which
2217 contains a subunit and a child unit with the same unit name. Although
2218 both units cannot appear in the same partition, the Ada Reference Manual
2219 allows (but does not require) the possibility of the two units coexisting
2220 in the same environment.
2222 The file name translation works in the following steps:
2224 @itemize @bullet
2226 @item
2227 If there is a specific @code{Source_File_Name} pragma for the given unit,
2228 then this is always used, and any general pattern rules are ignored.
2230 @item
2231 If there is a pattern type @code{Source_File_Name} pragma that applies to
2232 the unit, then the resulting file name will be used if the file exists. If
2233 more than one pattern matches, the latest one will be tried first, and the
2234 first attempt resulting in a reference to a file that exists will be used.
2236 @item
2237 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2238 for which the corresponding file exists, then the standard GNAT default
2239 naming rules are used.
2241 @end itemize
2243 @noindent
2244 As an example of the use of this mechanism, consider a commonly used scheme
2245 in which file names are all lower case, with separating periods copied
2246 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2247 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2248 two pragmas appear:
2250 @smallexample @c ada
2251 pragma Source_File_Name
2252   (Spec_File_Name => "*.1.ada");
2253 pragma Source_File_Name
2254   (Body_File_Name => "*.2.ada");
2255 @end smallexample
2257 @noindent
2258 The default GNAT scheme is actually implemented by providing the following
2259 default pragmas internally:
2261 @smallexample @c ada
2262 pragma Source_File_Name
2263   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2264 pragma Source_File_Name
2265   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2266 @end smallexample
2268 @noindent
2269 Our final example implements a scheme typically used with one of the
2270 Ada 83 compilers, where the separator character for subunits was ``__''
2271 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2272 by adding @file{.ADA}, and subunits by
2273 adding @file{.SEP}. All file names were
2274 upper case. Child units were not present of course since this was an
2275 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2276 the same double underscore separator for child units.
2278 @smallexample @c ada
2279 pragma Source_File_Name
2280   (Spec_File_Name => "*_.ADA",
2281    Dot_Replacement => "__",
2282    Casing = Uppercase);
2283 pragma Source_File_Name
2284   (Body_File_Name => "*.ADA",
2285    Dot_Replacement => "__",
2286    Casing = Uppercase);
2287 pragma Source_File_Name
2288   (Subunit_File_Name => "*.SEP",
2289    Dot_Replacement => "__",
2290    Casing = Uppercase);
2291 @end smallexample
2293 @node Generating Object Files
2294 @section Generating Object Files
2296 @noindent
2297 An Ada program consists of a set of source files, and the first step in
2298 compiling the program is to generate the corresponding object files.
2299 These are generated by compiling a subset of these source files.
2300 The files you need to compile are the following:
2302 @itemize @bullet
2303 @item
2304 If a package spec has no body, compile the package spec to produce the
2305 object file for the package.
2307 @item
2308 If a package has both a spec and a body, compile the body to produce the
2309 object file for the package. The source file for the package spec need
2310 not be compiled in this case because there is only one object file, which
2311 contains the code for both the spec and body of the package.
2313 @item
2314 For a subprogram, compile the subprogram body to produce the object file
2315 for the subprogram. The spec, if one is present, is as usual in a
2316 separate file, and need not be compiled.
2318 @item
2319 @cindex Subunits
2320 In the case of subunits, only compile the parent unit. A single object
2321 file is generated for the entire subunit tree, which includes all the
2322 subunits.
2324 @item
2325 Compile child units independently of their parent units
2326 (though, of course, the spec of all the ancestor unit must be present in order
2327 to compile a child unit).
2329 @item
2330 @cindex Generics
2331 Compile generic units in the same manner as any other units. The object
2332 files in this case are small dummy files that contain at most the
2333 flag used for elaboration checking. This is because GNAT always handles generic
2334 instantiation by means of macro expansion. However, it is still necessary to
2335 compile generic units, for dependency checking and elaboration purposes.
2336 @end itemize
2338 @noindent
2339 The preceding rules describe the set of files that must be compiled to
2340 generate the object files for a program. Each object file has the same
2341 name as the corresponding source file, except that the extension is
2342 @file{.o} as usual.
2344 You may wish to compile other files for the purpose of checking their
2345 syntactic and semantic correctness. For example, in the case where a
2346 package has a separate spec and body, you would not normally compile the
2347 spec. However, it is convenient in practice to compile the spec to make
2348 sure it is error-free before compiling clients of this spec, because such
2349 compilations will fail if there is an error in the spec.
2351 GNAT provides an option for compiling such files purely for the
2352 purposes of checking correctness; such compilations are not required as
2353 part of the process of building a program. To compile a file in this
2354 checking mode, use the @option{-gnatc} switch.
2356 @node Source Dependencies
2357 @section Source Dependencies
2359 @noindent
2360 A given object file clearly depends on the source file which is compiled
2361 to produce it. Here we are using @dfn{depends} in the sense of a typical
2362 @code{make} utility; in other words, an object file depends on a source
2363 file if changes to the source file require the object file to be
2364 recompiled.
2365 In addition to this basic dependency, a given object may depend on
2366 additional source files as follows:
2368 @itemize @bullet
2369 @item
2370 If a file being compiled @code{with}'s a unit @var{X}, the object file
2371 depends on the file containing the spec of unit @var{X}. This includes
2372 files that are @code{with}'ed implicitly either because they are parents
2373 of @code{with}'ed child units or they are run-time units required by the
2374 language constructs used in a particular unit.
2376 @item
2377 If a file being compiled instantiates a library level generic unit, the
2378 object file depends on both the spec and body files for this generic
2379 unit.
2381 @item
2382 If a file being compiled instantiates a generic unit defined within a
2383 package, the object file depends on the body file for the package as
2384 well as the spec file.
2386 @item
2387 @findex Inline
2388 @cindex @option{-gnatn} switch
2389 If a file being compiled contains a call to a subprogram for which
2390 pragma @code{Inline} applies and inlining is activated with the
2391 @option{-gnatn} switch, the object file depends on the file containing the
2392 body of this subprogram as well as on the file containing the spec. Note
2393 that for inlining to actually occur as a result of the use of this switch,
2394 it is necessary to compile in optimizing mode.
2396 @cindex @option{-gnatN} switch
2397 The use of @option{-gnatN} activates  inlining optimization
2398 that is performed by the front end of the compiler. This inlining does
2399 not require that the code generation be optimized. Like @option{-gnatn},
2400 the use of this switch generates additional dependencies.
2402 When using a gcc-based back end (in practice this means using any version
2403 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2404 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2405 Historically front end inlining was more extensive than the gcc back end
2406 inlining, but that is no longer the case.
2408 @item
2409 If an object file @file{O} depends on the proper body of a subunit through
2410 inlining or instantiation, it depends on the parent unit of the subunit.
2411 This means that any modification of the parent unit or one of its subunits
2412 affects the compilation of @file{O}.
2414 @item
2415 The object file for a parent unit depends on all its subunit body files.
2417 @item
2418 The previous two rules meant that for purposes of computing dependencies and
2419 recompilation, a body and all its subunits are treated as an indivisible whole.
2421 @noindent
2422 These rules are applied transitively: if unit @code{A} @code{with}'s
2423 unit @code{B}, whose elaboration calls an inlined procedure in package
2424 @code{C}, the object file for unit @code{A} will depend on the body of
2425 @code{C}, in file @file{c.adb}.
2427 The set of dependent files described by these rules includes all the
2428 files on which the unit is semantically dependent, as dictated by the
2429 Ada language standard. However, it is a superset of what the
2430 standard describes, because it includes generic, inline, and subunit
2431 dependencies.
2433 An object file must be recreated by recompiling the corresponding source
2434 file if any of the source files on which it depends are modified. For
2435 example, if the @code{make} utility is used to control compilation,
2436 the rule for an Ada object file must mention all the source files on
2437 which the object file depends, according to the above definition.
2438 The determination of the necessary
2439 recompilations is done automatically when one uses @command{gnatmake}.
2440 @end itemize
2442 @node The Ada Library Information Files
2443 @section The Ada Library Information Files
2444 @cindex Ada Library Information files
2445 @cindex @file{ALI} files
2447 @noindent
2448 Each compilation actually generates two output files. The first of these
2449 is the normal object file that has a @file{.o} extension. The second is a
2450 text file containing full dependency information. It has the same
2451 name as the source file, but an @file{.ali} extension.
2452 This file is known as the Ada Library Information (@file{ALI}) file.
2453 The following information is contained in the @file{ALI} file.
2455 @itemize @bullet
2456 @item
2457 Version information (indicates which version of GNAT was used to compile
2458 the unit(s) in question)
2460 @item
2461 Main program information (including priority and time slice settings,
2462 as well as the wide character encoding used during compilation).
2464 @item
2465 List of arguments used in the @command{gcc} command for the compilation
2467 @item
2468 Attributes of the unit, including configuration pragmas used, an indication
2469 of whether the compilation was successful, exception model used etc.
2471 @item
2472 A list of relevant restrictions applying to the unit (used for consistency)
2473 checking.
2475 @item
2476 Categorization information (e.g.@: use of pragma @code{Pure}).
2478 @item
2479 Information on all @code{with}'ed units, including presence of
2480 @code{Elaborate} or @code{Elaborate_All} pragmas.
2482 @item
2483 Information from any @code{Linker_Options} pragmas used in the unit
2485 @item
2486 Information on the use of @code{Body_Version} or @code{Version}
2487 attributes in the unit.
2489 @item
2490 Dependency information. This is a list of files, together with
2491 time stamp and checksum information. These are files on which
2492 the unit depends in the sense that recompilation is required
2493 if any of these units are modified.
2495 @item
2496 Cross-reference data. Contains information on all entities referenced
2497 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2498 provide cross-reference information.
2500 @end itemize
2502 @noindent
2503 For a full detailed description of the format of the @file{ALI} file,
2504 see the source of the body of unit @code{Lib.Writ}, contained in file
2505 @file{lib-writ.adb} in the GNAT compiler sources.
2507 @node Binding an Ada Program
2508 @section Binding an Ada Program
2510 @noindent
2511 When using languages such as C and C++, once the source files have been
2512 compiled the only remaining step in building an executable program
2513 is linking the object modules together. This means that it is possible to
2514 link an inconsistent version of a program, in which two units have
2515 included different versions of the same header.
2517 The rules of Ada do not permit such an inconsistent program to be built.
2518 For example, if two clients have different versions of the same package,
2519 it is illegal to build a program containing these two clients.
2520 These rules are enforced by the GNAT binder, which also determines an
2521 elaboration order consistent with the Ada rules.
2523 The GNAT binder is run after all the object files for a program have
2524 been created. It is given the name of the main program unit, and from
2525 this it determines the set of units required by the program, by reading the
2526 corresponding ALI files. It generates error messages if the program is
2527 inconsistent or if no valid order of elaboration exists.
2529 If no errors are detected, the binder produces a main program, in Ada by
2530 default, that contains calls to the elaboration procedures of those
2531 compilation unit that require them, followed by
2532 a call to the main program. This Ada program is compiled to generate the
2533 object file for the main program. The name of
2534 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2535 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2536 main program unit.
2538 Finally, the linker is used to build the resulting executable program,
2539 using the object from the main program from the bind step as well as the
2540 object files for the Ada units of the program.
2542 @node Mixed Language Programming
2543 @section Mixed Language Programming
2544 @cindex Mixed Language Programming
2546 @noindent
2547 This section describes how to develop a mixed-language program,
2548 specifically one that comprises units in both Ada and C.
2550 @menu
2551 * Interfacing to C::
2552 * Calling Conventions::
2553 @end menu
2555 @node Interfacing to C
2556 @subsection Interfacing to C
2557 @noindent
2558 Interfacing Ada with a foreign language such as C involves using
2559 compiler directives to import and/or export entity definitions in each
2560 language---using @code{extern} statements in C, for instance, and the
2561 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2562 A full treatment of these topics is provided in Appendix B, section 1
2563 of the Ada Reference Manual.
2565 There are two ways to build a program using GNAT that contains some Ada
2566 sources and some foreign language sources, depending on whether or not
2567 the main subprogram is written in Ada.  Here is a source example with
2568 the main subprogram in Ada:
2570 @smallexample
2571 /* file1.c */
2572 #include <stdio.h>
2574 void print_num (int num)
2576   printf ("num is %d.\n", num);
2577   return;
2580 /* file2.c */
2582 /* num_from_Ada is declared in my_main.adb */
2583 extern int num_from_Ada;
2585 int get_num (void)
2587   return num_from_Ada;
2589 @end smallexample
2591 @smallexample @c ada
2592 --  my_main.adb
2593 procedure My_Main is
2595    --  Declare then export an Integer entity called num_from_Ada
2596    My_Num : Integer := 10;
2597    pragma Export (C, My_Num, "num_from_Ada");
2599    --  Declare an Ada function spec for Get_Num, then use
2600    --  C function get_num for the implementation.
2601    function Get_Num return Integer;
2602    pragma Import (C, Get_Num, "get_num");
2604    --  Declare an Ada procedure spec for Print_Num, then use
2605    --  C function print_num for the implementation.
2606    procedure Print_Num (Num : Integer);
2607    pragma Import (C, Print_Num, "print_num");
2609 begin
2610    Print_Num (Get_Num);
2611 end My_Main;
2612 @end smallexample
2614 @enumerate
2615 @item
2616 To build this example, first compile the foreign language files to
2617 generate object files:
2618 @smallexample
2619 ^gcc -c file1.c^gcc -c FILE1.C^
2620 ^gcc -c file2.c^gcc -c FILE2.C^
2621 @end smallexample
2623 @item
2624 Then, compile the Ada units to produce a set of object files and ALI
2625 files:
2626 @smallexample
2627 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2628 @end smallexample
2630 @item
2631 Run the Ada binder on the Ada main program:
2632 @smallexample
2633 gnatbind my_main.ali
2634 @end smallexample
2636 @item
2637 Link the Ada main program, the Ada objects and the other language
2638 objects:
2639 @smallexample
2640 gnatlink my_main.ali file1.o file2.o
2641 @end smallexample
2642 @end enumerate
2644 The last three steps can be grouped in a single command:
2645 @smallexample
2646 gnatmake my_main.adb -largs file1.o file2.o
2647 @end smallexample
2649 @cindex Binder output file
2650 @noindent
2651 If the main program is in a language other than Ada, then you may have
2652 more than one entry point into the Ada subsystem. You must use a special
2653 binder option to generate callable routines that initialize and
2654 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2655 Calls to the initialization and finalization routines must be inserted
2656 in the main program, or some other appropriate point in the code. The
2657 call to initialize the Ada units must occur before the first Ada
2658 subprogram is called, and the call to finalize the Ada units must occur
2659 after the last Ada subprogram returns. The binder will place the
2660 initialization and finalization subprograms into the
2661 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2662 sources.  To illustrate, we have the following example:
2664 @smallexample
2665 /* main.c */
2666 extern void adainit (void);
2667 extern void adafinal (void);
2668 extern int add (int, int);
2669 extern int sub (int, int);
2671 int main (int argc, char *argv[])
2673   int a = 21, b = 7;
2675   adainit();
2677   /* Should print "21 + 7 = 28" */
2678   printf ("%d + %d = %d\n", a, b, add (a, b));
2679   /* Should print "21 - 7 = 14" */
2680   printf ("%d - %d = %d\n", a, b, sub (a, b));
2682   adafinal();
2684 @end smallexample
2686 @smallexample @c ada
2687 --  unit1.ads
2688 package Unit1 is
2689    function Add (A, B : Integer) return Integer;
2690    pragma Export (C, Add, "add");
2691 end Unit1;
2693 --  unit1.adb
2694 package body Unit1 is
2695    function Add (A, B : Integer) return Integer is
2696    begin
2697       return A + B;
2698    end Add;
2699 end Unit1;
2701 --  unit2.ads
2702 package Unit2 is
2703    function Sub (A, B : Integer) return Integer;
2704    pragma Export (C, Sub, "sub");
2705 end Unit2;
2707 --  unit2.adb
2708 package body Unit2 is
2709    function Sub (A, B : Integer) return Integer is
2710    begin
2711       return A - B;
2712    end Sub;
2713 end Unit2;
2714 @end smallexample
2716 @enumerate
2717 @item
2718 The build procedure for this application is similar to the last
2719 example's.  First, compile the foreign language files to generate object
2720 files:
2721 @smallexample
2722 ^gcc -c main.c^gcc -c main.c^
2723 @end smallexample
2725 @item
2726 Next, compile the Ada units to produce a set of object files and ALI
2727 files:
2728 @smallexample
2729 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2730 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2731 @end smallexample
2733 @item
2734 Run the Ada binder on every generated ALI file.  Make sure to use the
2735 @option{-n} option to specify a foreign main program:
2736 @smallexample
2737 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2738 @end smallexample
2740 @item
2741 Link the Ada main program, the Ada objects and the foreign language
2742 objects. You need only list the last ALI file here:
2743 @smallexample
2744 gnatlink unit2.ali main.o -o exec_file
2745 @end smallexample
2747 This procedure yields a binary executable called @file{exec_file}.
2748 @end enumerate
2750 @noindent
2751 Depending on the circumstances (for example when your non-Ada main object
2752 does not provide symbol @code{main}), you may also need to instruct the
2753 GNAT linker not to include the standard startup objects by passing the
2754 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2756 @node Calling Conventions
2757 @subsection Calling Conventions
2758 @cindex Foreign Languages
2759 @cindex Calling Conventions
2760 GNAT follows standard calling sequence conventions and will thus interface
2761 to any other language that also follows these conventions. The following
2762 Convention identifiers are recognized by GNAT:
2764 @table @code
2765 @cindex Interfacing to Ada
2766 @cindex Other Ada compilers
2767 @cindex Convention Ada
2768 @item Ada
2769 This indicates that the standard Ada calling sequence will be
2770 used and all Ada data items may be passed without any limitations in the
2771 case where GNAT is used to generate both the caller and callee. It is also
2772 possible to mix GNAT generated code and code generated by another Ada
2773 compiler. In this case, the data types should be restricted to simple
2774 cases, including primitive types. Whether complex data types can be passed
2775 depends on the situation. Probably it is safe to pass simple arrays, such
2776 as arrays of integers or floats. Records may or may not work, depending
2777 on whether both compilers lay them out identically. Complex structures
2778 involving variant records, access parameters, tasks, or protected types,
2779 are unlikely to be able to be passed.
2781 Note that in the case of GNAT running
2782 on a platform that supports HP Ada 83, a higher degree of compatibility
2783 can be guaranteed, and in particular records are layed out in an identical
2784 manner in the two compilers. Note also that if output from two different
2785 compilers is mixed, the program is responsible for dealing with elaboration
2786 issues. Probably the safest approach is to write the main program in the
2787 version of Ada other than GNAT, so that it takes care of its own elaboration
2788 requirements, and then call the GNAT-generated adainit procedure to ensure
2789 elaboration of the GNAT components. Consult the documentation of the other
2790 Ada compiler for further details on elaboration.
2792 However, it is not possible to mix the tasking run time of GNAT and
2793 HP Ada 83, All the tasking operations must either be entirely within
2794 GNAT compiled sections of the program, or entirely within HP Ada 83
2795 compiled sections of the program.
2797 @cindex Interfacing to Assembly
2798 @cindex Convention Assembler
2799 @item Assembler
2800 Specifies assembler as the convention. In practice this has the
2801 same effect as convention Ada (but is not equivalent in the sense of being
2802 considered the same convention).
2804 @cindex Convention Asm
2805 @findex Asm
2806 @item Asm
2807 Equivalent to Assembler.
2809 @cindex Interfacing to COBOL
2810 @cindex Convention COBOL
2811 @findex COBOL
2812 @item COBOL
2813 Data will be passed according to the conventions described
2814 in section B.4 of the Ada Reference Manual.
2816 @findex C
2817 @cindex Interfacing to C
2818 @cindex Convention C
2819 @item C
2820 Data will be passed according to the conventions described
2821 in section B.3 of the Ada Reference Manual.
2823 A note on interfacing to a C ``varargs'' function:
2824 @findex C varargs function
2825 @cindex Interfacing to C varargs function
2826 @cindex varargs function interfaces
2828 @itemize @bullet
2829 @item
2830 In C, @code{varargs} allows a function to take a variable number of
2831 arguments. There is no direct equivalent in this to Ada. One
2832 approach that can be used is to create a C wrapper for each
2833 different profile and then interface to this C wrapper. For
2834 example, to print an @code{int} value using @code{printf},
2835 create a C function @code{printfi} that takes two arguments, a
2836 pointer to a string and an int, and calls @code{printf}.
2837 Then in the Ada program, use pragma @code{Import} to
2838 interface to @code{printfi}.
2840 @item
2841 It may work on some platforms to directly interface to
2842 a @code{varargs} function by providing a specific Ada profile
2843 for a particular call. However, this does not work on
2844 all platforms, since there is no guarantee that the
2845 calling sequence for a two argument normal C function
2846 is the same as for calling a @code{varargs} C function with
2847 the same two arguments.
2848 @end itemize
2850 @cindex Convention Default
2851 @findex Default
2852 @item Default
2853 Equivalent to C.
2855 @cindex Convention External
2856 @findex External
2857 @item External
2858 Equivalent to C.
2860 @ifclear vms
2861 @findex C++
2862 @cindex Interfacing to C++
2863 @cindex Convention C++
2864 @item C_Plus_Plus (or CPP)
2865 This stands for C++. For most purposes this is identical to C.
2866 See the separate description of the specialized GNAT pragmas relating to
2867 C++ interfacing for further details.
2868 @end ifclear
2870 @findex Fortran
2871 @cindex Interfacing to Fortran
2872 @cindex Convention Fortran
2873 @item Fortran
2874 Data will be passed according to the conventions described
2875 in section B.5 of the Ada Reference Manual.
2877 @item Intrinsic
2878 This applies to an intrinsic operation, as defined in the Ada
2879 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2880 this means that the body of the subprogram is provided by the compiler itself,
2881 usually by means of an efficient code sequence, and that the user does not
2882 supply an explicit body for it. In an application program, the pragma may
2883 be applied to the following sets of names:
2885 @itemize @bullet
2886 @item
2887 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2888 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2889 two formal parameters. The
2890 first one must be a signed integer type or a modular type with a binary
2891 modulus, and the second parameter must be of type Natural.
2892 The return type must be the same as the type of the first argument. The size
2893 of this type can only be 8, 16, 32, or 64.
2895 @item
2896 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2897 The corresponding operator declaration must have parameters and result type
2898 that have the same root numeric type (for example, all three are long_float
2899 types). This simplifies the definition of operations that use type checking
2900 to perform dimensional checks:
2902 @smallexample @c ada
2903 type Distance is new Long_Float;
2904 type Time     is new Long_Float;
2905 type Velocity is new Long_Float;
2906 function "/" (D : Distance; T : Time)
2907   return Velocity;
2908 pragma Import (Intrinsic, "/");
2909 @end smallexample
2911 @noindent
2912 This common idiom is often programmed with a generic definition and an
2913 explicit body. The pragma makes it simpler to introduce such declarations.
2914 It incurs no overhead in compilation time or code size, because it is
2915 implemented as a single machine instruction.
2917 @item
2918 General subprogram entities, to bind an Ada subprogram declaration to
2919 a compiler builtin by name with back-ends where such interfaces are
2920 available. A typical example is the set of ``__builtin'' functions
2921 exposed by the GCC back-end, as in the following example:
2923 @smallexample @c ada
2924    function builtin_sqrt (F : Float) return Float;
2925    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2926 @end smallexample
2928 Most of the GCC builtins are accessible this way, and as for other
2929 import conventions (e.g. C), it is the user's responsibility to ensure
2930 that the Ada subprogram profile matches the underlying builtin
2931 expectations.
2932 @end itemize
2934 @noindent
2936 @ifset unw
2937 @findex Stdcall
2938 @cindex Convention Stdcall
2939 @item Stdcall
2940 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2941 and specifies that the @code{Stdcall} calling sequence will be used,
2942 as defined by the NT API. Nevertheless, to ease building
2943 cross-platform bindings this convention will be handled as a @code{C} calling
2944 convention on non-Windows platforms.
2946 @findex DLL
2947 @cindex Convention DLL
2948 @item DLL
2949 This is equivalent to @code{Stdcall}.
2951 @findex Win32
2952 @cindex Convention Win32
2953 @item Win32
2954 This is equivalent to @code{Stdcall}.
2955 @end ifset
2957 @findex Stubbed
2958 @cindex Convention Stubbed
2959 @item Stubbed
2960 This is a special convention that indicates that the compiler
2961 should provide a stub body that raises @code{Program_Error}.
2962 @end table
2964 @noindent
2965 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2966 that can be used to parameterize conventions and allow additional synonyms
2967 to be specified. For example if you have legacy code in which the convention
2968 identifier Fortran77 was used for Fortran, you can use the configuration
2969 pragma:
2971 @smallexample @c ada
2972 pragma Convention_Identifier (Fortran77, Fortran);
2973 @end smallexample
2975 @noindent
2976 And from now on the identifier Fortran77 may be used as a convention
2977 identifier (for example in an @code{Import} pragma) with the same
2978 meaning as Fortran.
2980 @ifclear vms
2981 @node Building Mixed Ada & C++ Programs
2982 @section Building Mixed Ada and C++ Programs
2984 @noindent
2985 A programmer inexperienced with mixed-language development may find that
2986 building an application containing both Ada and C++ code can be a
2987 challenge.  This section gives a few
2988 hints that should make this task easier. The first section addresses
2989 the differences between interfacing with C and interfacing with C++.
2990 The second section
2991 looks into the delicate problem of linking the complete application from
2992 its Ada and C++ parts. The last section gives some hints on how the GNAT
2993 run-time library can be adapted in order to allow inter-language dispatching
2994 with a new C++ compiler.
2996 @menu
2997 * Interfacing to C++::
2998 * Linking a Mixed C++ & Ada Program::
2999 * A Simple Example::
3000 * Interfacing with C++ constructors::
3001 * Interfacing with C++ at the Class Level::
3002 @end menu
3004 @node Interfacing to C++
3005 @subsection Interfacing to C++
3007 @noindent
3008 GNAT supports interfacing with the G++ compiler (or any C++ compiler
3009 generating code that is compatible with the G++ Application Binary
3010 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
3012 @noindent
3013 Interfacing can be done at 3 levels: simple data, subprograms, and
3014 classes. In the first two cases, GNAT offers a specific @code{Convention
3015 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
3016 Usually, C++ mangles the names of subprograms. To generate proper mangled
3017 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
3018 This problem can also be addressed manually in two ways:
3020 @itemize @bullet
3021 @item
3022 by modifying the C++ code in order to force a C convention using
3023 the @code{extern "C"} syntax.
3025 @item
3026 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3027 Link_Name argument of the pragma import.
3028 @end itemize
3030 @noindent
3031 Interfacing at the class level can be achieved by using the GNAT specific
3032 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3033 gnat_rm, GNAT Reference Manual}, for additional information.
3035 @node Linking a Mixed C++ & Ada Program
3036 @subsection Linking a Mixed C++ & Ada Program
3038 @noindent
3039 Usually the linker of the C++ development system must be used to link
3040 mixed applications because most C++ systems will resolve elaboration
3041 issues (such as calling constructors on global class instances)
3042 transparently during the link phase. GNAT has been adapted to ease the
3043 use of a foreign linker for the last phase. Three cases can be
3044 considered:
3045 @enumerate
3047 @item
3048 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3049 The C++ linker can simply be called by using the C++ specific driver
3050 called @code{g++}.
3052 Note that if the C++ code uses inline functions, you will need to
3053 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3054 order to provide an existing function implementation that the Ada code can
3055 link with.
3057 @smallexample
3058 $ g++ -c -fkeep-inline-functions file1.C
3059 $ g++ -c -fkeep-inline-functions file2.C
3060 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3061 @end smallexample
3063 @item
3064 Using GNAT and G++ from two different GCC installations: If both
3065 compilers are on the @env{PATH}, the previous method may be used. It is
3066 important to note that environment variables such as
3067 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3068 @env{GCC_ROOT} will affect both compilers
3069 at the same time and may make one of the two compilers operate
3070 improperly if set during invocation of the wrong compiler.  It is also
3071 very important that the linker uses the proper @file{libgcc.a} GCC
3072 library -- that is, the one from the C++ compiler installation. The
3073 implicit link command as suggested in the @command{gnatmake} command
3074 from the former example can be replaced by an explicit link command with
3075 the full-verbosity option in order to verify which library is used:
3076 @smallexample
3077 $ gnatbind ada_unit
3078 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3079 @end smallexample
3080 If there is a problem due to interfering environment variables, it can
3081 be worked around by using an intermediate script. The following example
3082 shows the proper script to use when GNAT has not been installed at its
3083 default location and g++ has been installed at its default location:
3085 @smallexample
3086 $ cat ./my_script
3087 #!/bin/sh
3088 unset BINUTILS_ROOT
3089 unset GCC_ROOT
3090 c++ $*
3091 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3092 @end smallexample
3094 @item
3095 Using a non-GNU C++ compiler: The commands previously described can be
3096 used to insure that the C++ linker is used. Nonetheless, you need to add
3097 a few more parameters to the link command line, depending on the exception
3098 mechanism used.
3100 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3101 to the libgcc libraries are required:
3103 @smallexample
3104 $ cat ./my_script
3105 #!/bin/sh
3106 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3107 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3108 @end smallexample
3110 Where CC is the name of the non-GNU C++ compiler.
3112 If the @code{zero cost} exception mechanism is used, and the platform
3113 supports automatic registration of exception tables (e.g.@: Solaris),
3114 paths to more objects are required:
3116 @smallexample
3117 $ cat ./my_script
3118 #!/bin/sh
3119 CC `gcc -print-file-name=crtbegin.o` $* \
3120 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3121 `gcc -print-file-name=crtend.o`
3122 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3123 @end smallexample
3125 If the @code{zero cost} exception mechanism is used, and the platform
3126 doesn't support automatic registration of exception tables (e.g.@: HP-UX
3127 or AIX), the simple approach described above will not work and
3128 a pre-linking phase using GNAT will be necessary.
3130 @end enumerate
3132 Another alternative is to use the @command{gprbuild} multi-language builder
3133 which has a large knowledge base and knows how to link Ada and C++ code
3134 together automatically in most cases.
3136 @node A Simple Example
3137 @subsection  A Simple Example
3138 @noindent
3139 The following example, provided as part of the GNAT examples, shows how
3140 to achieve procedural interfacing between Ada and C++ in both
3141 directions. The C++ class A has two methods. The first method is exported
3142 to Ada by the means of an extern C wrapper function. The second method
3143 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3144 a limited record with a layout comparable to the C++ class. The Ada
3145 subprogram, in turn, calls the C++ method. So, starting from the C++
3146 main program, the process passes back and forth between the two
3147 languages.
3149 @noindent
3150 Here are the compilation commands:
3151 @smallexample
3152 $ gnatmake -c simple_cpp_interface
3153 $ g++ -c cpp_main.C
3154 $ g++ -c ex7.C
3155 $ gnatbind -n simple_cpp_interface
3156 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3157       -lstdc++ ex7.o cpp_main.o
3158 @end smallexample
3160 @noindent
3161 Here are the corresponding sources:
3162 @smallexample
3164 //cpp_main.C
3166 #include "ex7.h"
3168 extern "C" @{
3169   void adainit (void);
3170   void adafinal (void);
3171   void method1 (A *t);
3174 void method1 (A *t)
3176   t->method1 ();
3179 int main ()
3181   A obj;
3182   adainit ();
3183   obj.method2 (3030);
3184   adafinal ();
3187 //ex7.h
3189 class Origin @{
3190  public:
3191   int o_value;
3193 class A : public Origin @{
3194  public:
3195   void method1 (void);
3196   void method2 (int v);
3197   A();
3198   int   a_value;
3201 //ex7.C
3203 #include "ex7.h"
3204 #include <stdio.h>
3206 extern "C" @{ void ada_method2 (A *t, int v);@}
3208 void A::method1 (void)
3210   a_value = 2020;
3211   printf ("in A::method1, a_value = %d \n",a_value);
3215 void A::method2 (int v)
3217    ada_method2 (this, v);
3218    printf ("in A::method2, a_value = %d \n",a_value);
3222 A::A(void)
3224    a_value = 1010;
3225   printf ("in A::A, a_value = %d \n",a_value);
3227 @end smallexample
3229 @smallexample @c ada
3230 -- Ada sources
3231 package body Simple_Cpp_Interface is
3233    procedure Ada_Method2 (This : in out A; V : Integer) is
3234    begin
3235       Method1 (This);
3236       This.A_Value := V;
3237    end Ada_Method2;
3239 end Simple_Cpp_Interface;
3241 with System;
3242 package Simple_Cpp_Interface is
3243    type A is limited
3244       record
3245          Vptr    : System.Address;
3246          O_Value : Integer;
3247          A_Value : Integer;
3248       end record;
3249    pragma Convention (C, A);
3251    procedure Method1 (This : in out A);
3252    pragma Import (C, Method1);
3254    procedure Ada_Method2 (This : in out A; V : Integer);
3255    pragma Export (C, Ada_Method2);
3257 end Simple_Cpp_Interface;
3258 @end smallexample
3260 @node Interfacing with C++ constructors
3261 @subsection Interfacing with C++ constructors
3262 @noindent
3264 In order to interface with C++ constructors GNAT provides the
3265 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3266 gnat_rm, GNAT Reference Manual}, for additional information).
3267 In this section we present some common uses of C++ constructors
3268 in mixed-languages programs in GNAT.
3270 Let us assume that we need to interface with the following
3271 C++ class:
3273 @smallexample
3274 @b{class} Root @{
3275 @b{public}:
3276   int  a_value;
3277   int  b_value;
3278   @b{virtual} int Get_Value ();
3279   Root();              // Default constructor
3280   Root(int v);         // 1st non-default constructor
3281   Root(int v, int w);  // 2nd non-default constructor
3283 @end smallexample
3285 For this purpose we can write the following package spec (further
3286 information on how to build this spec is available in
3287 @ref{Interfacing with C++ at the Class Level} and
3288 @ref{Generating Ada Bindings for C and C++ headers}).
3290 @smallexample @c ada
3291 with Interfaces.C; use Interfaces.C;
3292 package Pkg_Root is
3293   type Root is tagged limited record
3294      A_Value : int;
3295      B_Value : int;
3296   end record;
3297   pragma Import (CPP, Root);
3299   function Get_Value (Obj : Root) return int;
3300   pragma Import (CPP, Get_Value);
3302   function Constructor return Root;
3303   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3305   function Constructor (v : Integer) return Root;
3306   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3308   function Constructor (v, w : Integer) return Root;
3309   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3310 end Pkg_Root;
3311 @end smallexample
3313 On the Ada side the constructor is represented by a function (whose
3314 name is arbitrary) that returns the classwide type corresponding to
3315 the imported C++ class. Although the constructor is described as a
3316 function, it is typically a procedure with an extra implicit argument
3317 (the object being initialized) at the implementation level. GNAT
3318 issues the appropriate call, whatever it is, to get the object
3319 properly initialized.
3321 Constructors can only appear in the following contexts:
3323 @itemize @bullet
3324 @item
3325 On the right side of an initialization of an object of type @var{T}.
3326 @item
3327 On the right side of an initialization of a record component of type @var{T}.
3328 @item
3329 In an Ada 2005 limited aggregate.
3330 @item
3331 In an Ada 2005 nested limited aggregate.
3332 @item
3333 In an Ada 2005 limited aggregate that initializes an object built in
3334 place by an extended return statement.
3335 @end itemize
3337 @noindent
3338 In a declaration of an object whose type is a class imported from C++,
3339 either the default C++ constructor is implicitly called by GNAT, or
3340 else the required C++ constructor must be explicitly called in the
3341 expression that initializes the object. For example:
3343 @smallexample @c ada
3344   Obj1 : Root;
3345   Obj2 : Root := Constructor;
3346   Obj3 : Root := Constructor (v => 10);
3347   Obj4 : Root := Constructor (30, 40);
3348 @end smallexample
3350 The first two declarations are equivalent: in both cases the default C++
3351 constructor is invoked (in the former case the call to the constructor is
3352 implicit, and in the latter case the call is explicit in the object
3353 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3354 that takes an integer argument, and @code{Obj4} is initialized by the
3355 non-default C++ constructor that takes two integers.
3357 Let us derive the imported C++ class in the Ada side. For example:
3359 @smallexample @c ada
3360   type DT is new Root with record
3361      C_Value : Natural := 2009;
3362   end record;
3363 @end smallexample
3365 In this case the components DT inherited from the C++ side must be
3366 initialized by a C++ constructor, and the additional Ada components
3367 of type DT are initialized by GNAT. The initialization of such an
3368 object is done either by default, or by means of a function returning
3369 an aggregate of type DT, or by means of an extension aggregate.
3371 @smallexample @c ada
3372   Obj5 : DT;
3373   Obj6 : DT := Function_Returning_DT (50);
3374   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3375 @end smallexample
3377 The declaration of @code{Obj5} invokes the default constructors: the
3378 C++ default constructor of the parent type takes care of the initialization
3379 of the components inherited from Root, and GNAT takes care of the default
3380 initialization of the additional Ada components of type DT (that is,
3381 @code{C_Value} is initialized to value 2009). The order of invocation of
3382 the constructors is consistent with the order of elaboration required by
3383 Ada and C++. That is, the constructor of the parent type is always called
3384 before the constructor of the derived type.
3386 Let us now consider a record that has components whose type is imported
3387 from C++. For example:
3389 @smallexample @c ada
3390   type Rec1 is limited record
3391      Data1 : Root := Constructor (10);
3392      Value : Natural := 1000;
3393   end record;
3395   type Rec2 (D : Integer := 20) is limited record
3396      Rec   : Rec1;
3397      Data2 : Root := Constructor (D, 30);
3398   end record;
3399 @end smallexample
3401 The initialization of an object of type @code{Rec2} will call the
3402 non-default C++ constructors specified for the imported components.
3403 For example:
3405 @smallexample @c ada
3406   Obj8 : Rec2 (40);
3407 @end smallexample
3409 Using Ada 2005 we can use limited aggregates to initialize an object
3410 invoking C++ constructors that differ from those specified in the type
3411 declarations. For example:
3413 @smallexample @c ada
3414   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3415                           others => <>),
3416                   others => <>);
3417 @end smallexample
3419 The above declaration uses an Ada 2005 limited aggregate to
3420 initialize @code{Obj9}, and the C++ constructor that has two integer
3421 arguments is invoked to initialize the @code{Data1} component instead
3422 of the constructor specified in the declaration of type @code{Rec1}. In
3423 Ada 2005 the box in the aggregate indicates that unspecified components
3424 are initialized using the expression (if any) available in the component
3425 declaration. That is, in this case discriminant @code{D} is initialized
3426 to value @code{20}, @code{Value} is initialized to value 1000, and the
3427 non-default C++ constructor that handles two integers takes care of
3428 initializing component @code{Data2} with values @code{20,30}.
3430 In Ada 2005 we can use the extended return statement to build the Ada
3431 equivalent to C++ non-default constructors. For example:
3433 @smallexample @c ada
3434   function Constructor (V : Integer) return Rec2 is
3435   begin
3436      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3437                                    others => <>),
3438                            others => <>) do
3439         --  Further actions required for construction of
3440         --  objects of type Rec2
3441         ...
3442      end record;
3443   end Constructor;
3444 @end smallexample
3446 In this example the extended return statement construct is used to
3447 build in place the returned object whose components are initialized
3448 by means of a limited aggregate. Any further action associated with
3449 the constructor can be placed inside the construct.
3451 @node Interfacing with C++ at the Class Level
3452 @subsection Interfacing with C++ at the Class Level
3453 @noindent
3454 In this section we demonstrate the GNAT features for interfacing with
3455 C++ by means of an example making use of Ada 2005 abstract interface
3456 types. This example consists of a classification of animals; classes
3457 have been used to model our main classification of animals, and
3458 interfaces provide support for the management of secondary
3459 classifications. We first demonstrate a case in which the types and
3460 constructors are defined on the C++ side and imported from the Ada
3461 side, and latter the reverse case.
3463 The root of our derivation will be the @code{Animal} class, with a
3464 single private attribute (the @code{Age} of the animal) and two public
3465 primitives to set and get the value of this attribute.
3467 @smallexample
3468 @b{class} Animal @{
3469  @b{public}:
3470    @b{virtual} void Set_Age (int New_Age);
3471    @b{virtual} int Age ();
3472  @b{private}:
3473    int Age_Count;
3475 @end smallexample
3477 Abstract interface types are defined in C++ by means of classes with pure
3478 virtual functions and no data members. In our example we will use two
3479 interfaces that provide support for the common management of @code{Carnivore}
3480 and @code{Domestic} animals:
3482 @smallexample
3483 @b{class} Carnivore @{
3484 @b{public}:
3485    @b{virtual} int Number_Of_Teeth () = 0;
3488 @b{class} Domestic @{
3489 @b{public}:
3490    @b{virtual void} Set_Owner (char* Name) = 0;
3492 @end smallexample
3494 Using these declarations, we can now say that a @code{Dog} is an animal that is
3495 both Carnivore and Domestic, that is:
3497 @smallexample
3498 @b{class} Dog : Animal, Carnivore, Domestic @{
3499  @b{public}:
3500    @b{virtual} int  Number_Of_Teeth ();
3501    @b{virtual} void Set_Owner (char* Name);
3503    Dog(); // Constructor
3504  @b{private}:
3505    int  Tooth_Count;
3506    char *Owner;
3508 @end smallexample
3510 In the following examples we will assume that the previous declarations are
3511 located in a file named @code{animals.h}. The following package demonstrates
3512 how to import these C++ declarations from the Ada side:
3514 @smallexample @c ada
3515 with Interfaces.C.Strings; use Interfaces.C.Strings;
3516 package Animals is
3517   type Carnivore is interface;
3518   pragma Convention (C_Plus_Plus, Carnivore);
3519   function Number_Of_Teeth (X : Carnivore)
3520      return Natural is abstract;
3522   type Domestic is interface;
3523   pragma Convention (C_Plus_Plus, Set_Owner);
3524   procedure Set_Owner
3525     (X    : in out Domestic;
3526      Name : Chars_Ptr) is abstract;
3528   type Animal is tagged record
3529     Age : Natural := 0;
3530   end record;
3531   pragma Import (C_Plus_Plus, Animal);
3533   procedure Set_Age (X : in out Animal; Age : Integer);
3534   pragma Import (C_Plus_Plus, Set_Age);
3536   function Age (X : Animal) return Integer;
3537   pragma Import (C_Plus_Plus, Age);
3539   type Dog is new Animal and Carnivore and Domestic with record
3540     Tooth_Count : Natural;
3541     Owner       : String (1 .. 30);
3542   end record;
3543   pragma Import (C_Plus_Plus, Dog);
3545   function Number_Of_Teeth (A : Dog) return Integer;
3546   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3548   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3549   pragma Import (C_Plus_Plus, Set_Owner);
3551   function New_Dog return Dog;
3552   pragma CPP_Constructor (New_Dog);
3553   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3554 end Animals;
3555 @end smallexample
3557 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3558 interfacing with these C++ classes is easy. The only requirement is that all
3559 the primitives and components must be declared exactly in the same order in
3560 the two languages.
3562 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3563 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3564 the arguments to the called primitives will be the same as for C++. For the
3565 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3566 to indicate that they have been defined on the C++ side; this is required
3567 because the dispatch table associated with these tagged types will be built
3568 in the C++ side and therefore will not contain the predefined Ada primitives
3569 which Ada would otherwise expect.
3571 As the reader can see there is no need to indicate the C++ mangled names
3572 associated with each subprogram because it is assumed that all the calls to
3573 these primitives will be dispatching calls. The only exception is the
3574 constructor, which must be registered with the compiler by means of
3575 @code{pragma CPP_Constructor} and needs to provide its associated C++
3576 mangled name because the Ada compiler generates direct calls to it.
3578 With the above packages we can now declare objects of type Dog on the Ada side
3579 and dispatch calls to the corresponding subprograms on the C++ side. We can
3580 also extend the tagged type Dog with further fields and primitives, and
3581 override some of its C++ primitives on the Ada side. For example, here we have
3582 a type derivation defined on the Ada side that inherits all the dispatching
3583 primitives of the ancestor from the C++ side.
3585 @smallexample
3586 @b{with} Animals; @b{use} Animals;
3587 @b{package} Vaccinated_Animals @b{is}
3588   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3589   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3590 @b{end} Vaccinated_Animals;
3591 @end smallexample
3593 It is important to note that, because of the ABI compatibility, the programmer
3594 does not need to add any further information to indicate either the object
3595 layout or the dispatch table entry associated with each dispatching operation.
3597 Now let us define all the types and constructors on the Ada side and export
3598 them to C++, using the same hierarchy of our previous example:
3600 @smallexample @c ada
3601 with Interfaces.C.Strings;
3602 use Interfaces.C.Strings;
3603 package Animals is
3604   type Carnivore is interface;
3605   pragma Convention (C_Plus_Plus, Carnivore);
3606   function Number_Of_Teeth (X : Carnivore)
3607      return Natural is abstract;
3609   type Domestic is interface;
3610   pragma Convention (C_Plus_Plus, Set_Owner);
3611   procedure Set_Owner
3612     (X    : in out Domestic;
3613      Name : Chars_Ptr) is abstract;
3615   type Animal is tagged record
3616     Age : Natural := 0;
3617   end record;
3618   pragma Convention (C_Plus_Plus, Animal);
3620   procedure Set_Age (X : in out Animal; Age : Integer);
3621   pragma Export (C_Plus_Plus, Set_Age);
3623   function Age (X : Animal) return Integer;
3624   pragma Export (C_Plus_Plus, Age);
3626   type Dog is new Animal and Carnivore and Domestic with record
3627     Tooth_Count : Natural;
3628     Owner       : String (1 .. 30);
3629   end record;
3630   pragma Convention (C_Plus_Plus, Dog);
3632   function Number_Of_Teeth (A : Dog) return Integer;
3633   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3635   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3636   pragma Export (C_Plus_Plus, Set_Owner);
3638   function New_Dog return Dog'Class;
3639   pragma Export (C_Plus_Plus, New_Dog);
3640 end Animals;
3641 @end smallexample
3643 Compared with our previous example the only difference is the use of
3644 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3645 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3646 nothing else to be done; as explained above, the only requirement is that all
3647 the primitives and components are declared in exactly the same order.
3649 For completeness, let us see a brief C++ main program that uses the
3650 declarations available in @code{animals.h} (presented in our first example) to
3651 import and use the declarations from the Ada side, properly initializing and
3652 finalizing the Ada run-time system along the way:
3654 @smallexample
3655 @b{#include} "animals.h"
3656 @b{#include} <iostream>
3657 @b{using namespace} std;
3659 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3660 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3661 void Check_Animal (Animal *obj)       @{@dots{}@}
3662 void Check_Dog (Dog *obj)             @{@dots{}@}
3664 @b{extern} "C" @{
3665   void adainit (void);
3666   void adafinal (void);
3667   Dog* new_dog ();
3670 void test ()
3672   Dog *obj = new_dog();  // Ada constructor
3673   Check_Carnivore (obj); // Check secondary DT
3674   Check_Domestic (obj);  // Check secondary DT
3675   Check_Animal (obj);    // Check primary DT
3676   Check_Dog (obj);       // Check primary DT
3679 int main ()
3681   adainit ();  test();  adafinal ();
3682   return 0;
3684 @end smallexample
3686 @node Comparison between GNAT and C/C++ Compilation Models
3687 @section Comparison between GNAT and C/C++ Compilation Models
3689 @noindent
3690 The GNAT model of compilation is close to the C and C++ models. You can
3691 think of Ada specs as corresponding to header files in C. As in C, you
3692 don't need to compile specs; they are compiled when they are used. The
3693 Ada @code{with} is similar in effect to the @code{#include} of a C
3694 header.
3696 One notable difference is that, in Ada, you may compile specs separately
3697 to check them for semantic and syntactic accuracy. This is not always
3698 possible with C headers because they are fragments of programs that have
3699 less specific syntactic or semantic rules.
3701 The other major difference is the requirement for running the binder,
3702 which performs two important functions. First, it checks for
3703 consistency. In C or C++, the only defense against assembling
3704 inconsistent programs lies outside the compiler, in a makefile, for
3705 example. The binder satisfies the Ada requirement that it be impossible
3706 to construct an inconsistent program when the compiler is used in normal
3707 mode.
3709 @cindex Elaboration order control
3710 The other important function of the binder is to deal with elaboration
3711 issues. There are also elaboration issues in C++ that are handled
3712 automatically. This automatic handling has the advantage of being
3713 simpler to use, but the C++ programmer has no control over elaboration.
3714 Where @code{gnatbind} might complain there was no valid order of
3715 elaboration, a C++ compiler would simply construct a program that
3716 malfunctioned at run time.
3717 @end ifclear
3719 @node Comparison between GNAT and Conventional Ada Library Models
3720 @section Comparison between GNAT and Conventional Ada Library Models
3722 @noindent
3723 This section is intended for Ada programmers who have
3724 used an Ada compiler implementing the traditional Ada library
3725 model, as described in the Ada Reference Manual.
3727 @cindex GNAT library
3728 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3729 source files themselves acts as the library. Compiling Ada programs does
3730 not generate any centralized information, but rather an object file and
3731 a ALI file, which are of interest only to the binder and linker.
3732 In a traditional system, the compiler reads information not only from
3733 the source file being compiled, but also from the centralized library.
3734 This means that the effect of a compilation depends on what has been
3735 previously compiled. In particular:
3737 @itemize @bullet
3738 @item
3739 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3740 to the version of the unit most recently compiled into the library.
3742 @item
3743 Inlining is effective only if the necessary body has already been
3744 compiled into the library.
3746 @item
3747 Compiling a unit may obsolete other units in the library.
3748 @end itemize
3750 @noindent
3751 In GNAT, compiling one unit never affects the compilation of any other
3752 units because the compiler reads only source files. Only changes to source
3753 files can affect the results of a compilation. In particular:
3755 @itemize @bullet
3756 @item
3757 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3758 to the source version of the unit that is currently accessible to the
3759 compiler.
3761 @item
3762 @cindex Inlining
3763 Inlining requires the appropriate source files for the package or
3764 subprogram bodies to be available to the compiler. Inlining is always
3765 effective, independent of the order in which units are complied.
3767 @item
3768 Compiling a unit never affects any other compilations. The editing of
3769 sources may cause previous compilations to be out of date if they
3770 depended on the source file being modified.
3771 @end itemize
3773 @noindent
3774 The most important result of these differences is that order of compilation
3775 is never significant in GNAT. There is no situation in which one is
3776 required to do one compilation before another. What shows up as order of
3777 compilation requirements in the traditional Ada library becomes, in
3778 GNAT, simple source dependencies; in other words, there is only a set
3779 of rules saying what source files must be present when a file is
3780 compiled.
3782 @ifset vms
3783 @node Placement of temporary files
3784 @section Placement of temporary files
3785 @cindex Temporary files (user control over placement)
3787 @noindent
3788 GNAT creates temporary files in the directory designated by the environment
3789 variable @env{TMPDIR}.
3790 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3791 for detailed information on how environment variables are resolved.
3792 For most users the easiest way to make use of this feature is to simply
3793 define @env{TMPDIR} as a job level logical name).
3794 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3795 for compiler temporary files, then you can include something like the
3796 following command in your @file{LOGIN.COM} file:
3798 @smallexample
3799 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3800 @end smallexample
3802 @noindent
3803 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3804 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3805 designated by @env{TEMP}.
3806 If none of these environment variables are defined then GNAT uses the
3807 directory designated by the logical name @code{SYS$SCRATCH:}
3808 (by default the user's home directory). If all else fails
3809 GNAT uses the current directory for temporary files.
3810 @end ifset
3812 @c *************************
3813 @node Compiling Using gcc
3814 @chapter Compiling Using @command{gcc}
3816 @noindent
3817 This chapter discusses how to compile Ada programs using the @command{gcc}
3818 command. It also describes the set of switches
3819 that can be used to control the behavior of the compiler.
3820 @menu
3821 * Compiling Programs::
3822 * Switches for gcc::
3823 * Search Paths and the Run-Time Library (RTL)::
3824 * Order of Compilation Issues::
3825 * Examples::
3826 @end menu
3828 @node Compiling Programs
3829 @section Compiling Programs
3831 @noindent
3832 The first step in creating an executable program is to compile the units
3833 of the program using the @command{gcc} command. You must compile the
3834 following files:
3836 @itemize @bullet
3837 @item
3838 the body file (@file{.adb}) for a library level subprogram or generic
3839 subprogram
3841 @item
3842 the spec file (@file{.ads}) for a library level package or generic
3843 package that has no body
3845 @item
3846 the body file (@file{.adb}) for a library level package
3847 or generic package that has a body
3849 @end itemize
3851 @noindent
3852 You need @emph{not} compile the following files
3854 @itemize @bullet
3856 @item
3857 the spec of a library unit which has a body
3859 @item
3860 subunits
3861 @end itemize
3863 @noindent
3864 because they are compiled as part of compiling related units. GNAT
3865 package specs
3866 when the corresponding body is compiled, and subunits when the parent is
3867 compiled.
3869 @cindex cannot generate code
3870 If you attempt to compile any of these files, you will get one of the
3871 following error messages (where @var{fff} is the name of the file you
3872 compiled):
3874 @smallexample
3875 cannot generate code for file @var{fff} (package spec)
3876 to check package spec, use -gnatc
3878 cannot generate code for file @var{fff} (missing subunits)
3879 to check parent unit, use -gnatc
3881 cannot generate code for file @var{fff} (subprogram spec)
3882 to check subprogram spec, use -gnatc
3884 cannot generate code for file @var{fff} (subunit)
3885 to check subunit, use -gnatc
3886 @end smallexample
3888 @noindent
3889 As indicated by the above error messages, if you want to submit
3890 one of these files to the compiler to check for correct semantics
3891 without generating code, then use the @option{-gnatc} switch.
3893 The basic command for compiling a file containing an Ada unit is
3895 @smallexample
3896 @c $ gcc -c @ovar{switches} @file{file name}
3897 @c Expanding @ovar macro inline (explanation in macro def comments)
3898 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3899 @end smallexample
3901 @noindent
3902 where @var{file name} is the name of the Ada file (usually
3903 having an extension
3904 @file{.ads} for a spec or @file{.adb} for a body).
3905 @ifclear vms
3906 You specify the
3907 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3908 @end ifclear
3909 The result of a successful compilation is an object file, which has the
3910 same name as the source file but an extension of @file{.o} and an Ada
3911 Library Information (ALI) file, which also has the same name as the
3912 source file, but with @file{.ali} as the extension. GNAT creates these
3913 two output files in the current directory, but you may specify a source
3914 file in any directory using an absolute or relative path specification
3915 containing the directory information.
3917 @findex gnat1
3918 @command{gcc} is actually a driver program that looks at the extensions of
3919 the file arguments and loads the appropriate compiler. For example, the
3920 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3921 These programs are in directories known to the driver program (in some
3922 configurations via environment variables you set), but need not be in
3923 your path. The @command{gcc} driver also calls the assembler and any other
3924 utilities needed to complete the generation of the required object
3925 files.
3927 It is possible to supply several file names on the same @command{gcc}
3928 command. This causes @command{gcc} to call the appropriate compiler for
3929 each file. For example, the following command lists three separate
3930 files to be compiled:
3932 @smallexample
3933 $ gcc -c x.adb y.adb z.c
3934 @end smallexample
3936 @noindent
3937 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3938 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3939 The compiler generates three object files @file{x.o}, @file{y.o} and
3940 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3941 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3942 @ifclear vms
3943 except for
3944 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3945 @end ifclear
3947 @node Switches for gcc
3948 @section Switches for @command{gcc}
3950 @noindent
3951 The @command{gcc} command accepts switches that control the
3952 compilation process. These switches are fully described in this section.
3953 First we briefly list all the switches, in alphabetical order, then we
3954 describe the switches in more detail in functionally grouped sections.
3956 More switches exist for GCC than those documented here, especially
3957 for specific targets. However, their use is not recommended as
3958 they may change code generation in ways that are incompatible with
3959 the Ada run-time library, or can cause inconsistencies between
3960 compilation units.
3962 @menu
3963 * Output and Error Message Control::
3964 * Warning Message Control::
3965 * Debugging and Assertion Control::
3966 * Validity Checking::
3967 * Style Checking::
3968 * Run-Time Checks::
3969 * Using gcc for Syntax Checking::
3970 * Using gcc for Semantic Checking::
3971 * Compiling Different Versions of Ada::
3972 * Character Set Control::
3973 * File Naming Control::
3974 * Subprogram Inlining Control::
3975 * Auxiliary Output Control::
3976 * Debugging Control::
3977 * Exception Handling Control::
3978 * Units to Sources Mapping Files::
3979 * Integrated Preprocessing::
3980 * Code Generation Control::
3981 @ifset vms
3982 * Return Codes::
3983 @end ifset
3984 @end menu
3986 @table @option
3987 @c !sort!
3988 @ifclear vms
3989 @cindex @option{-b} (@command{gcc})
3990 @item -b @var{target}
3991 Compile your program to run on @var{target}, which is the name of a
3992 system configuration. You must have a GNAT cross-compiler built if
3993 @var{target} is not the same as your host system.
3995 @item -B@var{dir}
3996 @cindex @option{-B} (@command{gcc})
3997 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3998 from @var{dir} instead of the default location. Only use this switch
3999 when multiple versions of the GNAT compiler are available.
4000 @xref{Directory Options,, Options for Directory Search, gcc, Using the
4001 GNU Compiler Collection (GCC)}, for further details. You would normally
4002 use the @option{-b} or @option{-V} switch instead.
4004 @item -c
4005 @cindex @option{-c} (@command{gcc})
4006 Compile. Always use this switch when compiling Ada programs.
4008 Note: for some other languages when using @command{gcc}, notably in
4009 the case of C and C++, it is possible to use
4010 use @command{gcc} without a @option{-c} switch to
4011 compile and link in one step. In the case of GNAT, you
4012 cannot use this approach, because the binder must be run
4013 and @command{gcc} cannot be used to run the GNAT binder.
4014 @end ifclear
4016 @item -fcallgraph-info@r{[}=su,da@r{]}
4017 @cindex @option{-fcallgraph-info} (@command{gcc})
4018 Makes the compiler output callgraph information for the program, on a
4019 per-file basis. The information is generated in the VCG format.  It can
4020 be decorated with additional, per-node and/or per-edge information, if a
4021 list of comma-separated markers is additionally specified. When the
4022 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
4023 marker is specified, the callgraph is decorated with information about
4024 dynamically allocated objects.
4026 @item -fdump-scos
4027 @cindex @option{-fdump-scos} (@command{gcc})
4028 Generates SCO (Source Coverage Obligation) information in the ALI file.
4029 This information is used by advanced coverage tools. See unit @file{SCOs}
4030 in the compiler sources for details in files @file{scos.ads} and
4031 @file{scos.adb}.
4033 @item -flto@r{[}=n@r{]}
4034 @cindex @option{-flto} (@command{gcc})
4035 Enables Link Time Optimization. This switch must be used in conjunction
4036 with the traditional @option{-Ox} switches and instructs the compiler to
4037 defer most optimizations until the link stage. The advantage of this
4038 approach is that the compiler can do a whole-program analysis and choose
4039 the best interprocedural optimization strategy based on a complete view
4040 of the program, instead of a fragmentary view with the usual approach.
4041 This can also speed up the compilation of huge programs and reduce the
4042 size of the final executable, compared with a per-unit compilation with
4043 full inlining across modules enabled with the @option{-gnatn2} switch.
4044 The drawback of this approach is that it may require much more memory.
4045 The switch, as well as the accompanying @option{-Ox} switches, must be
4046 specified both for the compilation and the link phases.
4047 If the @var{n} parameter is specified, the optimization and final code
4048 generation at link time are executed using @var{n} parallel jobs by
4049 means of an installed @command{make} program.
4051 @item -fno-inline
4052 @cindex @option{-fno-inline} (@command{gcc})
4053 Suppresses all inlining, even if other optimization or inlining
4054 switches are set.  This includes suppression of inlining that
4055 results from the use of the pragma @code{Inline_Always}.
4056 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4057 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4058 effects if this switch is present.  Note that inlining can also
4059 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
4061 @item -fno-inline-functions
4062 @cindex @option{-fno-inline-functions} (@command{gcc})
4063 Suppresses automatic inlining of subprograms, which is enabled
4064 if @option{-O3} is used.
4066 @item -fno-inline-small-functions
4067 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4068 Suppresses automatic inlining of small subprograms, which is enabled
4069 if @option{-O2} is used.
4071 @item -fno-inline-functions-called-once
4072 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4073 Suppresses inlining of subprograms local to the unit and called once
4074 from within it, which is enabled if @option{-O1} is used.
4076 @item -fno-ivopts
4077 @cindex @option{-fno-ivopts} (@command{gcc})
4078 Suppresses high-level loop induction variable optimizations, which are
4079 enabled if @option{-O1} is used. These optimizations are generally
4080 profitable but, for some specific cases of loops with numerous uses
4081 of the iteration variable that follow a common pattern, they may end
4082 up destroying the regularity that could be exploited at a lower level
4083 and thus producing inferior code.
4085 @item -fno-strict-aliasing
4086 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4087 Causes the compiler to avoid assumptions regarding non-aliasing
4088 of objects of different types. See
4089 @ref{Optimization and Strict Aliasing} for details.
4091 @item -fstack-check
4092 @cindex @option{-fstack-check} (@command{gcc})
4093 Activates stack checking.
4094 See @ref{Stack Overflow Checking} for details.
4096 @item -fstack-usage
4097 @cindex @option{-fstack-usage} (@command{gcc})
4098 Makes the compiler output stack usage information for the program, on a
4099 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4101 @item ^-g^/DEBUG^
4102 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4103 Generate debugging information. This information is stored in the object
4104 file and copied from there to the final executable file by the linker,
4105 where it can be read by the debugger. You must use the
4106 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4108 @item -gnat83
4109 @cindex @option{-gnat83} (@command{gcc})
4110 Enforce Ada 83 restrictions.
4112 @item -gnat95
4113 @cindex @option{-gnat95} (@command{gcc})
4114 Enforce Ada 95 restrictions.
4116 @item -gnat05
4117 @cindex @option{-gnat05} (@command{gcc})
4118 Allow full Ada 2005 features.
4120 @item -gnat2005
4121 @cindex @option{-gnat2005} (@command{gcc})
4122 Allow full Ada 2005 features (same as @option{-gnat05})
4124 @item -gnat12
4125 @cindex @option{-gnat12} (@command{gcc})
4127 @item -gnat2012
4128 @cindex @option{-gnat2012} (@command{gcc})
4129 Allow full Ada 2012 features (same as @option{-gnat12})
4131 @item -gnata
4132 @cindex @option{-gnata} (@command{gcc})
4133 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4134 activated. Note that these pragmas can also be controlled using the
4135 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4136 It also activates pragmas @code{Check}, @code{Precondition}, and
4137 @code{Postcondition}. Note that these pragmas can also be controlled
4138 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
4139 also activates all assertions defined in the RM as aspects: preconditions,
4140 postconditions, type invariants and (sub)type predicates. In all Ada modes,
4141 corresponding pragmas for type invariants and (sub)type predicates are
4142 also activated.
4144 @item -gnatA
4145 @cindex @option{-gnatA} (@command{gcc})
4146 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4147 it will be ignored.
4149 @item -gnatb
4150 @cindex @option{-gnatb} (@command{gcc})
4151 Generate brief messages to @file{stderr} even if verbose mode set.
4153 @item -gnatB
4154 @cindex @option{-gnatB} (@command{gcc})
4155 Assume no invalid (bad) values except for 'Valid attribute use
4156 (@pxref{Validity Checking}).
4158 @item -gnatc
4159 @cindex @option{-gnatc} (@command{gcc})
4160 Check syntax and semantics only (no code generation attempted).
4162 @item -gnatC
4163 @cindex @option{-gnatC} (@command{gcc})
4164 Generate CodePeer information (no code generation attempted).
4165 This switch will generate an intermediate representation suitable for
4166 use by CodePeer (@file{.scil} files). This switch is not compatible with
4167 code generation (it will, among other things, disable some switches such
4168 as -gnatn, and enable others such as -gnata).
4170 @item -gnatd
4171 @cindex @option{-gnatd} (@command{gcc})
4172 Specify debug options for the compiler. The string of characters after
4173 the @option{-gnatd} specify the specific debug options. The possible
4174 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4175 compiler source file @file{debug.adb} for details of the implemented
4176 debug options. Certain debug options are relevant to applications
4177 programmers, and these are documented at appropriate points in this
4178 users guide.
4180 @ifclear vms
4181 @item -gnatD
4182 @cindex @option{-gnatD[nn]} (@command{gcc})
4183 @end ifclear
4184 @ifset vms
4185 @item /XDEBUG /LXDEBUG=nnn
4186 @end ifset
4187 Create expanded source files for source level debugging. This switch
4188 also suppress generation of cross-reference information
4189 (see @option{-gnatx}).
4191 @item ^-gnateA^/ALIASING_CHECK^
4192 @cindex @option{-gnateA} (@command{gcc})
4193 Check that there is no aliasing between two parameters of the same subprogram.
4195 @item -gnatec=@var{path}
4196 @cindex @option{-gnatec} (@command{gcc})
4197 Specify a configuration pragma file
4198 @ifclear vms
4199 (the equal sign is optional)
4200 @end ifclear
4201 (@pxref{The Configuration Pragmas Files}).
4203 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
4204 @cindex @option{-gnated} (@command{gcc})
4205 Disable atomic synchronization
4207 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4208 @cindex @option{-gnateD} (@command{gcc})
4209 Defines a symbol, associated with @var{value}, for preprocessing.
4210 (@pxref{Integrated Preprocessing}).
4212 @item -gnateE
4213 @cindex @option{-gnateE} (@command{gcc})
4214 Generate extra information in exception messages. In particular, display
4215 extra column information and the value and range associated with index and
4216 range check failures, and extra column information for access checks.
4217 In cases where the compiler is able to determine at compile time that
4218 a check will fail, it gives a warning, and the extra information is not
4219 produced at run time.
4221 @item -gnatef
4222 @cindex @option{-gnatef} (@command{gcc})
4223 Display full source path name in brief error messages.
4225 @item -gnateF
4226 @cindex @option{-gnateF} (@command{gcc})
4227 Check for overflow on all floating-point operations, including those
4228 for unconstrained predefined types. See description of pragma
4229 @code{Check_Float_Overflow} in GNAT RM.
4231 @item -gnateG
4232 @cindex @option{-gnateG} (@command{gcc})
4233 Save result of preprocessing in a text file.
4235 @item -gnatei@var{nnn}
4236 @cindex @option{-gnatei} (@command{gcc})
4237 Set maximum number of instantiations during compilation of a single unit to
4238 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
4239 the rare case when a single unit legitimately exceeds this limit.
4241 @item -gnateI@var{nnn}
4242 @cindex @option{-gnateI} (@command{gcc})
4243 Indicates that the source is a multi-unit source and that the index of the
4244 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4245 to be a valid index in the multi-unit source.
4247 @item -gnatem=@var{path}
4248 @cindex @option{-gnatem} (@command{gcc})
4249 Specify a mapping file
4250 @ifclear vms
4251 (the equal sign is optional)
4252 @end ifclear
4253 (@pxref{Units to Sources Mapping Files}).
4255 @item -gnatep=@var{file}
4256 @cindex @option{-gnatep} (@command{gcc})
4257 Specify a preprocessing data file
4258 @ifclear vms
4259 (the equal sign is optional)
4260 @end ifclear
4261 (@pxref{Integrated Preprocessing}).
4263 @item -gnateP
4264 @cindex @option{-gnateP} (@command{gcc})
4265 Turn categorization dependency errors into warnings.
4266 Ada requires that units that WITH one another have compatible categories, for
4267 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4268 these errors become warnings (which can be ignored, or suppressed in the usual
4269 manner). This can be useful in some specialized circumstances such as the
4270 temporary use of special test software.
4272 @item -gnateS
4273 @cindex @option{-gnateS} (@command{gcc})
4274 Synonym of @option{-fdump-scos}, kept for backards compatibility.
4276 @item ^-gnatet^/TARGET_DEPENDENT_INFO^
4277 @cindex @option{-gnatet} (@command{gcc})
4278 Generate target dependent information.
4280 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
4281 @cindex @option{-gnateV} (@command{gcc})
4282 Check validity of subprogram parameters.
4284 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
4285 @cindex @option{-gnateY} (@command{gcc})
4286 Ignore all STYLE_CHECKS pragmas. Full legality checks
4287 are still carried out, but the pragmas have no effect
4288 on what style checks are active. This allows all style
4289 checking options to be controlled from the command line.
4291 @item -gnatE
4292 @cindex @option{-gnatE} (@command{gcc})
4293 Full dynamic elaboration checks.
4295 @item -gnatf
4296 @cindex @option{-gnatf} (@command{gcc})
4297 Full errors. Multiple errors per line, all undefined references, do not
4298 attempt to suppress cascaded errors.
4300 @item -gnatF
4301 @cindex @option{-gnatF} (@command{gcc})
4302 Externals names are folded to all uppercase.
4304 @item ^-gnatg^/GNAT_INTERNAL^
4305 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4306 Internal GNAT implementation mode. This should not be used for
4307 applications programs, it is intended only for use by the compiler
4308 and its run-time library. For documentation, see the GNAT sources.
4309 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4310 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4311 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4312 so that all standard warnings and all standard style options are turned on.
4313 All warnings and style messages are treated as errors.
4315 @ifclear vms
4316 @item -gnatG=nn
4317 @cindex @option{-gnatG[nn]} (@command{gcc})
4318 @end ifclear
4319 @ifset vms
4320 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4321 @end ifset
4322 List generated expanded code in source form.
4324 @item ^-gnath^/HELP^
4325 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4326 Output usage information. The output is written to @file{stdout}.
4328 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4329 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4330 Identifier character set
4331 @ifclear vms
4332 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4333 @end ifclear
4334 For details of the possible selections for @var{c},
4335 see @ref{Character Set Control}.
4337 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4338 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4339 Ignore representation clauses. When this switch is used,
4340 representation clauses are treated as comments. This is useful
4341 when initially porting code where you want to ignore rep clause
4342 problems, and also for compiling foreign code (particularly
4343 for use with ASIS). The representation clauses that are ignored
4344 are: enumeration_representation_clause, record_representation_clause,
4345 and attribute_definition_clause for the following attributes:
4346 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4347 Object_Size, Size, Small, Stream_Size, and Value_Size.
4348 Note that this option should be used only for compiling -- the
4349 code is likely to malfunction at run time.
4351 @item -gnatjnn
4352 @cindex @option{-gnatjnn} (@command{gcc})
4353 Reformat error messages to fit on nn character lines
4355 @item -gnatk=@var{n}
4356 @cindex @option{-gnatk} (@command{gcc})
4357 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4359 @item -gnatl
4360 @cindex @option{-gnatl} (@command{gcc})
4361 Output full source listing with embedded error messages.
4363 @item -gnatL
4364 @cindex @option{-gnatL} (@command{gcc})
4365 Used in conjunction with -gnatG or -gnatD to intersperse original
4366 source lines (as comment lines with line numbers) in the expanded
4367 source output.
4369 @item -gnatm=@var{n}
4370 @cindex @option{-gnatm} (@command{gcc})
4371 Limit number of detected error or warning messages to @var{n}
4372 where @var{n} is in the range 1..999999. The default setting if
4373 no switch is given is 9999. If the number of warnings reaches this
4374 limit, then a message is output and further warnings are suppressed,
4375 but the compilation is continued. If the number of error messages
4376 reaches this limit, then a message is output and the compilation
4377 is abandoned. The equal sign here is optional. A value of zero
4378 means that no limit applies.
4380 @item -gnatn[12]
4381 @cindex @option{-gnatn} (@command{gcc})
4382 Activate inlining for subprograms for which pragma @code{Inline} is
4383 specified. This inlining is performed by the GCC back-end. An optional
4384 digit sets the inlining level: 1 for moderate inlining across modules
4385 or 2 for full inlining across modules. If no inlining level is specified,
4386 the compiler will pick it based on the optimization level.
4388 @item -gnatN
4389 @cindex @option{-gnatN} (@command{gcc})
4390 Activate front end inlining for subprograms for which
4391 pragma @code{Inline} is specified. This inlining is performed
4392 by the front end and will be visible in the
4393 @option{-gnatG} output.
4395 When using a gcc-based back end (in practice this means using any version
4396 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4397 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4398 Historically front end inlining was more extensive than the gcc back end
4399 inlining, but that is no longer the case.
4401 @item -gnato??
4402 @cindex @option{-gnato??} (@command{gcc})
4403 Set default mode for handling generation of code to avoid intermediate
4404 arithmetic overflow. Here `@code{??}' is two digits, a
4405 single digit, or nothing. Each digit is one of the digits `@code{1}'
4406 through `@code{3}':
4408 @itemize @bullet
4409 @item   @code{1}:
4410 all intermediate overflows checked against base type (@code{STRICT})
4411 @item   @code{2}:
4412 minimize intermediate overflows (@code{MINIMIZED})
4413 @item   @code{3}:
4414 eliminate intermediate overflows (@code{ELIMINATED})
4415 @end itemize
4417 If only one digit appears then it applies to all
4418 cases; if two digits are given, then the first applies outside
4419 assertions, and the second within assertions.
4421 If no digits follow the @option{-gnato}, then it is equivalent to
4422 @option{-gnato11},
4423 causing all intermediate overflows to be handled in strict mode.
4425 This switch also causes arithmetic overflow checking to be performed
4426 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4428 The default if no option @option{-gnato} is given is that overflow handling
4429 is in @code{STRICT} mode (computations done using the base type), and that
4430 overflow checking is suppressed.
4432 Note that division by zero is a separate check that is not
4433 controlled by this switch (division by zero checking is on by default).
4435 See also @ref{Specifying the Desired Mode}.
4437 @item -gnatp
4438 @cindex @option{-gnatp} (@command{gcc})
4439 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4440 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4442 @item -gnat-p
4443 @cindex @option{-gnat-p} (@command{gcc})
4444 Cancel effect of previous @option{-gnatp} switch.
4446 @item -gnatP
4447 @cindex @option{-gnatP} (@command{gcc})
4448 Enable polling. This is required on some systems (notably Windows NT) to
4449 obtain asynchronous abort and asynchronous transfer of control capability.
4450 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4451 details.
4453 @item -gnatq
4454 @cindex @option{-gnatq} (@command{gcc})
4455 Don't quit. Try semantics, even if parse errors.
4457 @item -gnatQ
4458 @cindex @option{-gnatQ} (@command{gcc})
4459 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4461 @item -gnatr
4462 @cindex @option{-gnatr} (@command{gcc})
4463 Treat pragma Restrictions as Restriction_Warnings.
4465 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4466 @cindex @option{-gnatR} (@command{gcc})
4467 Output representation information for declared types and objects.
4469 @item -gnats
4470 @cindex @option{-gnats} (@command{gcc})
4471 Syntax check only.
4473 @item -gnatS
4474 @cindex @option{-gnatS} (@command{gcc})
4475 Print package Standard.
4477 @item -gnatt
4478 @cindex @option{-gnatt} (@command{gcc})
4479 Generate tree output file.
4481 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4482 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4483 All compiler tables start at @var{nnn} times usual starting size.
4485 @item -gnatu
4486 @cindex @option{-gnatu} (@command{gcc})
4487 List units for this compilation.
4489 @item -gnatU
4490 @cindex @option{-gnatU} (@command{gcc})
4491 Tag all error messages with the unique string ``error:''
4493 @item -gnatv
4494 @cindex @option{-gnatv} (@command{gcc})
4495 Verbose mode. Full error output with source lines to @file{stdout}.
4497 @item -gnatV
4498 @cindex @option{-gnatV} (@command{gcc})
4499 Control level of validity checking (@pxref{Validity Checking}).
4501 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4502 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4503 Warning mode where
4504 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4505 the exact warnings that
4506 are enabled or disabled (@pxref{Warning Message Control}).
4508 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4509 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4510 Wide character encoding method
4511 @ifclear vms
4512 (@var{e}=n/h/u/s/e/8).
4513 @end ifclear
4514 @ifset vms
4515 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4516 @end ifset
4518 @item -gnatx
4519 @cindex @option{-gnatx} (@command{gcc})
4520 Suppress generation of cross-reference information.
4522 @item -gnatX
4523 @cindex @option{-gnatX} (@command{gcc})
4524 Enable GNAT implementation extensions and latest Ada version.
4526 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4527 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4528 Enable built-in style checks (@pxref{Style Checking}).
4530 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4531 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4532 Distribution stub generation and compilation
4533 @ifclear vms
4534 (@var{m}=r/c for receiver/caller stubs).
4535 @end ifclear
4536 @ifset vms
4537 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4538 to be generated and compiled).
4539 @end ifset
4541 @item ^-I^/SEARCH=^@var{dir}
4542 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4543 @cindex RTL
4544 Direct GNAT to search the @var{dir} directory for source files needed by
4545 the current compilation
4546 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4548 @item ^-I-^/NOCURRENT_DIRECTORY^
4549 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4550 @cindex RTL
4551 Except for the source file named in the command line, do not look for source
4552 files in the directory containing the source file named in the command line
4553 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4555 @ifclear vms
4556 @item -mbig-switch
4557 @cindex @option{-mbig-switch} (@command{gcc})
4558 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4559 This standard gcc switch causes the compiler to use larger offsets in its
4560 jump table representation for @code{case} statements.
4561 This may result in less efficient code, but is sometimes necessary
4562 (for example on HP-UX targets)
4563 @cindex HP-UX and @option{-mbig-switch} option
4564 in order to compile large and/or nested @code{case} statements.
4566 @item -o @var{file}
4567 @cindex @option{-o} (@command{gcc})
4568 This switch is used in @command{gcc} to redirect the generated object file
4569 and its associated ALI file. Beware of this switch with GNAT, because it may
4570 cause the object file and ALI file to have different names which in turn
4571 may confuse the binder and the linker.
4572 @end ifclear
4574 @item -nostdinc
4575 @cindex @option{-nostdinc} (@command{gcc})
4576 Inhibit the search of the default location for the GNAT Run Time
4577 Library (RTL) source files.
4579 @item -nostdlib
4580 @cindex @option{-nostdlib} (@command{gcc})
4581 Inhibit the search of the default location for the GNAT Run Time
4582 Library (RTL) ALI files.
4584 @ifclear vms
4585 @c @item -O@ovar{n}
4586 @c Expanding @ovar macro inline (explanation in macro def comments)
4587 @item -O@r{[}@var{n}@r{]}
4588 @cindex @option{-O} (@command{gcc})
4589 @var{n} controls the optimization level.
4591 @table @asis
4592 @item n = 0
4593 No optimization, the default setting if no @option{-O} appears
4595 @item n = 1
4596 Normal optimization, the default if you specify @option{-O} without
4597 an operand. A good compromise between code quality and compilation
4598 time.
4600 @item n = 2
4601 Extensive optimization, may improve execution time, possibly at the cost of
4602 substantially increased compilation time.
4604 @item n = 3
4605 Same as @option{-O2}, and also includes inline expansion for small subprograms
4606 in the same unit.
4608 @item n = s
4609 Optimize space usage
4610 @end table
4612 @noindent
4613 See also @ref{Optimization Levels}.
4614 @end ifclear
4616 @ifset vms
4617 @item  /NOOPTIMIZE
4618 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4619 Equivalent to @option{/OPTIMIZE=NONE}.
4620 This is the default behavior in the absence of an @option{/OPTIMIZE}
4621 qualifier.
4623 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4624 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4625 Selects the level of optimization for your program. The supported
4626 keywords are as follows:
4627 @table @code
4628 @item   ALL
4629 Perform most optimizations, including those that
4630 are expensive.
4631 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4632 without keyword options.
4634 @item   NONE
4635 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4637 @item SOME
4638 Perform some optimizations, but omit ones that are costly.
4640 @item   DEVELOPMENT
4641 Same as @code{SOME}.
4643 @item INLINING
4644 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4645 automatic inlining of small subprograms within a unit
4647 @item   UNROLL_LOOPS
4648 Try to unroll loops. This keyword may be specified together with
4649 any keyword above other than @code{NONE}. Loop unrolling
4650 usually, but not always, improves the performance of programs.
4652 @item SPACE
4653 Optimize space usage
4654 @end table
4656 @noindent
4657 See also @ref{Optimization Levels}.
4658 @end ifset
4660 @ifclear vms
4661 @item -pass-exit-codes
4662 @cindex @option{-pass-exit-codes} (@command{gcc})
4663 Catch exit codes from the compiler and use the most meaningful as
4664 exit status.
4665 @end ifclear
4667 @item --RTS=@var{rts-path}
4668 @cindex @option{--RTS} (@command{gcc})
4669 Specifies the default location of the runtime library. Same meaning as the
4670 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4672 @item ^-S^/ASM^
4673 @cindex @option{^-S^/ASM^} (@command{gcc})
4674 ^Used in place of @option{-c} to^Used to^
4675 cause the assembler source file to be
4676 generated, using @file{^.s^.S^} as the extension,
4677 instead of the object file.
4678 This may be useful if you need to examine the generated assembly code.
4680 @item ^-fverbose-asm^/VERBOSE_ASM^
4681 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4682 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4683 to cause the generated assembly code file to be annotated with variable
4684 names, making it significantly easier to follow.
4686 @item ^-v^/VERBOSE^
4687 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4688 Show commands generated by the @command{gcc} driver. Normally used only for
4689 debugging purposes or if you need to be sure what version of the
4690 compiler you are executing.
4692 @ifclear vms
4693 @item -V @var{ver}
4694 @cindex @option{-V} (@command{gcc})
4695 Execute @var{ver} version of the compiler. This is the @command{gcc}
4696 version, not the GNAT version.
4697 @end ifclear
4699 @item ^-w^/NO_BACK_END_WARNINGS^
4700 @cindex @option{-w} (@command{gcc})
4701 Turn off warnings generated by the back end of the compiler. Use of
4702 this switch also causes the default for front end warnings to be set
4703 to suppress (as though @option{-gnatws} had appeared at the start of
4704 the options).
4706 @end table
4708 @ifclear vms
4709 @c Combining qualifiers does not work on VMS
4710 You may combine a sequence of GNAT switches into a single switch. For
4711 example, the combined switch
4713 @cindex Combining GNAT switches
4714 @smallexample
4715 -gnatofi3
4716 @end smallexample
4718 @noindent
4719 is equivalent to specifying the following sequence of switches:
4721 @smallexample
4722 -gnato -gnatf -gnati3
4723 @end smallexample
4724 @end ifclear
4726 @noindent
4727 The following restrictions apply to the combination of switches
4728 in this manner:
4730 @itemize @bullet
4731 @item
4732 The switch @option{-gnatc} if combined with other switches must come
4733 first in the string.
4735 @item
4736 The switch @option{-gnats} if combined with other switches must come
4737 first in the string.
4739 @item
4740 The switches
4741 ^^@option{/DISTRIBUTION_STUBS=},^
4742 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4743 switches, and only one of them may appear in the command line.
4745 @item
4746 The switch @option{-gnat-p} may not be combined with any other switch.
4748 @ifclear vms
4749 @item
4750 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4751 switch), then all further characters in the switch are interpreted
4752 as style modifiers (see description of @option{-gnaty}).
4754 @item
4755 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4756 switch), then all further characters in the switch are interpreted
4757 as debug flags (see description of @option{-gnatd}).
4759 @item
4760 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4761 switch), then all further characters in the switch are interpreted
4762 as warning mode modifiers (see description of @option{-gnatw}).
4764 @item
4765 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4766 switch), then all further characters in the switch are interpreted
4767 as validity checking options (@pxref{Validity Checking}).
4769 @item
4770 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4771 a combined list of options.
4772 @end ifclear
4773 @end itemize
4775 @node Output and Error Message Control
4776 @subsection Output and Error Message Control
4777 @findex stderr
4779 @noindent
4780 The standard default format for error messages is called ``brief format''.
4781 Brief format messages are written to @file{stderr} (the standard error
4782 file) and have the following form:
4784 @smallexample
4785 e.adb:3:04: Incorrect spelling of keyword "function"
4786 e.adb:4:20: ";" should be "is"
4787 @end smallexample
4789 @noindent
4790 The first integer after the file name is the line number in the file,
4791 and the second integer is the column number within the line.
4792 @ifclear vms
4793 @code{GPS} can parse the error messages
4794 and point to the referenced character.
4795 @end ifclear
4796 The following switches provide control over the error message
4797 format:
4799 @table @option
4800 @c !sort!
4801 @item -gnatv
4802 @cindex @option{-gnatv} (@command{gcc})
4803 @findex stdout
4804 @ifclear vms
4805 The v stands for verbose.
4806 @end ifclear
4807 The effect of this setting is to write long-format error
4808 messages to @file{stdout} (the standard output file.
4809 The same program compiled with the
4810 @option{-gnatv} switch would generate:
4812 @smallexample
4813 @cartouche
4814 3. funcion X (Q : Integer)
4815    |
4816 >>> Incorrect spelling of keyword "function"
4817 4. return Integer;
4818                  |
4819 >>> ";" should be "is"
4820 @end cartouche
4821 @end smallexample
4823 @noindent
4824 The vertical bar indicates the location of the error, and the @samp{>>>}
4825 prefix can be used to search for error messages. When this switch is
4826 used the only source lines output are those with errors.
4828 @item -gnatl
4829 @cindex @option{-gnatl} (@command{gcc})
4830 @ifclear vms
4831 The @code{l} stands for list.
4832 @end ifclear
4833 This switch causes a full listing of
4834 the file to be generated. In the case where a body is
4835 compiled, the corresponding spec is also listed, along
4836 with any subunits. Typical output from compiling a package
4837 body @file{p.adb} might look like:
4839 @smallexample @c ada
4840 @cartouche
4841  Compiling: p.adb
4843      1. package body p is
4844      2.    procedure a;
4845      3.    procedure a is separate;
4846      4. begin
4847      5.    null
4848                |
4849         >>> missing ";"
4851      6. end;
4853 Compiling: p.ads
4855      1. package p is
4856      2.    pragma Elaborate_Body
4857                                 |
4858         >>> missing ";"
4860      3. end p;
4862 Compiling: p-a.adb
4864      1. separate p
4865                 |
4866         >>> missing "("
4868      2. procedure a is
4869      3. begin
4870      4.    null
4871                |
4872         >>> missing ";"
4874      5. end;
4875 @end cartouche
4876 @end smallexample
4878 @noindent
4879 @findex stderr
4880 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4881 standard output is redirected, a brief summary is written to
4882 @file{stderr} (standard error) giving the number of error messages and
4883 warning messages generated.
4885 @item ^-gnatl^/OUTPUT_FILE^=file
4886 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4887 This has the same effect as @option{-gnatl} except that the output is
4888 written to a file instead of to standard output. If the given name
4889 @file{fname} does not start with a period, then it is the full name
4890 of the file to be written. If @file{fname} is an extension, it is
4891 appended to the name of the file being compiled. For example, if
4892 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4893 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4895 @item -gnatU
4896 @cindex @option{-gnatU} (@command{gcc})
4897 This switch forces all error messages to be preceded by the unique
4898 string ``error:''. This means that error messages take a few more
4899 characters in space, but allows easy searching for and identification
4900 of error messages.
4902 @item -gnatb
4903 @cindex @option{-gnatb} (@command{gcc})
4904 @ifclear vms
4905 The @code{b} stands for brief.
4906 @end ifclear
4907 This switch causes GNAT to generate the
4908 brief format error messages to @file{stderr} (the standard error
4909 file) as well as the verbose
4910 format message or full listing (which as usual is written to
4911 @file{stdout} (the standard output file).
4913 @item -gnatm=@var{n}
4914 @cindex @option{-gnatm} (@command{gcc})
4915 @ifclear vms
4916 The @code{m} stands for maximum.
4917 @end ifclear
4918 @var{n} is a decimal integer in the
4919 range of 1 to 999999 and limits the number of error or warning
4920 messages to be generated. For example, using
4921 @option{-gnatm2} might yield
4923 @smallexample
4924 e.adb:3:04: Incorrect spelling of keyword "function"
4925 e.adb:5:35: missing ".."
4926 fatal error: maximum number of errors detected
4927 compilation abandoned
4928 @end smallexample
4930 @noindent
4931 The default setting if
4932 no switch is given is 9999. If the number of warnings reaches this
4933 limit, then a message is output and further warnings are suppressed,
4934 but the compilation is continued. If the number of error messages
4935 reaches this limit, then a message is output and the compilation
4936 is abandoned. A value of zero means that no limit applies.
4938 @noindent
4939 Note that the equal sign is optional, so the switches
4940 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4942 @item -gnatf
4943 @cindex @option{-gnatf} (@command{gcc})
4944 @cindex Error messages, suppressing
4945 @ifclear vms
4946 The @code{f} stands for full.
4947 @end ifclear
4948 Normally, the compiler suppresses error messages that are likely to be
4949 redundant. This switch causes all error
4950 messages to be generated. In particular, in the case of
4951 references to undefined variables. If a given variable is referenced
4952 several times, the normal format of messages is
4953 @smallexample
4954 e.adb:7:07: "V" is undefined (more references follow)
4955 @end smallexample
4957 @noindent
4958 where the parenthetical comment warns that there are additional
4959 references to the variable @code{V}. Compiling the same program with the
4960 @option{-gnatf} switch yields
4962 @smallexample
4963 e.adb:7:07: "V" is undefined
4964 e.adb:8:07: "V" is undefined
4965 e.adb:8:12: "V" is undefined
4966 e.adb:8:16: "V" is undefined
4967 e.adb:9:07: "V" is undefined
4968 e.adb:9:12: "V" is undefined
4969 @end smallexample
4971 @noindent
4972 The @option{-gnatf} switch also generates additional information for
4973 some error messages.  Some examples are:
4975 @itemize @bullet
4976 @item
4977 Details on possibly non-portable unchecked conversion
4978 @item
4979 List possible interpretations for ambiguous calls
4980 @item
4981 Additional details on incorrect parameters
4982 @end itemize
4984 @item -gnatjnn
4985 @cindex @option{-gnatjnn} (@command{gcc})
4986 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4987 with continuation lines are treated as though the continuation lines were
4988 separate messages (and so a warning with two continuation lines counts as
4989 three warnings, and is listed as three separate messages).
4991 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4992 messages are output in a different manner. A message and all its continuation
4993 lines are treated as a unit, and count as only one warning or message in the
4994 statistics totals. Furthermore, the message is reformatted so that no line
4995 is longer than nn characters.
4997 @item -gnatq
4998 @cindex @option{-gnatq} (@command{gcc})
4999 @ifclear vms
5000 The @code{q} stands for quit (really ``don't quit'').
5001 @end ifclear
5002 In normal operation mode, the compiler first parses the program and
5003 determines if there are any syntax errors. If there are, appropriate
5004 error messages are generated and compilation is immediately terminated.
5005 This switch tells
5006 GNAT to continue with semantic analysis even if syntax errors have been
5007 found. This may enable the detection of more errors in a single run. On
5008 the other hand, the semantic analyzer is more likely to encounter some
5009 internal fatal error when given a syntactically invalid tree.
5011 @item -gnatQ
5012 @cindex @option{-gnatQ} (@command{gcc})
5013 In normal operation mode, the @file{ALI} file is not generated if any
5014 illegalities are detected in the program. The use of @option{-gnatQ} forces
5015 generation of the @file{ALI} file. This file is marked as being in
5016 error, so it cannot be used for binding purposes, but it does contain
5017 reasonably complete cross-reference information, and thus may be useful
5018 for use by tools (e.g., semantic browsing tools or integrated development
5019 environments) that are driven from the @file{ALI} file. This switch
5020 implies @option{-gnatq}, since the semantic phase must be run to get a
5021 meaningful ALI file.
5023 In addition, if @option{-gnatt} is also specified, then the tree file is
5024 generated even if there are illegalities. It may be useful in this case
5025 to also specify @option{-gnatq} to ensure that full semantic processing
5026 occurs. The resulting tree file can be processed by ASIS, for the purpose
5027 of providing partial information about illegal units, but if the error
5028 causes the tree to be badly malformed, then ASIS may crash during the
5029 analysis.
5031 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
5032 being in error, @command{gnatmake} will attempt to recompile the source when it
5033 finds such an @file{ALI} file, including with switch @option{-gnatc}.
5035 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
5036 since ALI files are never generated if @option{-gnats} is set.
5038 @end table
5040 @node Warning Message Control
5041 @subsection Warning Message Control
5042 @cindex Warning messages
5043 @noindent
5044 In addition to error messages, which correspond to illegalities as defined
5045 in the Ada Reference Manual, the compiler detects two kinds of warning
5046 situations.
5048 First, the compiler considers some constructs suspicious and generates a
5049 warning message to alert you to a possible error. Second, if the
5050 compiler detects a situation that is sure to raise an exception at
5051 run time, it generates a warning message. The following shows an example
5052 of warning messages:
5053 @smallexample
5054 e.adb:4:24: warning: creation of object may raise Storage_Error
5055 e.adb:10:17: warning: static value out of range
5056 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
5057 @end smallexample
5059 @noindent
5060 GNAT considers a large number of situations as appropriate
5061 for the generation of warning messages. As always, warnings are not
5062 definite indications of errors. For example, if you do an out-of-range
5063 assignment with the deliberate intention of raising a
5064 @code{Constraint_Error} exception, then the warning that may be
5065 issued does not indicate an error. Some of the situations for which GNAT
5066 issues warnings (at least some of the time) are given in the following
5067 list. This list is not complete, and new warnings are often added to
5068 subsequent versions of GNAT. The list is intended to give a general idea
5069 of the kinds of warnings that are generated.
5071 @itemize @bullet
5072 @item
5073 Possible infinitely recursive calls
5075 @item
5076 Out-of-range values being assigned
5078 @item
5079 Possible order of elaboration problems
5081 @item
5082 Assertions (pragma Assert) that are sure to fail
5084 @item
5085 Unreachable code
5087 @item
5088 Address clauses with possibly unaligned values, or where an attempt is
5089 made to overlay a smaller variable with a larger one.
5091 @item
5092 Fixed-point type declarations with a null range
5094 @item
5095 Direct_IO or Sequential_IO instantiated with a type that has access values
5097 @item
5098 Variables that are never assigned a value
5100 @item
5101 Variables that are referenced before being initialized
5103 @item
5104 Task entries with no corresponding @code{accept} statement
5106 @item
5107 Duplicate accepts for the same task entry in a @code{select}
5109 @item
5110 Objects that take too much storage
5112 @item
5113 Unchecked conversion between types of differing sizes
5115 @item
5116 Missing @code{return} statement along some execution path in a function
5118 @item
5119 Incorrect (unrecognized) pragmas
5121 @item
5122 Incorrect external names
5124 @item
5125 Allocation from empty storage pool
5127 @item
5128 Potentially blocking operation in protected type
5130 @item
5131 Suspicious parenthesization of expressions
5133 @item
5134 Mismatching bounds in an aggregate
5136 @item
5137 Attempt to return local value by reference
5139 @item
5140 Premature instantiation of a generic body
5142 @item
5143 Attempt to pack aliased components
5145 @item
5146 Out of bounds array subscripts
5148 @item
5149 Wrong length on string assignment
5151 @item
5152 Violations of style rules if style checking is enabled
5154 @item
5155 Unused @code{with} clauses
5157 @item
5158 @code{Bit_Order} usage that does not have any effect
5160 @item
5161 @code{Standard.Duration} used to resolve universal fixed expression
5163 @item
5164 Dereference of possibly null value
5166 @item
5167 Declaration that is likely to cause storage error
5169 @item
5170 Internal GNAT unit @code{with}'ed by application unit
5172 @item
5173 Values known to be out of range at compile time
5175 @item
5176 Unreferenced labels and variables
5178 @item
5179 Address overlays that could clobber memory
5181 @item
5182 Unexpected initialization when address clause present
5184 @item
5185 Bad alignment for address clause
5187 @item
5188 Useless type conversions
5190 @item
5191 Redundant assignment statements and other redundant constructs
5193 @item
5194 Useless exception handlers
5196 @item
5197 Accidental hiding of name by child unit
5199 @item
5200 Access before elaboration detected at compile time
5202 @item
5203 A range in a @code{for} loop that is known to be null or might be null
5205 @end itemize
5207 @noindent
5208 The following section lists compiler switches that are available
5209 to control the handling of warning messages. It is also possible
5210 to exercise much finer control over what warnings are issued and
5211 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5212 gnat_rm, GNAT Reference manual}.
5214 @table @option
5215 @c !sort!
5216 @item -gnatwa
5217 @emph{Activate most optional warnings.}
5218 @cindex @option{-gnatwa} (@command{gcc})
5219 This switch activates most optional warning messages.  See the remaining list
5220 in this section for details on optional warning messages that can be
5221 individually controlled.  The warnings that are not turned on by this
5222 switch are
5223 @option{-gnatwd} (implicit dereferencing),
5224 @option{-gnatwh} (hiding),
5225 @ifclear vms
5226 @option{-gnatw.d} (tag warnings with -gnatw switch)
5227 @end ifclear
5228 @option{-gnatw.h} (holes (gaps) in record layouts)
5229 @option{-gnatw.i} (overlapping actuals),
5230 @option{-gnatw.k} (redefinition of names in standard),
5231 @option{-gnatwl} (elaboration warnings),
5232 @option{-gnatw.l} (inherited aspects),
5233 @option{-gnatw.o} (warn on values set by out parameters ignored),
5234 @option{-gnatwt} (tracking of deleted conditional code)
5235 and @option{-gnatw.u} (unordered enumeration),
5236 All other optional warnings are turned on.
5238 @item -gnatwA
5239 @emph{Suppress all optional errors.}
5240 @cindex @option{-gnatwA} (@command{gcc})
5241 This switch suppresses all optional warning messages, see remaining list
5242 in this section for details on optional warning messages that can be
5243 individually controlled. Note that unlike switch @option{-gnatws}, the
5244 use of switch @option{-gnatwA} does not suppress warnings that are
5245 normally given unconditionally and cannot be individually controlled
5246 (for example, the warning about a missing exit path in a function).
5247 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5248 the use of switch @option{-gnatwA} can be individually turned back
5249 on. For example the use of switch @option{-gnatwA} followed by
5250 switch @option{-gnatwd} will suppress all optional warnings except
5251 the warnings for implicit dereferencing.
5253 @item -gnatw.a
5254 @emph{Activate warnings on failing assertions.}
5255 @cindex @option{-gnatw.a} (@command{gcc})
5256 @cindex Assert failures
5257 This switch activates warnings for assertions where the compiler can tell at
5258 compile time that the assertion will fail. Note that this warning is given
5259 even if assertions are disabled. The default is that such warnings are
5260 generated.
5262 @item -gnatw.A
5263 @emph{Suppress warnings on failing assertions.}
5264 @cindex @option{-gnatw.A} (@command{gcc})
5265 @cindex Assert failures
5266 This switch suppresses warnings for assertions where the compiler can tell at
5267 compile time that the assertion will fail.
5269 @item -gnatwb
5270 @emph{Activate warnings on bad fixed values.}
5271 @cindex @option{-gnatwb} (@command{gcc})
5272 @cindex Bad fixed values
5273 @cindex Fixed-point Small value
5274 @cindex Small value
5275 This switch activates warnings for static fixed-point expressions whose
5276 value is not an exact multiple of Small. Such values are implementation
5277 dependent, since an implementation is free to choose either of the multiples
5278 that surround the value. GNAT always chooses the closer one, but this is not
5279 required behavior, and it is better to specify a value that is an exact
5280 multiple, ensuring predictable execution. The default is that such warnings
5281 are not generated.
5283 @item -gnatwB
5284 @emph{Suppress warnings on bad fixed values.}
5285 @cindex @option{-gnatwB} (@command{gcc})
5286 This switch suppresses warnings for static fixed-point expressions whose
5287 value is not an exact multiple of Small.
5289 @item -gnatw.b
5290 @emph{Activate warnings on biased representation.}
5291 @cindex @option{-gnatw.b} (@command{gcc})
5292 @cindex Biased representation
5293 This switch activates warnings when a size clause, value size clause, component
5294 clause, or component size clause forces the use of biased representation for an
5295 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5296 to represent 10/11). The default is that such warnings are generated.
5298 @item -gnatw.B
5299 @emph{Suppress warnings on biased representation.}
5300 @cindex @option{-gnatwB} (@command{gcc})
5301 This switch suppresses warnings for representation clauses that force the use
5302 of biased representation.
5304 @item -gnatwc
5305 @emph{Activate warnings on conditionals.}
5306 @cindex @option{-gnatwc} (@command{gcc})
5307 @cindex Conditionals, constant
5308 This switch activates warnings for conditional expressions used in
5309 tests that are known to be True or False at compile time. The default
5310 is that such warnings are not generated.
5311 Note that this warning does
5312 not get issued for the use of boolean variables or constants whose
5313 values are known at compile time, since this is a standard technique
5314 for conditional compilation in Ada, and this would generate too many
5315 false positive warnings.
5317 This warning option also activates a special test for comparisons using
5318 the operators ``>='' and`` <=''.
5319 If the compiler can tell that only the equality condition is possible,
5320 then it will warn that the ``>'' or ``<'' part of the test
5321 is useless and that the operator could be replaced by ``=''.
5322 An example would be comparing a @code{Natural} variable <= 0.
5324 This warning option also generates warnings if
5325 one or both tests is optimized away in a membership test for integer
5326 values if the result can be determined at compile time. Range tests on
5327 enumeration types are not included, since it is common for such tests
5328 to include an end point.
5330 This warning can also be turned on using @option{-gnatwa}.
5332 @item -gnatwC
5333 @emph{Suppress warnings on conditionals.}
5334 @cindex @option{-gnatwC} (@command{gcc})
5335 This switch suppresses warnings for conditional expressions used in
5336 tests that are known to be True or False at compile time.
5338 @item -gnatw.c
5339 @emph{Activate warnings on missing component clauses.}
5340 @cindex @option{-gnatw.c} (@command{gcc})
5341 @cindex Component clause, missing
5342 This switch activates warnings for record components where a record
5343 representation clause is present and has component clauses for the
5344 majority, but not all, of the components. A warning is given for each
5345 component for which no component clause is present.
5347 This warning can also be turned on using @option{-gnatwa}.
5349 @item -gnatw.C
5350 @emph{Suppress warnings on missing component clauses.}
5351 @cindex @option{-gnatwC} (@command{gcc})
5352 This switch suppresses warnings for record components that are
5353 missing a component clause in the situation described above.
5355 @item -gnatwd
5356 @emph{Activate warnings on implicit dereferencing.}
5357 @cindex @option{-gnatwd} (@command{gcc})
5358 If this switch is set, then the use of a prefix of an access type
5359 in an indexed component, slice, or selected component without an
5360 explicit @code{.all} will generate a warning. With this warning
5361 enabled, access checks occur only at points where an explicit
5362 @code{.all} appears in the source code (assuming no warnings are
5363 generated as a result of this switch). The default is that such
5364 warnings are not generated.
5365 Note that @option{-gnatwa} does not affect the setting of
5366 this warning option.
5368 @item -gnatwD
5369 @emph{Suppress warnings on implicit dereferencing.}
5370 @cindex @option{-gnatwD} (@command{gcc})
5371 @cindex Implicit dereferencing
5372 @cindex Dereferencing, implicit
5373 This switch suppresses warnings for implicit dereferences in
5374 indexed components, slices, and selected components.
5376 @ifclear vms
5377 @item -gnatw.d
5378 @emph{Activate tagging of warning messages.}
5379 @cindex @option{-gnatw.d} (@command{gcc})
5380 If this switch is set, then warning messages are tagged, either with
5381 the string ``@option{-gnatw?}'' showing which switch controls the warning,
5382 or with ``[enabled by default]'' if the warning is not under control of a
5383 specific @option{-gnatw?} switch. This mode is off by default, and is not
5384 affected by the use of @code{-gnatwa}.
5386 @item -gnatw.D
5387 @emph{Deactivate tagging of warning messages.}
5388 @cindex @option{-gnatw.d} (@command{gcc})
5389 If this switch is set, then warning messages return to the default
5390 mode in which warnings are not tagged as described above for
5391 @code{-gnatw.d}.
5392 @end ifclear
5394 @item -gnatwe
5395 @emph{Treat warnings and style checks as errors.}
5396 @cindex @option{-gnatwe} (@command{gcc})
5397 @cindex Warnings, treat as error
5398 This switch causes warning messages and style check messages to be
5399 treated as errors.
5400 The warning string still appears, but the warning messages are counted
5401 as errors, and prevent the generation of an object file. Note that this
5402 is the only -gnatw switch that affects the handling of style check messages.
5404 @item -gnatw.e
5405 @emph{Activate every optional warning}
5406 @cindex @option{-gnatw.e} (@command{gcc})
5407 @cindex Warnings, activate every optional warning
5408 This switch activates all optional warnings, including those which
5409 are not activated by @code{-gnatwa}. The use of this switch is not
5410 recommended for normal use. If you turn this switch on, it is almost
5411 certain that you will get large numbers of useless warnings. The
5412 warnings that are excluded from @code{-gnatwa} are typically highly
5413 specialized warnings that are suitable for use only in code that has
5414 been specifically designed according to specialized coding rules.
5416 @item -gnatwf
5417 @emph{Activate warnings on unreferenced formals.}
5418 @cindex @option{-gnatwf} (@command{gcc})
5419 @cindex Formals, unreferenced
5420 This switch causes a warning to be generated if a formal parameter
5421 is not referenced in the body of the subprogram. This warning can
5422 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5423 default is that these warnings are not generated.
5425 @item -gnatwF
5426 @emph{Suppress warnings on unreferenced formals.}
5427 @cindex @option{-gnatwF} (@command{gcc})
5428 This switch suppresses warnings for unreferenced formal
5429 parameters. Note that the
5430 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5431 effect of warning on unreferenced entities other than subprogram
5432 formals.
5434 @item -gnatwg
5435 @emph{Activate warnings on unrecognized pragmas.}
5436 @cindex @option{-gnatwg} (@command{gcc})
5437 @cindex Pragmas, unrecognized
5438 This switch causes a warning to be generated if an unrecognized
5439 pragma is encountered. Apart from issuing this warning, the
5440 pragma is ignored and has no effect. This warning can
5441 also be turned on using @option{-gnatwa}. The default
5442 is that such warnings are issued (satisfying the Ada Reference
5443 Manual requirement that such warnings appear).
5445 @item -gnatwG
5446 @emph{Suppress warnings on unrecognized pragmas.}
5447 @cindex @option{-gnatwG} (@command{gcc})
5448 This switch suppresses warnings for unrecognized pragmas.
5450 @item -gnatwh
5451 @emph{Activate warnings on hiding.}
5452 @cindex @option{-gnatwh} (@command{gcc})
5453 @cindex Hiding of Declarations
5454 This switch activates warnings on hiding declarations.
5455 A declaration is considered hiding
5456 if it is for a non-overloadable entity, and it declares an entity with the
5457 same name as some other entity that is directly or use-visible. The default
5458 is that such warnings are not generated.
5459 Note that @option{-gnatwa} does not affect the setting of this warning option.
5461 @item -gnatwH
5462 @emph{Suppress warnings on hiding.}
5463 @cindex @option{-gnatwH} (@command{gcc})
5464 This switch suppresses warnings on hiding declarations.
5466 @item -gnatw.h
5467 @emph{Activate warnings on holes/gaps in records.}
5468 @cindex @option{-gnatw.h} (@command{gcc})
5469 @cindex Record Representation (gaps)
5470 This switch activates warnings on component clauses in record
5471 representation clauses that leave holes (gaps) in the record layout.
5472 If this warning option is active, then record representation clauses
5473 should specify a contiguous layout, adding unused fill fields if needed.
5474 Note that @option{-gnatwa} does not affect the setting of this warning option.
5476 @item -gnatw.H
5477 @emph{Suppress warnings on holes/gaps in records.}
5478 @cindex @option{-gnatw.H} (@command{gcc})
5479 This switch suppresses warnings on component clauses in record
5480 representation clauses that leave holes (haps) in the record layout.
5482 @item -gnatwi
5483 @emph{Activate warnings on implementation units.}
5484 @cindex @option{-gnatwi} (@command{gcc})
5485 This switch activates warnings for a @code{with} of an internal GNAT
5486 implementation unit, defined as any unit from the @code{Ada},
5487 @code{Interfaces}, @code{GNAT},
5488 ^^@code{DEC},^ or @code{System}
5489 hierarchies that is not
5490 documented in either the Ada Reference Manual or the GNAT
5491 Programmer's Reference Manual. Such units are intended only
5492 for internal implementation purposes and should not be @code{with}'ed
5493 by user programs. The default is that such warnings are generated
5494 This warning can also be turned on using @option{-gnatwa}.
5496 @item -gnatwI
5497 @emph{Disable warnings on implementation units.}
5498 @cindex @option{-gnatwI} (@command{gcc})
5499 This switch disables warnings for a @code{with} of an internal GNAT
5500 implementation unit.
5502 @item -gnatw.i
5503 @emph{Activate warnings on overlapping actuals.}
5504 @cindex @option{-gnatw.i} (@command{gcc})
5505 This switch enables a warning on statically detectable overlapping actuals in
5506 a subprogram call, when one of the actuals is an in-out parameter, and the
5507 types of the actuals are not by-copy types. The warning is off by default,
5508 and is not included under -gnatwa.
5510 @item -gnatw.I
5511 @emph{Disable warnings on overlapping actuals.}
5512 @cindex @option{-gnatw.I} (@command{gcc})
5513 This switch disables warnings on overlapping actuals in a call..
5515 @item -gnatwj
5516 @emph{Activate warnings on obsolescent features (Annex J).}
5517 @cindex @option{-gnatwj} (@command{gcc})
5518 @cindex Features, obsolescent
5519 @cindex Obsolescent features
5520 If this warning option is activated, then warnings are generated for
5521 calls to subprograms marked with @code{pragma Obsolescent} and
5522 for use of features in Annex J of the Ada Reference Manual. In the
5523 case of Annex J, not all features are flagged. In particular use
5524 of the renamed packages (like @code{Text_IO}) and use of package
5525 @code{ASCII} are not flagged, since these are very common and
5526 would generate many annoying positive warnings. The default is that
5527 such warnings are not generated. This warning is also turned on by
5528 the use of @option{-gnatwa}.
5530 In addition to the above cases, warnings are also generated for
5531 GNAT features that have been provided in past versions but which
5532 have been superseded (typically by features in the new Ada standard).
5533 For example, @code{pragma Ravenscar} will be flagged since its
5534 function is replaced by @code{pragma Profile(Ravenscar)}, and
5535 @code{pragma Interface_Name} will be flagged since its function
5536 is replaced by @code{pragma Import}.
5538 Note that this warning option functions differently from the
5539 restriction @code{No_Obsolescent_Features} in two respects.
5540 First, the restriction applies only to annex J features.
5541 Second, the restriction does flag uses of package @code{ASCII}.
5543 @item -gnatwJ
5544 @emph{Suppress warnings on obsolescent features (Annex J).}
5545 @cindex @option{-gnatwJ} (@command{gcc})
5546 This switch disables warnings on use of obsolescent features.
5548 @item -gnatwk
5549 @emph{Activate warnings on variables that could be constants.}
5550 @cindex @option{-gnatwk} (@command{gcc})
5551 This switch activates warnings for variables that are initialized but
5552 never modified, and then could be declared constants. The default is that
5553 such warnings are not given.
5554 This warning can also be turned on using @option{-gnatwa}.
5556 @item -gnatwK
5557 @emph{Suppress warnings on variables that could be constants.}
5558 @cindex @option{-gnatwK} (@command{gcc})
5559 This switch disables warnings on variables that could be declared constants.
5561 @item -gnatw.k
5562 @emph{Activate warnings on redefinition of names in standard.}
5563 @cindex @option{-gnatw.k} (@command{gcc})
5564 This switch activates warnings for declarations that declare a name that
5565 is defined in package Standard. Such declarations can be confusing,
5566 especially since the names in package Standard continue to be directly
5567 visible, meaning that use visibiliy on such redeclared names does not
5568 work as expected. Names of discriminants and components in records are
5569 not included in this check.
5570 This warning is not part of the warnings activated by @option{-gnatwa}.
5571 It must be explicitly activated.
5573 @item -gnatw.K
5574 @emph{Suppress warnings on variables that could be constants.}
5575 @cindex @option{-gnatwK} (@command{gcc})
5576 This switch activates warnings for declarations that declare a name that
5577 is defined in package Standard.
5579 @item -gnatwl
5580 @emph{Activate warnings for elaboration pragmas.}
5581 @cindex @option{-gnatwl} (@command{gcc})
5582 @cindex Elaboration, warnings
5583 This switch activates warnings on missing
5584 @code{Elaborate_All} and @code{Elaborate} pragmas.
5585 See the section in this guide on elaboration checking for details on
5586 when such pragmas should be used. In dynamic elaboration mode, this switch
5587 generations warnings about the need to add elaboration pragmas. Note however,
5588 that if you blindly follow these warnings, and add @code{Elaborate_All}
5589 warnings wherever they are recommended, you basically end up with the
5590 equivalent of the static elaboration model, which may not be what you want for
5591 legacy code for which the static model does not work.
5593 For the static model, the messages generated are labeled "info:" (for
5594 information messages). They are not warnings to add elaboration pragmas,
5595 merely informational messages showing what implicit elaboration pragmas
5596 have been added, for use in analyzing elaboration circularity problems.
5598 Warnings are also generated if you
5599 are using the static mode of elaboration, and a @code{pragma Elaborate}
5600 is encountered. The default is that such warnings
5601 are not generated.
5602 This warning is not automatically turned on by the use of @option{-gnatwa}.
5604 @item -gnatwL
5605 @emph{Suppress warnings for elaboration pragmas.}
5606 @cindex @option{-gnatwL} (@command{gcc})
5607 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5608 See the section in this guide on elaboration checking for details on
5609 when such pragmas should be used.
5611 @item -gnatw.l
5612 @emph{List inherited aspects.}
5613 @cindex @option{-gnatw.l} (@command{gcc})
5614 This switch causes the compiler to list inherited invariants,
5615 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5616 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5617 These messages are not automatically turned on by the use of @option{-gnatwa}.
5619 @item -gnatw.L
5620 @emph{Suppress listing of inherited aspects.}
5621 @cindex @option{-gnatw.L} (@command{gcc})
5622 This switch suppresses listing of inherited aspects.
5624 @item -gnatwm
5625 @emph{Activate warnings on modified but unreferenced variables.}
5626 @cindex @option{-gnatwm} (@command{gcc})
5627 This switch activates warnings for variables that are assigned (using
5628 an initialization value or with one or more assignment statements) but
5629 whose value is never read. The warning is suppressed for volatile
5630 variables and also for variables that are renamings of other variables
5631 or for which an address clause is given.
5632 This warning can also be turned on using @option{-gnatwa}.
5633 The default is that these warnings are not given.
5635 @item -gnatwM
5636 @emph{Disable warnings on modified but unreferenced variables.}
5637 @cindex @option{-gnatwM} (@command{gcc})
5638 This switch disables warnings for variables that are assigned or
5639 initialized, but never read.
5641 @item -gnatw.m
5642 @emph{Activate warnings on suspicious modulus values.}
5643 @cindex @option{-gnatw.m} (@command{gcc})
5644 This switch activates warnings for modulus values that seem suspicious.
5645 The cases caught are where the size is the same as the modulus (e.g.
5646 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5647 with no size clause. The guess in both cases is that 2**x was intended
5648 rather than x. In addition expressions of the form 2*x for small x
5649 generate a warning (the almost certainly accurate guess being that
5650 2**x was intended). The default is that these warnings are given.
5652 @item -gnatw.M
5653 @emph{Disable warnings on suspicious modulus values.}
5654 @cindex @option{-gnatw.M} (@command{gcc})
5655 This switch disables warnings for suspicious modulus values.
5657 @item -gnatwn
5658 @emph{Set normal warnings mode.}
5659 @cindex @option{-gnatwn} (@command{gcc})
5660 This switch sets normal warning mode, in which enabled warnings are
5661 issued and treated as warnings rather than errors. This is the default
5662 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5663 an explicit @option{-gnatws} or
5664 @option{-gnatwe}. It also cancels the effect of the
5665 implicit @option{-gnatwe} that is activated by the
5666 use of @option{-gnatg}.
5668 @item -gnatwo
5669 @emph{Activate warnings on address clause overlays.}
5670 @cindex @option{-gnatwo} (@command{gcc})
5671 @cindex Address Clauses, warnings
5672 This switch activates warnings for possibly unintended initialization
5673 effects of defining address clauses that cause one variable to overlap
5674 another. The default is that such warnings are generated.
5675 This warning can also be turned on using @option{-gnatwa}.
5677 @item -gnatwO
5678 @emph{Suppress warnings on address clause overlays.}
5679 @cindex @option{-gnatwO} (@command{gcc})
5680 This switch suppresses warnings on possibly unintended initialization
5681 effects of defining address clauses that cause one variable to overlap
5682 another.
5684 @item -gnatw.o
5685 @emph{Activate warnings on modified but unreferenced out parameters.}
5686 @cindex @option{-gnatw.o} (@command{gcc})
5687 This switch activates warnings for variables that are modified by using
5688 them as actuals for a call to a procedure with an out mode formal, where
5689 the resulting assigned value is never read. It is applicable in the case
5690 where there is more than one out mode formal. If there is only one out
5691 mode formal, the warning is issued by default (controlled by -gnatwu).
5692 The warning is suppressed for volatile
5693 variables and also for variables that are renamings of other variables
5694 or for which an address clause is given.
5695 The default is that these warnings are not given. Note that this warning
5696 is not included in -gnatwa, it must be activated explicitly.
5698 @item -gnatw.O
5699 @emph{Disable warnings on modified but unreferenced out parameters.}
5700 @cindex @option{-gnatw.O} (@command{gcc})
5701 This switch suppresses warnings for variables that are modified by using
5702 them as actuals for a call to a procedure with an out mode formal, where
5703 the resulting assigned value is never read.
5705 @item -gnatwp
5706 @emph{Activate warnings on ineffective pragma Inlines.}
5707 @cindex @option{-gnatwp} (@command{gcc})
5708 @cindex Inlining, warnings
5709 This switch activates warnings for failure of front end inlining
5710 (activated by @option{-gnatN}) to inline a particular call. There are
5711 many reasons for not being able to inline a call, including most
5712 commonly that the call is too complex to inline. The default is
5713 that such warnings are not given.
5714 This warning can also be turned on using @option{-gnatwa}.
5715 Warnings on ineffective inlining by the gcc back-end can be activated
5716 separately, using the gcc switch -Winline.
5718 @item -gnatwP
5719 @emph{Suppress warnings on ineffective pragma Inlines.}
5720 @cindex @option{-gnatwP} (@command{gcc})
5721 This switch suppresses warnings on ineffective pragma Inlines. If the
5722 inlining mechanism cannot inline a call, it will simply ignore the
5723 request silently.
5725 @item -gnatw.p
5726 @emph{Activate warnings on parameter ordering.}
5727 @cindex @option{-gnatw.p} (@command{gcc})
5728 @cindex Parameter order, warnings
5729 This switch activates warnings for cases of suspicious parameter
5730 ordering when the list of arguments are all simple identifiers that
5731 match the names of the formals, but are in a different order. The
5732 warning is suppressed if any use of named parameter notation is used,
5733 so this is the appropriate way to suppress a false positive (and
5734 serves to emphasize that the "misordering" is deliberate). The
5735 default is
5736 that such warnings are not given.
5737 This warning can also be turned on using @option{-gnatwa}.
5739 @item -gnatw.P
5740 @emph{Suppress warnings on parameter ordering.}
5741 @cindex @option{-gnatw.P} (@command{gcc})
5742 This switch suppresses warnings on cases of suspicious parameter
5743 ordering.
5745 @item -gnatwq
5746 @emph{Activate warnings on questionable missing parentheses.}
5747 @cindex @option{-gnatwq} (@command{gcc})
5748 @cindex Parentheses, warnings
5749 This switch activates warnings for cases where parentheses are not used and
5750 the result is potential ambiguity from a readers point of view. For example
5751 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5752 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5753 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5754 follow the rule of always parenthesizing to make the association clear, and
5755 this warning switch warns if such parentheses are not present. The default
5756 is that these warnings are given.
5757 This warning can also be turned on using @option{-gnatwa}.
5759 @item -gnatwQ
5760 @emph{Suppress warnings on questionable missing parentheses.}
5761 @cindex @option{-gnatwQ} (@command{gcc})
5762 This switch suppresses warnings for cases where the association is not
5763 clear and the use of parentheses is preferred.
5765 @item -gnatwr
5766 @emph{Activate warnings on redundant constructs.}
5767 @cindex @option{-gnatwr} (@command{gcc})
5768 This switch activates warnings for redundant constructs. The following
5769 is the current list of constructs regarded as redundant:
5771 @itemize @bullet
5772 @item
5773 Assignment of an item to itself.
5774 @item
5775 Type conversion that converts an expression to its own type.
5776 @item
5777 Use of the attribute @code{Base} where @code{typ'Base} is the same
5778 as @code{typ}.
5779 @item
5780 Use of pragma @code{Pack} when all components are placed by a record
5781 representation clause.
5782 @item
5783 Exception handler containing only a reraise statement (raise with no
5784 operand) which has no effect.
5785 @item
5786 Use of the operator abs on an operand that is known at compile time
5787 to be non-negative
5788 @item
5789 Comparison of boolean expressions to an explicit True value.
5790 @end itemize
5792 This warning can also be turned on using @option{-gnatwa}.
5793 The default is that warnings for redundant constructs are not given.
5795 @item -gnatwR
5796 @emph{Suppress warnings on redundant constructs.}
5797 @cindex @option{-gnatwR} (@command{gcc})
5798 This switch suppresses warnings for redundant constructs.
5800 @item -gnatw.r
5801 @emph{Activate warnings for object renaming function.}
5802 @cindex @option{-gnatw.r} (@command{gcc})
5803 This switch activates warnings for an object renaming that renames a
5804 function call, which is equivalent to a constant declaration (as
5805 opposed to renaming the function itself).  The default is that these
5806 warnings are given.  This warning can also be turned on using
5807 @option{-gnatwa}.
5809 @item -gnatw.R
5810 @emph{Suppress warnings for object renaming function.}
5811 @cindex @option{-gnatwT} (@command{gcc})
5812 This switch suppresses warnings for object renaming function.
5814 @item -gnatws
5815 @emph{Suppress all warnings.}
5816 @cindex @option{-gnatws} (@command{gcc})
5817 This switch completely suppresses the
5818 output of all warning messages from the GNAT front end, including
5819 both warnings that can be controlled by switches described in this
5820 section, and those that are normally given unconditionally. The
5821 effect of this suppress action can only be cancelled by a subsequent
5822 use of the switch @option{-gnatwn}.
5824 Note that switch @option{-gnatws} does not suppress
5825 warnings from the @command{gcc} back end.
5826 To suppress these back end warnings as well, use the switch @option{-w}
5827 in addition to @option{-gnatws}. Also this switch has no effect on the
5828 handling of style check messages.
5830 @item -gnatw.s
5831 @emph{Activate warnings on overridden size clauses.}
5832 @cindex @option{-gnatw.s} (@command{gcc})
5833 @cindex Record Representation (component sizes)
5834 This switch activates warnings on component clauses in record
5835 representation clauses where the length given overrides that
5836 specified by an explicit size clause for the component type. A
5837 warning is similarly given in the array case if a specified
5838 component size overrides an explicit size clause for the array
5839 component type.
5840 Note that @option{-gnatwa} does not affect the setting of this warning option.
5842 @item -gnatw.S
5843 @emph{Suppress warnings on overridden size clauses.}
5844 @cindex @option{-gnatw.S} (@command{gcc})
5845 This switch suppresses warnings on component clauses in record
5846 representation clauses that override size clauses, and similar
5847 warnings when an array component size overrides a size clause.
5849 @item -gnatwt
5850 @emph{Activate warnings for tracking of deleted conditional code.}
5851 @cindex @option{-gnatwt} (@command{gcc})
5852 @cindex Deactivated code, warnings
5853 @cindex Deleted code, warnings
5854 This switch activates warnings for tracking of code in conditionals (IF and
5855 CASE statements) that is detected to be dead code which cannot be executed, and
5856 which is removed by the front end. This warning is off by default, and is not
5857 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5858 useful for detecting deactivated code in certified applications.
5860 @item -gnatwT
5861 @emph{Suppress warnings for tracking of deleted conditional code.}
5862 @cindex @option{-gnatwT} (@command{gcc})
5863 This switch suppresses warnings for tracking of deleted conditional code.
5865 @item -gnatw.t
5866 @emph{Activate warnings on suspicious contracts.}
5867 @cindex @option{-gnatw.t} (@command{gcc})
5868 This switch activates warnings on suspicious postconditions (whether a
5869 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5870 and suspicious contract cases (pragma @code{Contract_Case}). A
5871 function postcondition or contract case is suspicious when no postcondition
5872 or contract case for this function mentions the result of the function.
5873 A procedure postcondition or contract case is suspicious when it only
5874 refers to the pre-state of the procedure, because in that case it should
5875 rather be expressed as a precondition. The default is that such warnings
5876 are not generated. This warning can also be turned on using @option{-gnatwa}.
5878 @item -gnatw.T
5879 @emph{Suppress warnings on suspicious contracts.}
5880 @cindex @option{-gnatw.T} (@command{gcc})
5881 This switch suppresses warnings on suspicious postconditions.
5883 @item -gnatwu
5884 @emph{Activate warnings on unused entities.}
5885 @cindex @option{-gnatwu} (@command{gcc})
5886 This switch activates warnings to be generated for entities that
5887 are declared but not referenced, and for units that are @code{with}'ed
5888 and not
5889 referenced. In the case of packages, a warning is also generated if
5890 no entities in the package are referenced. This means that if a with'ed
5891 package is referenced but the only references are in @code{use}
5892 clauses or @code{renames}
5893 declarations, a warning is still generated. A warning is also generated
5894 for a generic package that is @code{with}'ed but never instantiated.
5895 In the case where a package or subprogram body is compiled, and there
5896 is a @code{with} on the corresponding spec
5897 that is only referenced in the body,
5898 a warning is also generated, noting that the
5899 @code{with} can be moved to the body. The default is that
5900 such warnings are not generated.
5901 This switch also activates warnings on unreferenced formals
5902 (it includes the effect of @option{-gnatwf}).
5903 This warning can also be turned on using @option{-gnatwa}.
5905 @item -gnatwU
5906 @emph{Suppress warnings on unused entities.}
5907 @cindex @option{-gnatwU} (@command{gcc})
5908 This switch suppresses warnings for unused entities and packages.
5909 It also turns off warnings on unreferenced formals (and thus includes
5910 the effect of @option{-gnatwF}).
5912 @item -gnatw.u
5913 @emph{Activate warnings on unordered enumeration types.}
5914 @cindex @option{-gnatw.u} (@command{gcc})
5915 This switch causes enumeration types to be considered as conceptually
5916 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5917 The effect is to generate warnings in clients that use explicit comparisons
5918 or subranges, since these constructs both treat objects of the type as
5919 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5920 which the type is declared, or its body or subunits.) Please refer to
5921 the description of pragma @code{Ordered} in the
5922 @cite{@value{EDITION} Reference Manual} for further details.
5923 The default is that such warnings are not generated.
5924 This warning is not automatically turned on by the use of @option{-gnatwa}.
5926 @item -gnatw.U
5927 @emph{Deactivate warnings on unordered enumeration types.}
5928 @cindex @option{-gnatw.U} (@command{gcc})
5929 This switch causes all enumeration types to be considered as ordered, so
5930 that no warnings are given for comparisons or subranges for any type.
5932 @item -gnatwv
5933 @emph{Activate warnings on unassigned variables.}
5934 @cindex @option{-gnatwv} (@command{gcc})
5935 @cindex Unassigned variable warnings
5936 This switch activates warnings for access to variables which
5937 may not be properly initialized. The default is that
5938 such warnings are generated.
5939 This warning can also be turned on using @option{-gnatwa}.
5941 @item -gnatwV
5942 @emph{Suppress warnings on unassigned variables.}
5943 @cindex @option{-gnatwV} (@command{gcc})
5944 This switch suppresses warnings for access to variables which
5945 may not be properly initialized.
5946 For variables of a composite type, the warning can also be suppressed in
5947 Ada 2005 by using a default initialization with a box. For example, if
5948 Table is an array of records whose components are only partially uninitialized,
5949 then the following code:
5951 @smallexample @c ada
5952    Tab : Table := (others => <>);
5953 @end smallexample
5955 will suppress warnings on subsequent statements that access components
5956 of variable Tab.
5958 @item -gnatw.v
5959 @emph{Activate info messages for non-default bit order.}
5960 @cindex @option{-gnatw.v} (@command{gcc})
5961 @cindex bit order warnings
5962 This switch activates messages (labeled "info", they are not warnings,
5963 just informational messages) about the effects of non-default bit-order
5964 on records to which a component clause is applied. The effect of specifying
5965 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5966 these messages, which are given by default, are useful in understanding the
5967 exact consequences of using this feature. These messages
5968 can also be turned on using @option{-gnatwa}
5970 @item -gnatw.V
5971 @emph{Suppress info messages for non-default bit order.}
5972 @cindex @option{-gnatw.V} (@command{gcc})
5973 This switch suppresses information messages for the effects of specifying
5974 non-default bit order on record components with component clauses.
5976 @item -gnatww
5977 @emph{Activate warnings on wrong low bound assumption.}
5978 @cindex @option{-gnatww} (@command{gcc})
5979 @cindex String indexing warnings
5980 This switch activates warnings for indexing an unconstrained string parameter
5981 with a literal or S'Length. This is a case where the code is assuming that the
5982 low bound is one, which is in general not true (for example when a slice is
5983 passed). The default is that such warnings are generated.
5984 This warning can also be turned on using @option{-gnatwa}.
5986 @item -gnatwW
5987 @emph{Suppress warnings on wrong low bound assumption.}
5988 @cindex @option{-gnatwW} (@command{gcc})
5989 This switch suppresses warnings for indexing an unconstrained string parameter
5990 with a literal or S'Length. Note that this warning can also be suppressed
5991 in a particular case by adding an
5992 assertion that the lower bound is 1,
5993 as shown in the following example.
5995 @smallexample @c ada
5996    procedure K (S : String) is
5997       pragma Assert (S'First = 1);
5998       @dots{}
5999 @end smallexample
6001 @item -gnatw.w
6002 @emph{Activate warnings on unnecessary Warnings Off pragmas}
6003 @cindex @option{-gnatw.w} (@command{gcc})
6004 @cindex Warnings Off control
6005 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
6006 where either the pragma is entirely useless (because it suppresses no
6007 warnings), or it could be replaced by @code{pragma Unreferenced} or
6008 @code{pragma Unmodified}. The default is that these warnings are not given.
6009 Note that this warning is not included in -gnatwa, it must be
6010 activated explicitly.
6012 @item -gnatw.W
6013 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
6014 @cindex @option{-gnatw.W} (@command{gcc})
6015 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
6017 @item -gnatwx
6018 @emph{Activate warnings on Export/Import pragmas.}
6019 @cindex @option{-gnatwx} (@command{gcc})
6020 @cindex Export/Import pragma warnings
6021 This switch activates warnings on Export/Import pragmas when
6022 the compiler detects a possible conflict between the Ada and
6023 foreign language calling sequences. For example, the use of
6024 default parameters in a convention C procedure is dubious
6025 because the C compiler cannot supply the proper default, so
6026 a warning is issued. The default is that such warnings are
6027 generated.
6028 This warning can also be turned on using @option{-gnatwa}.
6030 @item -gnatwX
6031 @emph{Suppress warnings on Export/Import pragmas.}
6032 @cindex @option{-gnatwX} (@command{gcc})
6033 This switch suppresses warnings on Export/Import pragmas.
6034 The sense of this is that you are telling the compiler that
6035 you know what you are doing in writing the pragma, and it
6036 should not complain at you.
6038 @item -gnatw.x
6039 @emph{Activate warnings for No_Exception_Propagation mode.}
6040 @cindex @option{-gnatwm} (@command{gcc})
6041 This switch activates warnings for exception usage when pragma Restrictions
6042 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
6043 explicit exception raises which are not covered by a local handler, and for
6044 exception handlers which do not cover a local raise. The default is that these
6045 warnings are not given.
6047 @item -gnatw.X
6048 @emph{Disable warnings for No_Exception_Propagation mode.}
6049 This switch disables warnings for exception usage when pragma Restrictions
6050 (No_Exception_Propagation) is in effect.
6052 @item -gnatwy
6053 @emph{Activate warnings for Ada compatibility issues.}
6054 @cindex @option{-gnatwy} (@command{gcc})
6055 @cindex Ada compatibility issues warnings
6056 For the most part, newer versions of Ada are upwards compatible
6057 with older versions. For example, Ada 2005 programs will almost
6058 always work when compiled as Ada 2012.
6059 However there are some exceptions (for example the fact that
6060 @code{some} is now a reserved word in Ada 2012). This
6061 switch activates several warnings to help in identifying
6062 and correcting such incompatibilities. The default is that
6063 these warnings are generated. Note that at one point Ada 2005
6064 was called Ada 0Y, hence the choice of character.
6065 This warning can also be turned on using @option{-gnatwa}.
6067 @item -gnatwY
6068 @emph{Disable warnings for Ada compatibility issues.}
6069 @cindex @option{-gnatwY} (@command{gcc})
6070 @cindex Ada compatibility issues warnings
6071 This switch suppresses the warnings intended to help in identifying
6072 incompatibilities between Ada language versions.
6074 @item -gnatwz
6075 @emph{Activate warnings on unchecked conversions.}
6076 @cindex @option{-gnatwz} (@command{gcc})
6077 @cindex Unchecked_Conversion warnings
6078 This switch activates warnings for unchecked conversions
6079 where the types are known at compile time to have different
6080 sizes. The default
6081 is that such warnings are generated. Warnings are also
6082 generated for subprogram pointers with different conventions,
6083 and, on VMS only, for data pointers with different conventions.
6084 This warning can also be turned on using @option{-gnatwa}.
6086 @item -gnatwZ
6087 @emph{Suppress warnings on unchecked conversions.}
6088 @cindex @option{-gnatwZ} (@command{gcc})
6089 This switch suppresses warnings for unchecked conversions
6090 where the types are known at compile time to have different
6091 sizes or conventions.
6093 @item ^-Wunused^WARNINGS=UNUSED^
6094 @cindex @option{-Wunused}
6095 The warnings controlled by the @option{-gnatw} switch are generated by
6096 the front end of the compiler. The @option{GCC} back end can provide
6097 additional warnings and they are controlled by the @option{-W} switch.
6098 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
6099 warnings for entities that are declared but not referenced.
6101 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
6102 @cindex @option{-Wuninitialized}
6103 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
6104 the back end warning for uninitialized variables. This switch must be
6105 used in conjunction with an optimization level greater than zero.
6107 @item -Wstack-usage=@var{len}
6108 @cindex @option{-Wstack-usage}
6109 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
6110 See @ref{Static Stack Usage Analysis} for details.
6112 @item ^-Wall^/ALL_BACK_END_WARNINGS^
6113 @cindex @option{-Wall}
6114 This switch enables most warnings from the @option{GCC} back end.
6115 The code generator detects a number of warning situations that are missed
6116 by the @option{GNAT} front end, and this switch can be used to activate them.
6117 The use of this switch also sets the default front end warning mode to
6118 @option{-gnatwa}, that is, most front end warnings activated as well.
6120 @item ^-w^/NO_BACK_END_WARNINGS^
6121 @cindex @option{-w}
6122 Conversely, this switch suppresses warnings from the @option{GCC} back end.
6123 The use of this switch also sets the default front end warning mode to
6124 @option{-gnatws}, that is, front end warnings suppressed as well.
6126 @end table
6128 @noindent
6129 @ifclear vms
6130 A string of warning parameters can be used in the same parameter. For example:
6132 @smallexample
6133 -gnatwaGe
6134 @end smallexample
6136 @noindent
6137 will turn on all optional warnings except for unrecognized pragma warnings,
6138 and also specify that warnings should be treated as errors.
6139 @end ifclear
6141 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
6143 @table @option
6144 @c !sort!
6145 @item -gnatw.a
6146 @item -gnatwB
6147 @item -gnatw.b
6148 @item -gnatwC
6149 @item -gnatw.C
6150 @item -gnatwD
6151 @item -gnatwF
6152 @item -gnatwg
6153 @item -gnatwH
6154 @item -gnatwi
6155 @item -gnatw.I
6156 @item -gnatwJ
6157 @item -gnatwK
6158 @item -gnatwL
6159 @item -gnatw.L
6160 @item -gnatwM
6161 @item -gnatw.m
6162 @item -gnatwn
6163 @item -gnatwo
6164 @item -gnatw.O
6165 @item -gnatwP
6166 @item -gnatw.P
6167 @item -gnatwq
6168 @item -gnatwR
6169 @item -gnatw.R
6170 @item -gnatw.S
6171 @item -gnatwT
6172 @item -gnatw.T
6173 @item -gnatwU
6174 @item -gnatwv
6175 @item -gnatww
6176 @item -gnatw.W
6177 @item -gnatwx
6178 @item -gnatw.X
6179 @item -gnatwy
6180 @item -gnatwz
6182 @end table
6184 @node Debugging and Assertion Control
6185 @subsection Debugging and Assertion Control
6187 @table @option
6188 @item -gnata
6189 @cindex @option{-gnata} (@command{gcc})
6190 @findex Assert
6191 @findex Debug
6192 @cindex Assertions
6194 @noindent
6195 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6196 are ignored. This switch, where @samp{a} stands for assert, causes
6197 @code{Assert} and @code{Debug} pragmas to be activated.
6199 The pragmas have the form:
6201 @smallexample
6202 @cartouche
6203    @b{pragma} Assert (@var{Boolean-expression} @r{[},
6204                       @var{static-string-expression}@r{]})
6205    @b{pragma} Debug (@var{procedure call})
6206 @end cartouche
6207 @end smallexample
6209 @noindent
6210 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6211 If the result is @code{True}, the pragma has no effect (other than
6212 possible side effects from evaluating the expression). If the result is
6213 @code{False}, the exception @code{Assert_Failure} declared in the package
6214 @code{System.Assertions} is
6215 raised (passing @var{static-string-expression}, if present, as the
6216 message associated with the exception). If no string expression is
6217 given the default is a string giving the file name and line number
6218 of the pragma.
6220 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6221 @code{pragma Debug} may appear within a declaration sequence, allowing
6222 debugging procedures to be called between declarations.
6224 @ifset vms
6225 @item /DEBUG@r{[}=debug-level@r{]}
6226 @itemx  /NODEBUG
6227 Specifies how much debugging information is to be included in
6228 the resulting object file where 'debug-level' is one of the following:
6229 @table @code
6230 @item   TRACEBACK
6231 Include both debugger symbol records and traceback
6232 the object file.
6233 This is the default setting.
6234 @item   ALL
6235 Include both debugger symbol records and traceback in
6236 object file.
6237 @item   NONE
6238 Excludes both debugger symbol records and traceback
6239 the object file. Same as /NODEBUG.
6240 @item   SYMBOLS
6241 Includes only debugger symbol records in the object
6242 file. Note that this doesn't include traceback information.
6243 @end table
6244 @end ifset
6245 @end table
6247 @node Validity Checking
6248 @subsection Validity Checking
6249 @findex Validity Checking
6251 @noindent
6252 The Ada Reference Manual defines the concept of invalid values (see
6253 RM 13.9.1). The primary source of invalid values is uninitialized
6254 variables. A scalar variable that is left uninitialized may contain
6255 an invalid value; the concept of invalid does not apply to access or
6256 composite types.
6258 It is an error to read an invalid value, but the RM does not require
6259 run-time checks to detect such errors, except for some minimal
6260 checking to prevent erroneous execution (i.e. unpredictable
6261 behavior). This corresponds to the @option{-gnatVd} switch below,
6262 which is the default. For example, by default, if the expression of a
6263 case statement is invalid, it will raise Constraint_Error rather than
6264 causing a wild jump, and if an array index on the left-hand side of an
6265 assignment is invalid, it will raise Constraint_Error rather than
6266 overwriting an arbitrary memory location.
6268 The @option{-gnatVa} may be used to enable additional validity checks,
6269 which are not required by the RM. These checks are often very
6270 expensive (which is why the RM does not require them). These checks
6271 are useful in tracking down uninitialized variables, but they are
6272 not usually recommended for production builds.
6274 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6275 control; you can enable whichever validity checks you desire. However,
6276 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6277 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6278 sufficient for non-debugging use.
6280 The @option{-gnatB} switch tells the compiler to assume that all
6281 values are valid (that is, within their declared subtype range)
6282 except in the context of a use of the Valid attribute. This means
6283 the compiler can generate more efficient code, since the range
6284 of values is better known at compile time. However, an uninitialized
6285 variable can cause wild jumps and memory corruption in this mode.
6287 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6288 checking mode as described below.
6289 @ifclear vms
6290 The @code{x} argument is a string of letters that
6291 indicate validity checks that are performed or not performed in addition
6292 to the default checks required by Ada as described above.
6293 @end ifclear
6294 @ifset vms
6295 The options allowed for this qualifier
6296 indicate validity checks that are performed or not performed in addition
6297 to the default checks required by Ada as described above.
6298 @end ifset
6300 @table @option
6301 @c !sort!
6302 @item -gnatVa
6303 @emph{All validity checks.}
6304 @cindex @option{-gnatVa} (@command{gcc})
6305 All validity checks are turned on.
6306 @ifclear vms
6307 That is, @option{-gnatVa} is
6308 equivalent to @option{gnatVcdfimorst}.
6309 @end ifclear
6311 @item -gnatVc
6312 @emph{Validity checks for copies.}
6313 @cindex @option{-gnatVc} (@command{gcc})
6314 The right hand side of assignments, and the initializing values of
6315 object declarations are validity checked.
6317 @item -gnatVd
6318 @emph{Default (RM) validity checks.}
6319 @cindex @option{-gnatVd} (@command{gcc})
6320 Some validity checks are done by default following normal Ada semantics
6321 (RM 13.9.1 (9-11)).
6322 A check is done in case statements that the expression is within the range
6323 of the subtype. If it is not, Constraint_Error is raised.
6324 For assignments to array components, a check is done that the expression used
6325 as index is within the range. If it is not, Constraint_Error is raised.
6326 Both these validity checks may be turned off using switch @option{-gnatVD}.
6327 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6328 switch @option{-gnatVd} will leave the checks turned on.
6329 Switch @option{-gnatVD} should be used only if you are sure that all such
6330 expressions have valid values. If you use this switch and invalid values
6331 are present, then the program is erroneous, and wild jumps or memory
6332 overwriting may occur.
6334 @item -gnatVe
6335 @emph{Validity checks for elementary components.}
6336 @cindex @option{-gnatVe} (@command{gcc})
6337 In the absence of this switch, assignments to record or array components are
6338 not validity checked, even if validity checks for assignments generally
6339 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6340 require valid data, but assignment of individual components does. So for
6341 example, there is a difference between copying the elements of an array with a
6342 slice assignment, compared to assigning element by element in a loop. This
6343 switch allows you to turn off validity checking for components, even when they
6344 are assigned component by component.
6346 @item -gnatVf
6347 @emph{Validity checks for floating-point values.}
6348 @cindex @option{-gnatVf} (@command{gcc})
6349 In the absence of this switch, validity checking occurs only for discrete
6350 values. If @option{-gnatVf} is specified, then validity checking also applies
6351 for floating-point values, and NaNs and infinities are considered invalid,
6352 as well as out of range values for constrained types. Note that this means
6353 that standard IEEE infinity mode is not allowed. The exact contexts
6354 in which floating-point values are checked depends on the setting of other
6355 options. For example,
6356 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6357 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6358 (the order does not matter) specifies that floating-point parameters of mode
6359 @code{in} should be validity checked.
6361 @item -gnatVi
6362 @emph{Validity checks for @code{in} mode parameters}
6363 @cindex @option{-gnatVi} (@command{gcc})
6364 Arguments for parameters of mode @code{in} are validity checked in function
6365 and procedure calls at the point of call.
6367 @item -gnatVm
6368 @emph{Validity checks for @code{in out} mode parameters.}
6369 @cindex @option{-gnatVm} (@command{gcc})
6370 Arguments for parameters of mode @code{in out} are validity checked in
6371 procedure calls at the point of call. The @code{'m'} here stands for
6372 modify, since this concerns parameters that can be modified by the call.
6373 Note that there is no specific option to test @code{out} parameters,
6374 but any reference within the subprogram will be tested in the usual
6375 manner, and if an invalid value is copied back, any reference to it
6376 will be subject to validity checking.
6378 @item -gnatVn
6379 @emph{No validity checks.}
6380 @cindex @option{-gnatVn} (@command{gcc})
6381 This switch turns off all validity checking, including the default checking
6382 for case statements and left hand side subscripts. Note that the use of
6383 the switch @option{-gnatp} suppresses all run-time checks, including
6384 validity checks, and thus implies @option{-gnatVn}. When this switch
6385 is used, it cancels any other @option{-gnatV} previously issued.
6387 @item -gnatVo
6388 @emph{Validity checks for operator and attribute operands.}
6389 @cindex @option{-gnatVo} (@command{gcc})
6390 Arguments for predefined operators and attributes are validity checked.
6391 This includes all operators in package @code{Standard},
6392 the shift operators defined as intrinsic in package @code{Interfaces}
6393 and operands for attributes such as @code{Pos}. Checks are also made
6394 on individual component values for composite comparisons, and on the
6395 expressions in type conversions and qualified expressions. Checks are
6396 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6398 @item -gnatVp
6399 @emph{Validity checks for parameters.}
6400 @cindex @option{-gnatVp} (@command{gcc})
6401 This controls the treatment of parameters within a subprogram (as opposed
6402 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6403 of parameters on a call. If either of these call options is used, then
6404 normally an assumption is made within a subprogram that the input arguments
6405 have been validity checking at the point of call, and do not need checking
6406 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6407 is not made, and parameters are not assumed to be valid, so their validity
6408 will be checked (or rechecked) within the subprogram.
6410 @item -gnatVr
6411 @emph{Validity checks for function returns.}
6412 @cindex @option{-gnatVr} (@command{gcc})
6413 The expression in @code{return} statements in functions is validity
6414 checked.
6416 @item -gnatVs
6417 @emph{Validity checks for subscripts.}
6418 @cindex @option{-gnatVs} (@command{gcc})
6419 All subscripts expressions are checked for validity, whether they appear
6420 on the right side or left side (in default mode only left side subscripts
6421 are validity checked).
6423 @item -gnatVt
6424 @emph{Validity checks for tests.}
6425 @cindex @option{-gnatVt} (@command{gcc})
6426 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6427 statements are checked, as well as guard expressions in entry calls.
6429 @end table
6431 @noindent
6432 The @option{-gnatV} switch may be followed by
6433 ^a string of letters^a list of options^
6434 to turn on a series of validity checking options.
6435 For example,
6436 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6437 specifies that in addition to the default validity checking, copies and
6438 function return expressions are to be validity checked.
6439 In order to make it easier
6440 to specify the desired combination of effects,
6441 @ifclear vms
6442 the upper case letters @code{CDFIMORST} may
6443 be used to turn off the corresponding lower case option.
6444 @end ifclear
6445 @ifset vms
6446 the prefix @code{NO} on an option turns off the corresponding validity
6447 checking:
6448 @itemize @bullet
6449 @item @code{NOCOPIES}
6450 @item @code{NODEFAULT}
6451 @item @code{NOFLOATS}
6452 @item @code{NOIN_PARAMS}
6453 @item @code{NOMOD_PARAMS}
6454 @item @code{NOOPERANDS}
6455 @item @code{NORETURNS}
6456 @item @code{NOSUBSCRIPTS}
6457 @item @code{NOTESTS}
6458 @end itemize
6459 @end ifset
6460 Thus
6461 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6462 turns on all validity checking options except for
6463 checking of @code{@b{in out}} procedure arguments.
6465 The specification of additional validity checking generates extra code (and
6466 in the case of @option{-gnatVa} the code expansion can be substantial).
6467 However, these additional checks can be very useful in detecting
6468 uninitialized variables, incorrect use of unchecked conversion, and other
6469 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6470 is useful in conjunction with the extra validity checking, since this
6471 ensures that wherever possible uninitialized variables have invalid values.
6473 See also the pragma @code{Validity_Checks} which allows modification of
6474 the validity checking mode at the program source level, and also allows for
6475 temporary disabling of validity checks.
6477 @node Style Checking
6478 @subsection Style Checking
6479 @findex Style checking
6481 @noindent
6482 The @option{-gnaty^x^(option,option,@dots{})^} switch
6483 @cindex @option{-gnaty} (@command{gcc})
6484 causes the compiler to
6485 enforce specified style rules. A limited set of style rules has been used
6486 in writing the GNAT sources themselves. This switch allows user programs
6487 to activate all or some of these checks. If the source program fails a
6488 specified style check, an appropriate message is given, preceded by
6489 the character sequence ``(style)''. This message does not prevent
6490 successful compilation (unless the @option{-gnatwe} switch is used).
6492 Note that this is by no means intended to be a general facility for
6493 checking arbitrary coding standards. It is simply an embedding of the
6494 style rules we have chosen for the GNAT sources. If you are starting
6495 a project which does not have established style standards, you may
6496 find it useful to adopt the entire set of GNAT coding standards, or
6497 some subset of them. If you already have an established set of coding
6498 standards, then it may be that selected style checking options do
6499 indeed correspond to choices you have made, but for general checking
6500 of an existing set of coding rules, you should look to the gnatcheck
6501 tool, which is designed for that purpose.
6503 @ifset vms
6504 @code{(option,option,@dots{})} is a sequence of keywords
6505 @end ifset
6506 @ifclear vms
6507 The string @var{x} is a sequence of letters or digits
6508 @end ifclear
6509 indicating the particular style
6510 checks to be performed. The following checks are defined:
6512 @table @option
6513 @c !sort!
6514 @item 0-9
6515 @emph{Specify indentation level.}
6516 If a digit from 1-9 appears
6517 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6518 then proper indentation is checked, with the digit indicating the
6519 indentation level required. A value of zero turns off this style check.
6520 The general style of required indentation is as specified by
6521 the examples in the Ada Reference Manual. Full line comments must be
6522 aligned with the @code{--} starting on a column that is a multiple of
6523 the alignment level, or they may be aligned the same way as the following
6524 non-blank line (this is useful when full line comments appear in the middle
6525 of a statement.
6527 @item ^a^ATTRIBUTE^
6528 @emph{Check attribute casing.}
6529 Attribute names, including the case of keywords such as @code{digits}
6530 used as attributes names, must be written in mixed case, that is, the
6531 initial letter and any letter following an underscore must be uppercase.
6532 All other letters must be lowercase.
6534 @item ^A^ARRAY_INDEXES^
6535 @emph{Use of array index numbers in array attributes.}
6536 When using the array attributes First, Last, Range,
6537 or Length, the index number must be omitted for one-dimensional arrays
6538 and is required for multi-dimensional arrays.
6540 @item ^b^BLANKS^
6541 @emph{Blanks not allowed at statement end.}
6542 Trailing blanks are not allowed at the end of statements. The purpose of this
6543 rule, together with h (no horizontal tabs), is to enforce a canonical format
6544 for the use of blanks to separate source tokens.
6546 @item ^B^BOOLEAN_OPERATORS^
6547 @emph{Check Boolean operators.}
6548 The use of AND/OR operators is not permitted except in the cases of modular
6549 operands, array operands, and simple stand-alone boolean variables or
6550 boolean constants. In all other cases @code{and then}/@code{or else} are
6551 required.
6553 @item ^c^COMMENTS^
6554 @emph{Check comments, double space.}
6555 Comments must meet the following set of rules:
6557 @itemize @bullet
6559 @item
6560 The ``@code{--}'' that starts the column must either start in column one,
6561 or else at least one blank must precede this sequence.
6563 @item
6564 Comments that follow other tokens on a line must have at least one blank
6565 following the ``@code{--}'' at the start of the comment.
6567 @item
6568 Full line comments must have at least two blanks following the
6569 ``@code{--}'' that starts the comment, with the following exceptions.
6571 @item
6572 A line consisting only of the ``@code{--}'' characters, possibly preceded
6573 by blanks is permitted.
6575 @item
6576 A comment starting with ``@code{--x}'' where @code{x} is a special character
6577 is permitted.
6578 This allows proper processing of the output generated by specialized tools
6579 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6580 annotation
6581 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6582 special character is defined as being in one of the ASCII ranges
6583 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6584 Note that this usage is not permitted
6585 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6587 @item
6588 A line consisting entirely of minus signs, possibly preceded by blanks, is
6589 permitted. This allows the construction of box comments where lines of minus
6590 signs are used to form the top and bottom of the box.
6592 @item
6593 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6594 least one blank follows the initial ``@code{--}''. Together with the preceding
6595 rule, this allows the construction of box comments, as shown in the following
6596 example:
6597 @smallexample
6598 ---------------------------
6599 -- This is a box comment --
6600 -- with two text lines.  --
6601 ---------------------------
6602 @end smallexample
6603 @end itemize
6605 @item ^C^COMMENTS1^
6606 @emph{Check comments, single space.}
6607 This is identical to @code{^c^COMMENTS^} except that only one space
6608 is required following the @code{--} of a comment instead of two.
6610 @item ^d^DOS_LINE_ENDINGS^
6611 @emph{Check no DOS line terminators present.}
6612 All lines must be terminated by a single ASCII.LF
6613 character (in particular the DOS line terminator sequence CR/LF is not
6614 allowed).
6616 @item ^e^END^
6617 @emph{Check end/exit labels.}
6618 Optional labels on @code{end} statements ending subprograms and on
6619 @code{exit} statements exiting named loops, are required to be present.
6621 @item ^f^VTABS^
6622 @emph{No form feeds or vertical tabs.}
6623 Neither form feeds nor vertical tab characters are permitted
6624 in the source text.
6626 @item ^g^GNAT^
6627 @emph{GNAT style mode.}
6628 The set of style check switches is set to match that used by the GNAT sources.
6629 This may be useful when developing code that is eventually intended to be
6630 incorporated into GNAT. For further details, see GNAT sources.
6632 @item ^h^HTABS^
6633 @emph{No horizontal tabs.}
6634 Horizontal tab characters are not permitted in the source text.
6635 Together with the b (no blanks at end of line) check, this
6636 enforces a canonical form for the use of blanks to separate
6637 source tokens.
6639 @item ^i^IF_THEN^
6640 @emph{Check if-then layout.}
6641 The keyword @code{then} must appear either on the same
6642 line as corresponding @code{if}, or on a line on its own, lined
6643 up under the @code{if} with at least one non-blank line in between
6644 containing all or part of the condition to be tested.
6646 @item ^I^IN_MODE^
6647 @emph{check mode IN keywords.}
6648 Mode @code{in} (the default mode) is not
6649 allowed to be given explicitly. @code{in out} is fine,
6650 but not @code{in} on its own.
6652 @item ^k^KEYWORD^
6653 @emph{Check keyword casing.}
6654 All keywords must be in lower case (with the exception of keywords
6655 such as @code{digits} used as attribute names to which this check
6656 does not apply).
6658 @item ^l^LAYOUT^
6659 @emph{Check layout.}
6660 Layout of statement and declaration constructs must follow the
6661 recommendations in the Ada Reference Manual, as indicated by the
6662 form of the syntax rules. For example an @code{else} keyword must
6663 be lined up with the corresponding @code{if} keyword.
6665 There are two respects in which the style rule enforced by this check
6666 option are more liberal than those in the Ada Reference Manual. First
6667 in the case of record declarations, it is permissible to put the
6668 @code{record} keyword on the same line as the @code{type} keyword, and
6669 then the @code{end} in @code{end record} must line up under @code{type}.
6670 This is also permitted when the type declaration is split on two lines.
6671 For example, any of the following three layouts is acceptable:
6673 @smallexample @c ada
6674 @cartouche
6675 type q is record
6676    a : integer;
6677    b : integer;
6678 end record;
6680 type q is
6681    record
6682       a : integer;
6683       b : integer;
6684    end record;
6686 type q is
6687    record
6688       a : integer;
6689       b : integer;
6690 end record;
6692 @end cartouche
6693 @end smallexample
6695 @noindent
6696 Second, in the case of a block statement, a permitted alternative
6697 is to put the block label on the same line as the @code{declare} or
6698 @code{begin} keyword, and then line the @code{end} keyword up under
6699 the block label. For example both the following are permitted:
6701 @smallexample @c ada
6702 @cartouche
6703 Block : declare
6704    A : Integer := 3;
6705 begin
6706    Proc (A, A);
6707 end Block;
6709 Block :
6710    declare
6711       A : Integer := 3;
6712    begin
6713       Proc (A, A);
6714    end Block;
6715 @end cartouche
6716 @end smallexample
6718 @noindent
6719 The same alternative format is allowed for loops. For example, both of
6720 the following are permitted:
6722 @smallexample @c ada
6723 @cartouche
6724 Clear : while J < 10 loop
6725    A (J) := 0;
6726 end loop Clear;
6728 Clear :
6729    while J < 10 loop
6730       A (J) := 0;
6731    end loop Clear;
6732 @end cartouche
6733 @end smallexample
6735 @item ^Lnnn^MAX_NESTING=nnn^
6736 @emph{Set maximum nesting level.}
6737 The maximum level of nesting of constructs (including subprograms, loops,
6738 blocks, packages, and conditionals) may not exceed the given value
6739 @option{nnn}. A value of zero disconnects this style check.
6741 @item ^m^LINE_LENGTH^
6742 @emph{Check maximum line length.}
6743 The length of source lines must not exceed 79 characters, including
6744 any trailing blanks. The value of 79 allows convenient display on an
6745 80 character wide device or window, allowing for possible special
6746 treatment of 80 character lines. Note that this count is of
6747 characters in the source text. This means that a tab character counts
6748 as one character in this count and a wide character sequence counts as
6749 a single character (however many bytes are needed in the encoding).
6751 @item ^Mnnn^MAX_LENGTH=nnn^
6752 @emph{Set maximum line length.}
6753 The length of lines must not exceed the
6754 given value @option{nnn}. The maximum value that can be specified is 32767.
6755 If neither style option for setting the line length is used, then the
6756 default is 255. This also controls the maximum length of lexical elements,
6757 where the only restriction is that they must fit on a single line.
6759 @item ^n^STANDARD_CASING^
6760 @emph{Check casing of entities in Standard.}
6761 Any identifier from Standard must be cased
6762 to match the presentation in the Ada Reference Manual (for example,
6763 @code{Integer} and @code{ASCII.NUL}).
6765 @item ^N^NONE^
6766 @emph{Turn off all style checks.}
6767 All style check options are turned off.
6769 @item ^o^ORDERED_SUBPROGRAMS^
6770 @emph{Check order of subprogram bodies.}
6771 All subprogram bodies in a given scope
6772 (e.g.@: a package body) must be in alphabetical order. The ordering
6773 rule uses normal Ada rules for comparing strings, ignoring casing
6774 of letters, except that if there is a trailing numeric suffix, then
6775 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6776 before Junk10).
6778 @item ^O^OVERRIDING_INDICATORS^
6779 @emph{Check that overriding subprograms are explicitly marked as such.}
6780 The declaration of a primitive operation of a type extension that overrides
6781 an inherited operation must carry an overriding indicator.
6783 @item ^p^PRAGMA^
6784 @emph{Check pragma casing.}
6785 Pragma names must be written in mixed case, that is, the
6786 initial letter and any letter following an underscore must be uppercase.
6787 All other letters must be lowercase.
6789 @item ^r^REFERENCES^
6790 @emph{Check references.}
6791 All identifier references must be cased in the same way as the
6792 corresponding declaration. No specific casing style is imposed on
6793 identifiers. The only requirement is for consistency of references
6794 with declarations.
6796 @item ^s^SPECS^
6797 @emph{Check separate specs.}
6798 Separate declarations (``specs'') are required for subprograms (a
6799 body is not allowed to serve as its own declaration). The only
6800 exception is that parameterless library level procedures are
6801 not required to have a separate declaration. This exception covers
6802 the most frequent form of main program procedures.
6804 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6805 @emph{Check no statements after @code{then}/@code{else}.}
6806 No statements are allowed
6807 on the same line as a @code{then} or @code{else} keyword following the
6808 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6809 affected, and a special exception allows a pragma to appear after @code{else}.
6811 @item ^t^TOKEN^
6812 @emph{Check token spacing.}
6813 The following token spacing rules are enforced:
6815 @itemize @bullet
6817 @item
6818 The keywords @code{abs} and @code{not} must be followed by a space.
6820 @item
6821 The token @code{=>} must be surrounded by spaces.
6823 @item
6824 The token @code{<>} must be preceded by a space or a left parenthesis.
6826 @item
6827 Binary operators other than @code{**} must be surrounded by spaces.
6828 There is no restriction on the layout of the @code{**} binary operator.
6830 @item
6831 Colon must be surrounded by spaces.
6833 @item
6834 Colon-equal (assignment, initialization) must be surrounded by spaces.
6836 @item
6837 Comma must be the first non-blank character on the line, or be
6838 immediately preceded by a non-blank character, and must be followed
6839 by a space.
6841 @item
6842 If the token preceding a left parenthesis ends with a letter or digit, then
6843 a space must separate the two tokens.
6845 @item
6846 if the token following a right parenthesis starts with a letter or digit, then
6847 a space must separate the two tokens.
6849 @item
6850 A right parenthesis must either be the first non-blank character on
6851 a line, or it must be preceded by a non-blank character.
6853 @item
6854 A semicolon must not be preceded by a space, and must not be followed by
6855 a non-blank character.
6857 @item
6858 A unary plus or minus may not be followed by a space.
6860 @item
6861 A vertical bar must be surrounded by spaces.
6862 @end itemize
6864 @item
6865 Exactly one blank (and no other white space) must appear between
6866 a @code{not} token and a following @code{in} token.
6868 @item ^u^UNNECESSARY_BLANK_LINES^
6869 @emph{Check unnecessary blank lines.}
6870 Unnecessary blank lines are not allowed. A blank line is considered
6871 unnecessary if it appears at the end of the file, or if more than
6872 one blank line occurs in sequence.
6874 @item ^x^XTRA_PARENS^
6875 @emph{Check extra parentheses.}
6876 Unnecessary extra level of parentheses (C-style) are not allowed
6877 around conditions in @code{if} statements, @code{while} statements and
6878 @code{exit} statements.
6880 @item ^y^ALL_BUILTIN^
6881 @emph{Set all standard style check options}
6882 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6883 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6884 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6885 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6887 @ifclear vms
6888 @item -
6889 @emph{Remove style check options}
6890 This causes any subsequent options in the string to act as canceling the
6891 corresponding style check option. To cancel maximum nesting level control,
6892 use @option{L} parameter witout any integer value after that, because any
6893 digit following @option{-} in the parameter string of the @option{-gnaty}
6894 option will be threated as canceling indentation check. The same is true
6895 for @option{M} parameter. @option{y} and @option{N} parameters are not
6896 allowed after @option{-}.
6898 @item +
6899 This causes any subsequent options in the string to enable the corresponding
6900 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6901 if any.
6902 @end ifclear
6904 @ifset vms
6905 @item NOxxx
6906 @emph{Removing style check options}
6907 If the name of a style check is preceded by @option{NO} then the corresponding
6908 style check is turned off. For example @option{NOCOMMENTS} turns off style
6909 checking for comments.
6910 @end ifset
6911 @end table
6913 @noindent
6914 In the above rules, appearing in column one is always permitted, that is,
6915 counts as meeting either a requirement for a required preceding space,
6916 or as meeting a requirement for no preceding space.
6918 Appearing at the end of a line is also always permitted, that is, counts
6919 as meeting either a requirement for a following space, or as meeting
6920 a requirement for no following space.
6922 @noindent
6923 If any of these style rules is violated, a message is generated giving
6924 details on the violation. The initial characters of such messages are
6925 always ``@code{(style)}''. Note that these messages are treated as warning
6926 messages, so they normally do not prevent the generation of an object
6927 file. The @option{-gnatwe} switch can be used to treat warning messages,
6928 including style messages, as fatal errors.
6930 The switch
6931 @ifclear vms
6932 @option{-gnaty} on its own (that is not
6933 followed by any letters or digits) is equivalent
6934 to the use of @option{-gnatyy} as described above, that is all
6935 built-in standard style check options are enabled.
6937 @end ifclear
6938 @ifset vms
6939 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6940 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6941 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6942 @end ifset
6944 The switch
6945 @ifclear vms
6946 @option{-gnatyN}
6947 @end ifclear
6948 @ifset vms
6949 /STYLE_CHECKS=NONE
6950 @end ifset
6951 clears any previously set style checks.
6953 @node Run-Time Checks
6954 @subsection Run-Time Checks
6955 @cindex Division by zero
6956 @cindex Access before elaboration
6957 @cindex Checks, division by zero
6958 @cindex Checks, access before elaboration
6959 @cindex Checks, stack overflow checking
6961 @noindent
6962 By default, the following checks are suppressed: integer overflow
6963 checks, stack overflow checks, and checks for access before
6964 elaboration on subprogram calls. All other checks, including range
6965 checks and array bounds checks, are turned on by default. The
6966 following @command{gcc} switches refine this default behavior.
6968 @table @option
6969 @c !sort!
6970 @item -gnatp
6971 @cindex @option{-gnatp} (@command{gcc})
6972 @cindex Suppressing checks
6973 @cindex Checks, suppressing
6974 @findex Suppress
6975 This switch causes the unit to be compiled
6976 as though @code{pragma Suppress (All_checks)}
6977 had been present in the source. Validity checks are also eliminated (in
6978 other words @option{-gnatp} also implies @option{-gnatVn}.
6979 Use this switch to improve the performance
6980 of the code at the expense of safety in the presence of invalid data or
6981 program bugs.
6983 Note that when checks are suppressed, the compiler is allowed, but not
6984 required, to omit the checking code. If the run-time cost of the
6985 checking code is zero or near-zero, the compiler will generate it even
6986 if checks are suppressed. In particular, if the compiler can prove
6987 that a certain check will necessarily fail, it will generate code to
6988 do an unconditional ``raise'', even if checks are suppressed. The
6989 compiler warns in this case. Another case in which checks may not be
6990 eliminated is when they are embedded in certain run time routines such
6991 as math library routines.
6993 Of course, run-time checks are omitted whenever the compiler can prove
6994 that they will not fail, whether or not checks are suppressed.
6996 Note that if you suppress a check that would have failed, program
6997 execution is erroneous, which means the behavior is totally
6998 unpredictable. The program might crash, or print wrong answers, or
6999 do anything else. It might even do exactly what you wanted it to do
7000 (and then it might start failing mysteriously next week or next
7001 year). The compiler will generate code based on the assumption that
7002 the condition being checked is true, which can result in disaster if
7003 that assumption is wrong.
7005 The @option{-gnatp} switch has no effect if a subsequent
7006 @option{-gnat-p} switch appears.
7008 @item -gnat-p
7009 @cindex @option{-gnat-p} (@command{gcc})
7010 @cindex Suppressing checks
7011 @cindex Checks, suppressing
7012 @findex Suppress
7013 This switch cancels the effect of a previous @option{gnatp} switch.
7015 @item -gnato??
7016 @cindex @option{-gnato??} (@command{gcc})
7017 @cindex Overflow checks
7018 @cindex Overflow mode
7019 @cindex Check, overflow
7020 This switch controls the mode used for computing intermediate
7021 arithmetic integer operations, and also enables overflow checking.
7022 For a full description of overflow mode and checking control, see
7023 the ``Overflow Check Handling in GNAT'' appendix in this
7024 User's Guide.
7026 Overflow checks are always enabled by this switch. The argument
7027 controls the mode, using the codes
7029 @itemize
7030 @item 1 = STRICT
7031 In STRICT mode, intermediate operations are always done using the
7032 base type, and overflow checking ensures that the result is within
7033 the base type range.
7035 @item 2 = MINIMIZED
7036 In MINIMIZED mode, overflows in intermediate operations are avoided
7037 where possible by using a larger integer type for the computation
7038 (typically @code{Long_Long_Integer}). Overflow checking ensures that
7039 the result fits in this larger integer type.
7041 @item 3 = ELIMINATED
7042 In ELIMINATED mode, overflows in intermediate operations are avoided
7043 by using multi-precision arithmetic. In this case, overflow checking
7044 has no effect on intermediate operations (since overflow is impossible).
7045 @end itemize
7047 If two digits are present after @option{-gnato} then the first digit
7048 sets the mode for expressions outside assertions, and the second digit
7049 sets the mode for expressions within assertions. Here assertions is used
7050 in the technical sense (which includes for example precondition and
7051 postcondition expressions).
7053 If one digit is present, the corresponding mode is applicable to both
7054 expressions within and outside assertion expressions.
7056 If no digits are present, the default is to enable overflow checks
7057 and set STRICT mode for both kinds of expressions. This is compatible
7058 with the use of @option{-gnato} in previous versions of GNAT.
7060 @findex Machine_Overflows
7061 Note that the @option{-gnato??} switch does not affect the code generated
7062 for any floating-point operations; it applies only to integer
7063 semantics.
7064 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
7065 attribute set to @code{False} and the normal mode of operation is to
7066 generate IEEE NaN and infinite values on overflow or invalid operations
7067 (such as dividing 0.0 by 0.0).
7069 The reason that we distinguish overflow checking from other kinds of
7070 range constraint checking is that a failure of an overflow check, unlike
7071 for example the failure of a range check, can result in an incorrect
7072 value, but cannot cause random memory destruction (like an out of range
7073 subscript), or a wild jump (from an out of range case value). Overflow
7074 checking is also quite expensive in time and space, since in general it
7075 requires the use of double length arithmetic.
7077 Note again that the default is @option{-gnato00}, so overflow checking is
7078 not performed in default mode. This means that out of the box, with the
7079 default settings, @value{EDITION} does not do all the checks expected from the
7080 language description in the Ada Reference Manual. If you want all constraint
7081 checks to be performed, as described in this Manual, then you must
7082 explicitly use the @option{-gnato??} switch either on the @command{gnatmake} or
7083 @command{gcc} command.
7085 @item -gnatE
7086 @cindex @option{-gnatE} (@command{gcc})
7087 @cindex Elaboration checks
7088 @cindex Check, elaboration
7089 Enables dynamic checks for access-before-elaboration
7090 on subprogram calls and generic instantiations.
7091 Note that @option{-gnatE} is not necessary for safety, because in the
7092 default mode, GNAT ensures statically that the checks would not fail.
7093 For full details of the effect and use of this switch,
7094 @xref{Compiling Using gcc}.
7096 @item -fstack-check
7097 @cindex @option{-fstack-check} (@command{gcc})
7098 @cindex Stack Overflow Checking
7099 @cindex Checks, stack overflow checking
7100 Activates stack overflow checking. For full details of the effect and use of
7101 this switch see @ref{Stack Overflow Checking}.
7102 @end table
7104 @findex Unsuppress
7105 @noindent
7106 The setting of these switches only controls the default setting of the
7107 checks. You may modify them using either @code{Suppress} (to remove
7108 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
7109 the program source.
7111 @node Using gcc for Syntax Checking
7112 @subsection Using @command{gcc} for Syntax Checking
7113 @table @option
7114 @item -gnats
7115 @cindex @option{-gnats} (@command{gcc})
7116 @ifclear vms
7118 @noindent
7119 The @code{s} stands for ``syntax''.
7120 @end ifclear
7122 Run GNAT in syntax checking only mode. For
7123 example, the command
7125 @smallexample
7126 $ gcc -c -gnats x.adb
7127 @end smallexample
7129 @noindent
7130 compiles file @file{x.adb} in syntax-check-only mode. You can check a
7131 series of files in a single command
7132 @ifclear vms
7133 , and can use wild cards to specify such a group of files.
7134 Note that you must specify the @option{-c} (compile
7135 only) flag in addition to the @option{-gnats} flag.
7136 @end ifclear
7138 You may use other switches in conjunction with @option{-gnats}. In
7139 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
7140 format of any generated error messages.
7142 When the source file is empty or contains only empty lines and/or comments,
7143 the output is a warning:
7145 @smallexample
7146 $ gcc -c -gnats -x ada toto.txt
7147 toto.txt:1:01: warning: empty file, contains no compilation units
7149 @end smallexample
7151 Otherwise, the output is simply the error messages, if any. No object file or
7152 ALI file is generated by a syntax-only compilation. Also, no units other
7153 than the one specified are accessed. For example, if a unit @code{X}
7154 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
7155 check only mode does not access the source file containing unit
7156 @code{Y}.
7158 @cindex Multiple units, syntax checking
7159 Normally, GNAT allows only a single unit in a source file. However, this
7160 restriction does not apply in syntax-check-only mode, and it is possible
7161 to check a file containing multiple compilation units concatenated
7162 together. This is primarily used by the @code{gnatchop} utility
7163 (@pxref{Renaming Files Using gnatchop}).
7164 @end table
7166 @node Using gcc for Semantic Checking
7167 @subsection Using @command{gcc} for Semantic Checking
7168 @table @option
7169 @item -gnatc
7170 @cindex @option{-gnatc} (@command{gcc})
7172 @ifclear vms
7173 @noindent
7174 The @code{c} stands for ``check''.
7175 @end ifclear
7176 Causes the compiler to operate in semantic check mode,
7177 with full checking for all illegalities specified in the
7178 Ada Reference Manual, but without generation of any object code
7179 (no object file is generated).
7181 Because dependent files must be accessed, you must follow the GNAT
7182 semantic restrictions on file structuring to operate in this mode:
7184 @itemize @bullet
7185 @item
7186 The needed source files must be accessible
7187 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7189 @item
7190 Each file must contain only one compilation unit.
7192 @item
7193 The file name and unit name must match (@pxref{File Naming Rules}).
7194 @end itemize
7196 The output consists of error messages as appropriate. No object file is
7197 generated. An @file{ALI} file is generated for use in the context of
7198 cross-reference tools, but this file is marked as not being suitable
7199 for binding (since no object file is generated).
7200 The checking corresponds exactly to the notion of
7201 legality in the Ada Reference Manual.
7203 Any unit can be compiled in semantics-checking-only mode, including
7204 units that would not normally be compiled (subunits,
7205 and specifications where a separate body is present).
7206 @end table
7208 @node Compiling Different Versions of Ada
7209 @subsection Compiling Different Versions of Ada
7211 @noindent
7212 The switches described in this section allow you to explicitly specify
7213 the version of the Ada language that your programs are written in.
7214 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
7215 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
7216 indicate Ada 83 compatibility mode.
7218 @table @option
7219 @cindex Compatibility with Ada 83
7221 @item -gnat83 (Ada 83 Compatibility Mode)
7222 @cindex @option{-gnat83} (@command{gcc})
7223 @cindex ACVC, Ada 83 tests
7224 @cindex Ada 83 mode
7226 @noindent
7227 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7228 specifies that the program is to be compiled in Ada 83 mode. With
7229 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7230 semantics where this can be done easily.
7231 It is not possible to guarantee this switch does a perfect
7232 job; some subtle tests, such as are
7233 found in earlier ACVC tests (and that have been removed from the ACATS suite
7234 for Ada 95), might not compile correctly.
7235 Nevertheless, this switch may be useful in some circumstances, for example
7236 where, due to contractual reasons, existing code needs to be maintained
7237 using only Ada 83 features.
7239 With few exceptions (most notably the need to use @code{<>} on
7240 @cindex Generic formal parameters
7241 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7242 reserved words, and the use of packages
7243 with optional bodies), it is not necessary to specify the
7244 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7245 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7246 a correct Ada 83 program is usually also a correct program
7247 in these later versions of the language standard.
7248 For further information, please refer to @ref{Compatibility and Porting Guide}.
7250 @item -gnat95 (Ada 95 mode)
7251 @cindex @option{-gnat95} (@command{gcc})
7252 @cindex Ada 95 mode
7254 @noindent
7255 This switch directs the compiler to implement the Ada 95 version of the
7256 language.
7257 Since Ada 95 is almost completely upwards
7258 compatible with Ada 83, Ada 83 programs may generally be compiled using
7259 this switch (see the description of the @option{-gnat83} switch for further
7260 information about Ada 83 mode).
7261 If an Ada 2005 program is compiled in Ada 95 mode,
7262 uses of the new Ada 2005 features will cause error
7263 messages or warnings.
7265 This switch also can be used to cancel the effect of a previous
7266 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7267 switch earlier in the command line.
7269 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7270 @cindex @option{-gnat05} (@command{gcc})
7271 @cindex @option{-gnat2005} (@command{gcc})
7272 @cindex Ada 2005 mode
7274 @noindent
7275 This switch directs the compiler to implement the Ada 2005 version of the
7276 language, as documented in the official Ada standards document.
7277 Since Ada 2005 is almost completely upwards
7278 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7279 may generally be compiled using this switch (see the description of the
7280 @option{-gnat83} and @option{-gnat95} switches for further
7281 information).
7283 @ifset PROEDITION
7284 Note that even though Ada 2005 is the current official version of the
7285 language, GNAT still compiles in Ada 95 mode by default, so if you are
7286 using Ada 2005 features in your program, you must use this switch (or
7287 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7288 @end ifset
7290 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7291 @cindex @option{-gnat12} (@command{gcc})
7292 @cindex @option{-gnat2012} (@command{gcc})
7293 @cindex Ada 2012 mode
7295 @noindent
7296 This switch directs the compiler to implement the Ada 2012 version of the
7297 language.
7298 Since Ada 2012 is almost completely upwards
7299 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7300 Ada 83 and Ada 95 programs
7301 may generally be compiled using this switch (see the description of the
7302 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7303 for further information).
7305 For information about the approved ``Ada Issues'' that have been incorporated
7306 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7307 Included with GNAT releases is a file @file{features-ada12} that describes
7308 the set of implemented Ada 2012 features.
7310 @item -gnatX (Enable GNAT Extensions)
7311 @cindex @option{-gnatX} (@command{gcc})
7312 @cindex Ada language extensions
7313 @cindex GNAT extensions
7315 @noindent
7316 This switch directs the compiler to implement the latest version of the
7317 language (currently Ada 2012) and also to enable certain GNAT implementation
7318 extensions that are not part of any Ada standard. For a full list of these
7319 extensions, see the GNAT reference manual.
7321 @end table
7323 @node Character Set Control
7324 @subsection Character Set Control
7325 @table @option
7326 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7327 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7329 @noindent
7330 Normally GNAT recognizes the Latin-1 character set in source program
7331 identifiers, as described in the Ada Reference Manual.
7332 This switch causes
7333 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7334 single character ^^or word^ indicating the character set, as follows:
7336 @table @code
7337 @item 1
7338 ISO 8859-1 (Latin-1) identifiers
7340 @item 2
7341 ISO 8859-2 (Latin-2) letters allowed in identifiers
7343 @item 3
7344 ISO 8859-3 (Latin-3) letters allowed in identifiers
7346 @item 4
7347 ISO 8859-4 (Latin-4) letters allowed in identifiers
7349 @item 5
7350 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7352 @item 9
7353 ISO 8859-15 (Latin-9) letters allowed in identifiers
7355 @item ^p^PC^
7356 IBM PC letters (code page 437) allowed in identifiers
7358 @item ^8^PC850^
7359 IBM PC letters (code page 850) allowed in identifiers
7361 @item ^f^FULL_UPPER^
7362 Full upper-half codes allowed in identifiers
7364 @item ^n^NO_UPPER^
7365 No upper-half codes allowed in identifiers
7367 @item ^w^WIDE^
7368 Wide-character codes (that is, codes greater than 255)
7369 allowed in identifiers
7370 @end table
7372 @xref{Foreign Language Representation}, for full details on the
7373 implementation of these character sets.
7375 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7376 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7377 Specify the method of encoding for wide characters.
7378 @var{e} is one of the following:
7380 @table @code
7382 @item ^h^HEX^
7383 Hex encoding (brackets coding also recognized)
7385 @item ^u^UPPER^
7386 Upper half encoding (brackets encoding also recognized)
7388 @item ^s^SHIFT_JIS^
7389 Shift/JIS encoding (brackets encoding also recognized)
7391 @item ^e^EUC^
7392 EUC encoding (brackets encoding also recognized)
7394 @item ^8^UTF8^
7395 UTF-8 encoding (brackets encoding also recognized)
7397 @item ^b^BRACKETS^
7398 Brackets encoding only (default value)
7399 @end table
7400 For full details on these encoding
7401 methods see @ref{Wide Character Encodings}.
7402 Note that brackets coding is always accepted, even if one of the other
7403 options is specified, so for example @option{-gnatW8} specifies that both
7404 brackets and UTF-8 encodings will be recognized. The units that are
7405 with'ed directly or indirectly will be scanned using the specified
7406 representation scheme, and so if one of the non-brackets scheme is
7407 used, it must be used consistently throughout the program. However,
7408 since brackets encoding is always recognized, it may be conveniently
7409 used in standard libraries, allowing these libraries to be used with
7410 any of the available coding schemes.
7412 Note that brackets encoding only applies to program text. Within comments,
7413 brackets are considered to be normal graphic characters, and bracket sequences
7414 are never recognized as wide characters.
7416 If no @option{-gnatW?} parameter is present, then the default
7417 representation is normally Brackets encoding only. However, if the
7418 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7419 byte order mark or BOM for UTF-8), then these three characters are
7420 skipped and the default representation for the file is set to UTF-8.
7422 Note that the wide character representation that is specified (explicitly
7423 or by default) for the main program also acts as the default encoding used
7424 for Wide_Text_IO files if not specifically overridden by a WCEM form
7425 parameter.
7427 @end table
7429 When no @option{-gnatW?} is specified, then characters (other than wide
7430 characters represented using brackets notation) are treated as 8-bit
7431 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7432 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7433 characters in the range 16#00#..16#1F# are not accepted in program text
7434 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7435 in program text, but allowed and ignored in comments. Note in particular
7436 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7437 as an end of line in this default mode. If your source program contains
7438 instances of the NEL character used as a line terminator,
7439 you must use UTF-8 encoding for the whole
7440 source program. In default mode, all lines must be ended by a standard
7441 end of line sequence (CR, CR/LF, or LF).
7443 Note that the convention of simply accepting all upper half characters in
7444 comments means that programs that use standard ASCII for program text, but
7445 UTF-8 encoding for comments are accepted in default mode, providing that the
7446 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7447 This is a common mode for many programs with foreign language comments.
7449 @node File Naming Control
7450 @subsection File Naming Control
7452 @table @option
7453 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7454 @cindex @option{-gnatk} (@command{gcc})
7455 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7456 1-999, indicates the maximum allowable length of a file name (not
7457 including the @file{.ads} or @file{.adb} extension). The default is not
7458 to enable file name krunching.
7460 For the source file naming rules, @xref{File Naming Rules}.
7461 @end table
7463 @node Subprogram Inlining Control
7464 @subsection Subprogram Inlining Control
7466 @table @option
7467 @c !sort!
7468 @item -gnatn[12]
7469 @cindex @option{-gnatn} (@command{gcc})
7470 @ifclear vms
7471 The @code{n} here is intended to suggest the first syllable of the
7472 word ``inline''.
7473 @end ifclear
7474 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7475 inlining to actually occur, optimization must be enabled and, in order
7476 to enable inlining of subprograms specified by pragma @code{Inline},
7477 you must also specify this switch.
7478 In the absence of this switch, GNAT does not attempt
7479 inlining and does not need to access the bodies of
7480 subprograms for which @code{pragma Inline} is specified if they are not
7481 in the current unit.
7483 You can optionally specify the inlining level: 1 for moderate inlining across
7484 modules, which is a good compromise between compilation times and performances
7485 at run time, or 2 for full inlining across modules, which may bring about
7486 longer compilation times. If no inlining level is specified, the compiler will
7487 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7488 @option{-Os} and 2 for @option{-O3}.
7490 If you specify this switch the compiler will access these bodies,
7491 creating an extra source dependency for the resulting object file, and
7492 where possible, the call will be inlined.
7493 For further details on when inlining is possible
7494 see @ref{Inlining of Subprograms}.
7496 @item -gnatN
7497 @cindex @option{-gnatN} (@command{gcc})
7498 This switch activates front-end inlining which also
7499 generates additional dependencies.
7501 When using a gcc-based back end (in practice this means using any version
7502 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7503 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7504 Historically front end inlining was more extensive than the gcc back end
7505 inlining, but that is no longer the case.
7506 @end table
7508 @node Auxiliary Output Control
7509 @subsection Auxiliary Output Control
7511 @table @option
7512 @item -gnatt
7513 @cindex @option{-gnatt} (@command{gcc})
7514 @cindex Writing internal trees
7515 @cindex Internal trees, writing to file
7516 Causes GNAT to write the internal tree for a unit to a file (with the
7517 extension @file{.adt}.
7518 This not normally required, but is used by separate analysis tools.
7519 Typically
7520 these tools do the necessary compilations automatically, so you should
7521 not have to specify this switch in normal operation.
7522 Note that the combination of switches @option{-gnatct}
7523 generates a tree in the form required by ASIS applications.
7525 @item -gnatu
7526 @cindex @option{-gnatu} (@command{gcc})
7527 Print a list of units required by this compilation on @file{stdout}.
7528 The listing includes all units on which the unit being compiled depends
7529 either directly or indirectly.
7531 @ifclear vms
7532 @item -pass-exit-codes
7533 @cindex @option{-pass-exit-codes} (@command{gcc})
7534 If this switch is not used, the exit code returned by @command{gcc} when
7535 compiling multiple files indicates whether all source files have
7536 been successfully used to generate object files or not.
7538 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7539 exit status and allows an integrated development environment to better
7540 react to a compilation failure. Those exit status are:
7542 @table @asis
7543 @item 5
7544 There was an error in at least one source file.
7545 @item 3
7546 At least one source file did not generate an object file.
7547 @item 2
7548 The compiler died unexpectedly (internal error for example).
7549 @item 0
7550 An object file has been generated for every source file.
7551 @end table
7552 @end ifclear
7553 @end table
7555 @node Debugging Control
7556 @subsection Debugging Control
7558 @table @option
7559 @c !sort!
7560 @cindex Debugging options
7561 @ifclear vms
7562 @item -gnatd@var{x}
7563 @cindex @option{-gnatd} (@command{gcc})
7564 Activate internal debugging switches. @var{x} is a letter or digit, or
7565 string of letters or digits, which specifies the type of debugging
7566 outputs desired. Normally these are used only for internal development
7567 or system debugging purposes. You can find full documentation for these
7568 switches in the body of the @code{Debug} unit in the compiler source
7569 file @file{debug.adb}.
7570 @end ifclear
7572 @item -gnatG[=nn]
7573 @cindex @option{-gnatG} (@command{gcc})
7574 This switch causes the compiler to generate auxiliary output containing
7575 a pseudo-source listing of the generated expanded code. Like most Ada
7576 compilers, GNAT works by first transforming the high level Ada code into
7577 lower level constructs. For example, tasking operations are transformed
7578 into calls to the tasking run-time routines. A unique capability of GNAT
7579 is to list this expanded code in a form very close to normal Ada source.
7580 This is very useful in understanding the implications of various Ada
7581 usage on the efficiency of the generated code. There are many cases in
7582 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7583 generate a lot of run-time code. By using @option{-gnatG} you can identify
7584 these cases, and consider whether it may be desirable to modify the coding
7585 approach to improve efficiency.
7587 The optional parameter @code{nn} if present after -gnatG specifies an
7588 alternative maximum line length that overrides the normal default of 72.
7589 This value is in the range 40-999999, values less than 40 being silently
7590 reset to 40. The equal sign is optional.
7592 The format of the output is very similar to standard Ada source, and is
7593 easily understood by an Ada programmer. The following special syntactic
7594 additions correspond to low level features used in the generated code that
7595 do not have any exact analogies in pure Ada source form. The following
7596 is a partial list of these special constructions. See the spec
7597 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7599 If the switch @option{-gnatL} is used in conjunction with
7600 @cindex @option{-gnatL} (@command{gcc})
7601 @option{-gnatG}, then the original source lines are interspersed
7602 in the expanded source (as comment lines with the original line number).
7604 @table @code
7605 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7606 Shows the storage pool being used for an allocator.
7608 @item at end @var{procedure-name};
7609 Shows the finalization (cleanup) procedure for a scope.
7611 @item (if @var{expr} then @var{expr} else @var{expr})
7612 Conditional expression equivalent to the @code{x?y:z} construction in C.
7614 @item @var{target}^^^(@var{source})
7615 A conversion with floating-point truncation instead of rounding.
7617 @item @var{target}?(@var{source})
7618 A conversion that bypasses normal Ada semantic checking. In particular
7619 enumeration types and fixed-point types are treated simply as integers.
7621 @item @var{target}?^^^(@var{source})
7622 Combines the above two cases.
7624 @item @var{x} #/ @var{y}
7625 @itemx @var{x} #mod @var{y}
7626 @itemx @var{x} #* @var{y}
7627 @itemx @var{x} #rem @var{y}
7628 A division or multiplication of fixed-point values which are treated as
7629 integers without any kind of scaling.
7631 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7632 Shows the storage pool associated with a @code{free} statement.
7634 @item [subtype or type declaration]
7635 Used to list an equivalent declaration for an internally generated
7636 type that is referenced elsewhere in the listing.
7638 @c @item freeze @var{type-name} @ovar{actions}
7639 @c Expanding @ovar macro inline (explanation in macro def comments)
7640 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7641 Shows the point at which @var{type-name} is frozen, with possible
7642 associated actions to be performed at the freeze point.
7644 @item reference @var{itype}
7645 Reference (and hence definition) to internal type @var{itype}.
7647 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7648 Intrinsic function call.
7650 @item @var{label-name} : label
7651 Declaration of label @var{labelname}.
7653 @item #$ @var{subprogram-name}
7654 An implicit call to a run-time support routine
7655 (to meet the requirement of H.3.1(9) in a
7656 convenient manner).
7658 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7659 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7660 @var{expr}, but handled more efficiently).
7662 @item [constraint_error]
7663 Raise the @code{Constraint_Error} exception.
7665 @item @var{expression}'reference
7666 A pointer to the result of evaluating @var{expression}.
7668 @item @var{target-type}!(@var{source-expression})
7669 An unchecked conversion of @var{source-expression} to @var{target-type}.
7671 @item [@var{numerator}/@var{denominator}]
7672 Used to represent internal real literals (that) have no exact
7673 representation in base 2-16 (for example, the result of compile time
7674 evaluation of the expression 1.0/27.0).
7675 @end table
7677 @item -gnatD[=nn]
7678 @cindex @option{-gnatD} (@command{gcc})
7679 When used in conjunction with @option{-gnatG}, this switch causes
7680 the expanded source, as described above for
7681 @option{-gnatG} to be written to files with names
7682 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7683 instead of to the standard output file. For
7684 example, if the source file name is @file{hello.adb}, then a file
7685 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7686 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7687 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7688 you to do source level debugging using the generated code which is
7689 sometimes useful for complex code, for example to find out exactly
7690 which part of a complex construction raised an exception. This switch
7691 also suppress generation of cross-reference information (see
7692 @option{-gnatx}) since otherwise the cross-reference information
7693 would refer to the @file{^.dg^.DG^} file, which would cause
7694 confusion since this is not the original source file.
7696 Note that @option{-gnatD} actually implies @option{-gnatG}
7697 automatically, so it is not necessary to give both options.
7698 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7700 If the switch @option{-gnatL} is used in conjunction with
7701 @cindex @option{-gnatL} (@command{gcc})
7702 @option{-gnatDG}, then the original source lines are interspersed
7703 in the expanded source (as comment lines with the original line number).
7705 The optional parameter @code{nn} if present after -gnatD specifies an
7706 alternative maximum line length that overrides the normal default of 72.
7707 This value is in the range 40-999999, values less than 40 being silently
7708 reset to 40. The equal sign is optional.
7710 @item -gnatr
7711 @cindex @option{-gnatr} (@command{gcc})
7712 @cindex pragma Restrictions
7713 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7714 so that violation of restrictions causes warnings rather than illegalities.
7715 This is useful during the development process when new restrictions are added
7716 or investigated. The switch also causes pragma Profile to be treated as
7717 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7718 restriction warnings rather than restrictions.
7720 @ifclear vms
7721 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7722 @cindex @option{-gnatR} (@command{gcc})
7723 This switch controls output from the compiler of a listing showing
7724 representation information for declared types and objects. For
7725 @option{-gnatR0}, no information is output (equivalent to omitting
7726 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7727 so @option{-gnatR} with no parameter has the same effect), size and alignment
7728 information is listed for declared array and record types. For
7729 @option{-gnatR2}, size and alignment information is listed for all
7730 declared types and objects. Finally @option{-gnatR3} includes symbolic
7731 expressions for values that are computed at run time for
7732 variant records. These symbolic expressions have a mostly obvious
7733 format with #n being used to represent the value of the n'th
7734 discriminant. See source files @file{repinfo.ads/adb} in the
7735 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7736 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7737 the output is to a file with the name @file{^file.rep^file_REP^} where
7738 file is the name of the corresponding source file.
7739 @end ifclear
7740 @ifset vms
7741 @item /REPRESENTATION_INFO
7742 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7743 This qualifier controls output from the compiler of a listing showing
7744 representation information for declared types and objects. For
7745 @option{/REPRESENTATION_INFO=NONE}, no information is output
7746 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7747 @option{/REPRESENTATION_INFO} without option is equivalent to
7748 @option{/REPRESENTATION_INFO=ARRAYS}.
7749 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7750 information is listed for declared array and record types. For
7751 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7752 is listed for all expression information for values that are computed
7753 at run time for variant records. These symbolic expressions have a mostly
7754 obvious format with #n being used to represent the value of the n'th
7755 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7756 @code{GNAT} sources for full details on the format of
7757 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7758 If _FILE is added at the end of an option
7759 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7760 then the output is to a file with the name @file{file_REP} where
7761 file is the name of the corresponding source file.
7762 @end ifset
7763 Note that it is possible for record components to have zero size. In
7764 this case, the component clause uses an obvious extension of permitted
7765 Ada syntax, for example @code{at 0 range 0 .. -1}.
7767 Representation information requires that code be generated (since it is the
7768 code generator that lays out complex data structures). If an attempt is made
7769 to output representation information when no code is generated, for example
7770 when a subunit is compiled on its own, then no information can be generated
7771 and the compiler outputs a message to this effect.
7773 @item -gnatS
7774 @cindex @option{-gnatS} (@command{gcc})
7775 The use of the switch @option{-gnatS} for an
7776 Ada compilation will cause the compiler to output a
7777 representation of package Standard in a form very
7778 close to standard Ada. It is not quite possible to
7779 do this entirely in standard Ada (since new
7780 numeric base types cannot be created in standard
7781 Ada), but the output is easily
7782 readable to any Ada programmer, and is useful to
7783 determine the characteristics of target dependent
7784 types in package Standard.
7786 @item -gnatx
7787 @cindex @option{-gnatx} (@command{gcc})
7788 Normally the compiler generates full cross-referencing information in
7789 the @file{ALI} file. This information is used by a number of tools,
7790 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7791 suppresses this information. This saves some space and may slightly
7792 speed up compilation, but means that these tools cannot be used.
7793 @end table
7795 @node Exception Handling Control
7796 @subsection Exception Handling Control
7798 @noindent
7799 GNAT uses two methods for handling exceptions at run-time. The
7800 @code{setjmp/longjmp} method saves the context when entering
7801 a frame with an exception handler. Then when an exception is
7802 raised, the context can be restored immediately, without the
7803 need for tracing stack frames. This method provides very fast
7804 exception propagation, but introduces significant overhead for
7805 the use of exception handlers, even if no exception is raised.
7807 The other approach is called ``zero cost'' exception handling.
7808 With this method, the compiler builds static tables to describe
7809 the exception ranges. No dynamic code is required when entering
7810 a frame containing an exception handler. When an exception is
7811 raised, the tables are used to control a back trace of the
7812 subprogram invocation stack to locate the required exception
7813 handler. This method has considerably poorer performance for
7814 the propagation of exceptions, but there is no overhead for
7815 exception handlers if no exception is raised. Note that in this
7816 mode and in the context of mixed Ada and C/C++ programming,
7817 to propagate an exception through a C/C++ code, the C/C++ code
7818 must be compiled with the @option{-funwind-tables} GCC's
7819 option.
7821 The following switches may be used to control which of the
7822 two exception handling methods is used.
7824 @table @option
7825 @c !sort!
7827 @item --RTS=sjlj
7828 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7829 This switch causes the setjmp/longjmp run-time (when available) to be used
7830 for exception handling. If the default
7831 mechanism for the target is zero cost exceptions, then
7832 this switch can be used to modify this default, and must be
7833 used for all units in the partition.
7834 This option is rarely used. One case in which it may be
7835 advantageous is if you have an application where exception
7836 raising is common and the overall performance of the
7837 application is improved by favoring exception propagation.
7839 @item --RTS=zcx
7840 @cindex @option{--RTS=zcx} (@command{gnatmake})
7841 @cindex Zero Cost Exceptions
7842 This switch causes the zero cost approach to be used
7843 for exception handling. If this is the default mechanism for the
7844 target (see below), then this switch is unneeded. If the default
7845 mechanism for the target is setjmp/longjmp exceptions, then
7846 this switch can be used to modify this default, and must be
7847 used for all units in the partition.
7848 This option can only be used if the zero cost approach
7849 is available for the target in use, otherwise it will generate an error.
7850 @end table
7852 @noindent
7853 The same option @option{--RTS} must be used both for @command{gcc}
7854 and @command{gnatbind}. Passing this option to @command{gnatmake}
7855 (@pxref{Switches for gnatmake}) will ensure the required consistency
7856 through the compilation and binding steps.
7858 @node Units to Sources Mapping Files
7859 @subsection Units to Sources Mapping Files
7861 @table @option
7863 @item -gnatem=@var{path}
7864 @cindex @option{-gnatem} (@command{gcc})
7865 A mapping file is a way to communicate to the compiler two mappings:
7866 from unit names to file names (without any directory information) and from
7867 file names to path names (with full directory information). These mappings
7868 are used by the compiler to short-circuit the path search.
7870 The use of mapping files is not required for correct operation of the
7871 compiler, but mapping files can improve efficiency, particularly when
7872 sources are read over a slow network connection. In normal operation,
7873 you need not be concerned with the format or use of mapping files,
7874 and the @option{-gnatem} switch is not a switch that you would use
7875 explicitly. It is intended primarily for use by automatic tools such as
7876 @command{gnatmake} running under the project file facility. The
7877 description here of the format of mapping files is provided
7878 for completeness and for possible use by other tools.
7880 A mapping file is a sequence of sets of three lines. In each set, the
7881 first line is the unit name, in lower case, with @code{%s} appended
7882 for specs and @code{%b} appended for bodies; the second line is the
7883 file name; and the third line is the path name.
7885 Example:
7886 @smallexample
7887    main%b
7888    main.2.ada
7889    /gnat/project1/sources/main.2.ada
7890 @end smallexample
7892 When the switch @option{-gnatem} is specified, the compiler will
7893 create in memory the two mappings from the specified file. If there is
7894 any problem (nonexistent file, truncated file or duplicate entries),
7895 no mapping will be created.
7897 Several @option{-gnatem} switches may be specified; however, only the
7898 last one on the command line will be taken into account.
7900 When using a project file, @command{gnatmake} creates a temporary
7901 mapping file and communicates it to the compiler using this switch.
7903 @end table
7905 @node Integrated Preprocessing
7906 @subsection Integrated Preprocessing
7908 @noindent
7909 GNAT sources may be preprocessed immediately before compilation.
7910 In this case, the actual
7911 text of the source is not the text of the source file, but is derived from it
7912 through a process called preprocessing. Integrated preprocessing is specified
7913 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7914 indicates, through a text file, the preprocessing data to be used.
7915 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7917 @noindent
7918 Note that when integrated preprocessing is used, the output from the
7919 preprocessor is not written to any external file. Instead it is passed
7920 internally to the compiler. If you need to preserve the result of
7921 preprocessing in a file, then you should use @command{gnatprep}
7922 to perform the desired preprocessing in stand-alone mode.
7924 @noindent
7925 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7926 used when Integrated Preprocessing is used. The reason is that preprocessing
7927 with another Preprocessing Data file without changing the sources will
7928 not trigger recompilation without this switch.
7930 @noindent
7931 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7932 always trigger recompilation for sources that are preprocessed,
7933 because @command{gnatmake} cannot compute the checksum of the source after
7934 preprocessing.
7936 @noindent
7937 The actual preprocessing function is described in details in section
7938 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7939 preprocessing is triggered and parameterized.
7941 @table @code
7943 @item -gnatep=@var{file}
7944 @cindex @option{-gnatep} (@command{gcc})
7945 This switch indicates to the compiler the file name (without directory
7946 information) of the preprocessor data file to use. The preprocessor data file
7947 should be found in the source directories. Note that when the compiler is
7948 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7949 file, if the object directory is not also a source directory, the builder needs
7950 to be called with @option{-x}.
7952 @noindent
7953 A preprocessing data file is a text file with significant lines indicating
7954 how should be preprocessed either a specific source or all sources not
7955 mentioned in other lines. A significant line is a nonempty, non-comment line.
7956 Comments are similar to Ada comments.
7958 @noindent
7959 Each significant line starts with either a literal string or the character '*'.
7960 A literal string is the file name (without directory information) of the source
7961 to preprocess. A character '*' indicates the preprocessing for all the sources
7962 that are not specified explicitly on other lines (order of the lines is not
7963 significant). It is an error to have two lines with the same file name or two
7964 lines starting with the character '*'.
7966 @noindent
7967 After the file name or the character '*', another optional literal string
7968 indicating the file name of the definition file to be used for preprocessing
7969 (@pxref{Form of Definitions File}). The definition files are found by the
7970 compiler in one of the source directories. In some cases, when compiling
7971 a source in a directory other than the current directory, if the definition
7972 file is in the current directory, it may be necessary to add the current
7973 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7974 the compiler would not find the definition file.
7976 @noindent
7977 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7978 be found. Those ^switches^switches^ are:
7980 @table @code
7982 @item -b
7983 Causes both preprocessor lines and the lines deleted by
7984 preprocessing to be replaced by blank lines, preserving the line number.
7985 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7986 it cancels the effect of @option{-c}.
7988 @item -c
7989 Causes both preprocessor lines and the lines deleted
7990 by preprocessing to be retained as comments marked
7991 with the special string ``@code{--! }''.
7993 @item -Dsymbol=value
7994 Define or redefine a symbol, associated with value. A symbol is an Ada
7995 identifier, or an Ada reserved word, with the exception of @code{if},
7996 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7997 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7998 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7999 same name defined in a definition file.
8001 @item -s
8002 Causes a sorted list of symbol names and values to be
8003 listed on the standard output file.
8005 @item -u
8006 Causes undefined symbols to be treated as having the value @code{FALSE}
8007 in the context
8008 of a preprocessor test. In the absence of this option, an undefined symbol in
8009 a @code{#if} or @code{#elsif} test will be treated as an error.
8011 @end table
8013 @noindent
8014 Examples of valid lines in a preprocessor data file:
8016 @smallexample
8017   "toto.adb"  "prep.def" -u
8018   --  preprocess "toto.adb", using definition file "prep.def",
8019   --  undefined symbol are False.
8021   * -c -DVERSION=V101
8022   --  preprocess all other sources without a definition file;
8023   --  suppressed lined are commented; symbol VERSION has the value V101.
8025   "titi.adb" "prep2.def" -s
8026   --  preprocess "titi.adb", using definition file "prep2.def";
8027   --  list all symbols with their values.
8028 @end smallexample
8030 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
8031 @cindex @option{-gnateD} (@command{gcc})
8032 Define or redefine a preprocessing symbol, associated with value. If no value
8033 is given on the command line, then the value of the symbol is @code{True}.
8034 A symbol is an identifier, following normal Ada (case-insensitive)
8035 rules for its syntax, and value is any sequence (including an empty sequence)
8036 of characters from the set (letters, digits, period, underline).
8037 Ada reserved words may be used as symbols, with the exceptions of @code{if},
8038 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
8040 @noindent
8041 A symbol declared with this ^switch^switch^ on the command line replaces a
8042 symbol with the same name either in a definition file or specified with a
8043 ^switch^switch^ -D in the preprocessor data file.
8045 @noindent
8046 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
8048 @item -gnateG
8049 When integrated preprocessing is performed and the preprocessor modifies
8050 the source text, write the result of this preprocessing into a file
8051 <source>^.prep^_prep^.
8053 @end table
8055 @node Code Generation Control
8056 @subsection Code Generation Control
8058 @noindent
8060 The GCC technology provides a wide range of target dependent
8061 @option{-m} switches for controlling
8062 details of code generation with respect to different versions of
8063 architectures. This includes variations in instruction sets (e.g.@:
8064 different members of the power pc family), and different requirements
8065 for optimal arrangement of instructions (e.g.@: different members of
8066 the x86 family). The list of available @option{-m} switches may be
8067 found in the GCC documentation.
8069 Use of these @option{-m} switches may in some cases result in improved
8070 code performance.
8072 The @value{EDITION} technology is tested and qualified without any
8073 @option{-m} switches,
8074 so generally the most reliable approach is to avoid the use of these
8075 switches. However, we generally expect most of these switches to work
8076 successfully with @value{EDITION}, and many customers have reported successful
8077 use of these options.
8079 Our general advice is to avoid the use of @option{-m} switches unless
8080 special needs lead to requirements in this area. In particular,
8081 there is no point in using @option{-m} switches to improve performance
8082 unless you actually see a performance improvement.
8084 @ifset vms
8085 @node Return Codes
8086 @subsection Return Codes
8087 @cindex Return Codes
8088 @cindex @option{/RETURN_CODES=VMS}
8090 @noindent
8091 On VMS, GNAT compiled programs return POSIX-style codes by default,
8092 e.g.@: @option{/RETURN_CODES=POSIX}.
8094 To enable VMS style return codes, use GNAT BIND and LINK with the option
8095 @option{/RETURN_CODES=VMS}. For example:
8097 @smallexample
8098 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
8099 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
8100 @end smallexample
8102 @noindent
8103 Programs built with /RETURN_CODES=VMS are suitable to be called in
8104 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
8105 are suitable for spawning with appropriate GNAT RTL routines.
8107 @end ifset
8109 @node Search Paths and the Run-Time Library (RTL)
8110 @section Search Paths and the Run-Time Library (RTL)
8112 @noindent
8113 With the GNAT source-based library system, the compiler must be able to
8114 find source files for units that are needed by the unit being compiled.
8115 Search paths are used to guide this process.
8117 The compiler compiles one source file whose name must be given
8118 explicitly on the command line. In other words, no searching is done
8119 for this file. To find all other source files that are needed (the most
8120 common being the specs of units), the compiler examines the following
8121 directories, in the following order:
8123 @enumerate
8124 @item
8125 The directory containing the source file of the main unit being compiled
8126 (the file name on the command line).
8128 @item
8129 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
8130 @command{gcc} command line, in the order given.
8132 @item
8133 @findex ADA_PRJ_INCLUDE_FILE
8134 Each of the directories listed in the text file whose name is given
8135 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
8137 @noindent
8138 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8139 driver when project files are used. It should not normally be set
8140 by other means.
8142 @item
8143 @findex ADA_INCLUDE_PATH
8144 Each of the directories listed in the value of the
8145 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
8146 @ifclear vms
8147 Construct this value
8148 exactly as the @env{PATH} environment variable: a list of directory
8149 names separated by colons (semicolons when working with the NT version).
8150 @end ifclear
8151 @ifset vms
8152 Normally, define this value as a logical name containing a comma separated
8153 list of directory names.
8155 This variable can also be defined by means of an environment string
8156 (an argument to the HP C exec* set of functions).
8158 Logical Name:
8159 @smallexample
8160 DEFINE ANOTHER_PATH FOO:[BAG]
8161 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8162 @end smallexample
8164 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8165 first, followed by the standard Ada
8166 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
8167 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8168 (Text_IO, Sequential_IO, etc)
8169 instead of the standard Ada packages. Thus, in order to get the standard Ada
8170 packages by default, ADA_INCLUDE_PATH must be redefined.
8171 @end ifset
8173 @item
8174 The content of the @file{ada_source_path} file which is part of the GNAT
8175 installation tree and is used to store standard libraries such as the
8176 GNAT Run Time Library (RTL) source files.
8177 @ifclear vms
8178 @ref{Installing a library}
8179 @end ifclear
8180 @end enumerate
8182 @noindent
8183 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
8184 inhibits the use of the directory
8185 containing the source file named in the command line. You can still
8186 have this directory on your search path, but in this case it must be
8187 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8189 Specifying the switch @option{-nostdinc}
8190 inhibits the search of the default location for the GNAT Run Time
8191 Library (RTL) source files.
8193 The compiler outputs its object files and ALI files in the current
8194 working directory.
8195 @ifclear vms
8196 Caution: The object file can be redirected with the @option{-o} switch;
8197 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8198 so the @file{ALI} file will not go to the right place. Therefore, you should
8199 avoid using the @option{-o} switch.
8200 @end ifclear
8202 @findex System.IO
8203 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8204 children make up the GNAT RTL, together with the simple @code{System.IO}
8205 package used in the @code{"Hello World"} example. The sources for these units
8206 are needed by the compiler and are kept together in one directory. Not
8207 all of the bodies are needed, but all of the sources are kept together
8208 anyway. In a normal installation, you need not specify these directory
8209 names when compiling or binding. Either the environment variables or
8210 the built-in defaults cause these files to be found.
8212 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8213 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8214 consisting of child units of @code{GNAT}. This is a collection of generally
8215 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8216 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8218 Besides simplifying access to the RTL, a major use of search paths is
8219 in compiling sources from multiple directories. This can make
8220 development environments much more flexible.
8222 @node Order of Compilation Issues
8223 @section Order of Compilation Issues
8225 @noindent
8226 If, in our earlier example, there was a spec for the @code{hello}
8227 procedure, it would be contained in the file @file{hello.ads}; yet this
8228 file would not have to be explicitly compiled. This is the result of the
8229 model we chose to implement library management. Some of the consequences
8230 of this model are as follows:
8232 @itemize @bullet
8233 @item
8234 There is no point in compiling specs (except for package
8235 specs with no bodies) because these are compiled as needed by clients. If
8236 you attempt a useless compilation, you will receive an error message.
8237 It is also useless to compile subunits because they are compiled as needed
8238 by the parent.
8240 @item
8241 There are no order of compilation requirements: performing a
8242 compilation never obsoletes anything. The only way you can obsolete
8243 something and require recompilations is to modify one of the
8244 source files on which it depends.
8246 @item
8247 There is no library as such, apart from the ALI files
8248 (@pxref{The Ada Library Information Files}, for information on the format
8249 of these files). For now we find it convenient to create separate ALI files,
8250 but eventually the information therein may be incorporated into the object
8251 file directly.
8253 @item
8254 When you compile a unit, the source files for the specs of all units
8255 that it @code{with}'s, all its subunits, and the bodies of any generics it
8256 instantiates must be available (reachable by the search-paths mechanism
8257 described above), or you will receive a fatal error message.
8258 @end itemize
8260 @node Examples
8261 @section Examples
8263 @noindent
8264 The following are some typical Ada compilation command line examples:
8266 @table @code
8267 @item $ gcc -c xyz.adb
8268 Compile body in file @file{xyz.adb} with all default options.
8270 @ifclear vms
8271 @item $ gcc -c -O2 -gnata xyz-def.adb
8272 @end ifclear
8273 @ifset vms
8274 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8275 @end ifset
8277 Compile the child unit package in file @file{xyz-def.adb} with extensive
8278 optimizations, and pragma @code{Assert}/@code{Debug} statements
8279 enabled.
8281 @item $ gcc -c -gnatc abc-def.adb
8282 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8283 mode.
8284 @end table
8286 @node Binding Using gnatbind
8287 @chapter Binding Using @code{gnatbind}
8288 @findex gnatbind
8290 @menu
8291 * Running gnatbind::
8292 * Switches for gnatbind::
8293 * Command-Line Access::
8294 * Search Paths for gnatbind::
8295 * Examples of gnatbind Usage::
8296 @end menu
8298 @noindent
8299 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8300 to bind compiled GNAT objects.
8302 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8303 driver (see @ref{The GNAT Driver and Project Files}).
8305 The @code{gnatbind} program performs four separate functions:
8307 @enumerate
8308 @item
8309 Checks that a program is consistent, in accordance with the rules in
8310 Chapter 10 of the Ada Reference Manual. In particular, error
8311 messages are generated if a program uses inconsistent versions of a
8312 given unit.
8314 @item
8315 Checks that an acceptable order of elaboration exists for the program
8316 and issues an error message if it cannot find an order of elaboration
8317 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8319 @item
8320 Generates a main program incorporating the given elaboration order.
8321 This program is a small Ada package (body and spec) that
8322 must be subsequently compiled
8323 using the GNAT compiler. The necessary compilation step is usually
8324 performed automatically by @command{gnatlink}. The two most important
8325 functions of this program
8326 are to call the elaboration routines of units in an appropriate order
8327 and to call the main program.
8329 @item
8330 Determines the set of object files required by the given main program.
8331 This information is output in the forms of comments in the generated program,
8332 to be read by the @command{gnatlink} utility used to link the Ada application.
8333 @end enumerate
8335 @node Running gnatbind
8336 @section Running @code{gnatbind}
8338 @noindent
8339 The form of the @code{gnatbind} command is
8341 @smallexample
8342 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8343 @c Expanding @ovar macro inline (explanation in macro def comments)
8344 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8345 @end smallexample
8347 @noindent
8348 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8349 unit body. @code{gnatbind} constructs an Ada
8350 package in two files whose names are
8351 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8352 For example, if given the
8353 parameter @file{hello.ali}, for a main program contained in file
8354 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8355 and @file{b~hello.adb}.
8357 When doing consistency checking, the binder takes into consideration
8358 any source files it can locate. For example, if the binder determines
8359 that the given main program requires the package @code{Pack}, whose
8360 @file{.ALI}
8361 file is @file{pack.ali} and whose corresponding source spec file is
8362 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8363 (using the same search path conventions as previously described for the
8364 @command{gcc} command). If it can locate this source file, it checks that
8365 the time stamps
8366 or source checksums of the source and its references to in @file{ALI} files
8367 match. In other words, any @file{ALI} files that mentions this spec must have
8368 resulted from compiling this version of the source file (or in the case
8369 where the source checksums match, a version close enough that the
8370 difference does not matter).
8372 @cindex Source files, use by binder
8373 The effect of this consistency checking, which includes source files, is
8374 that the binder ensures that the program is consistent with the latest
8375 version of the source files that can be located at bind time. Editing a
8376 source file without compiling files that depend on the source file cause
8377 error messages to be generated by the binder.
8379 For example, suppose you have a main program @file{hello.adb} and a
8380 package @code{P}, from file @file{p.ads} and you perform the following
8381 steps:
8383 @enumerate
8384 @item
8385 Enter @code{gcc -c hello.adb} to compile the main program.
8387 @item
8388 Enter @code{gcc -c p.ads} to compile package @code{P}.
8390 @item
8391 Edit file @file{p.ads}.
8393 @item
8394 Enter @code{gnatbind hello}.
8395 @end enumerate
8397 @noindent
8398 At this point, the file @file{p.ali} contains an out-of-date time stamp
8399 because the file @file{p.ads} has been edited. The attempt at binding
8400 fails, and the binder generates the following error messages:
8402 @smallexample
8403 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8404 error: "p.ads" has been modified and must be recompiled
8405 @end smallexample
8407 @noindent
8408 Now both files must be recompiled as indicated, and then the bind can
8409 succeed, generating a main program. You need not normally be concerned
8410 with the contents of this file, but for reference purposes a sample
8411 binder output file is given in @ref{Example of Binder Output File}.
8413 In most normal usage, the default mode of @command{gnatbind} which is to
8414 generate the main package in Ada, as described in the previous section.
8415 In particular, this means that any Ada programmer can read and understand
8416 the generated main program. It can also be debugged just like any other
8417 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8418 @command{gnatbind} and @command{gnatlink}.
8420 @node Switches for gnatbind
8421 @section Switches for @command{gnatbind}
8423 @noindent
8424 The following switches are available with @code{gnatbind}; details will
8425 be presented in subsequent sections.
8427 @menu
8428 * Consistency-Checking Modes::
8429 * Binder Error Message Control::
8430 * Elaboration Control::
8431 * Output Control::
8432 * Dynamic Allocation Control::
8433 * Binding with Non-Ada Main Programs::
8434 * Binding Programs with No Main Subprogram::
8435 @end menu
8437 @table @option
8438 @c !sort!
8440 @item --version
8441 @cindex @option{--version} @command{gnatbind}
8442 Display Copyright and version, then exit disregarding all other options.
8444 @item --help
8445 @cindex @option{--help} @command{gnatbind}
8446 If @option{--version} was not used, display usage, then exit disregarding
8447 all other options.
8449 @item -a
8450 @cindex @option{-a} @command{gnatbind}
8451 Indicates that, if supported by the platform, the adainit procedure should
8452 be treated as an initialisation routine by the linker (a constructor). This
8453 is intended to be used by the Project Manager to automatically initialize
8454 shared Stand-Alone Libraries.
8456 @item ^-aO^/OBJECT_SEARCH^
8457 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8458 Specify directory to be searched for ALI files.
8460 @item ^-aI^/SOURCE_SEARCH^
8461 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8462 Specify directory to be searched for source file.
8464 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8465 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8466 Output ALI list (to standard output or to the named file).
8468 @item ^-b^/REPORT_ERRORS=BRIEF^
8469 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8470 Generate brief messages to @file{stderr} even if verbose mode set.
8472 @item ^-c^/NOOUTPUT^
8473 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8474 Check only, no generation of binder output file.
8476 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8477 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8478 This switch can be used to change the default task stack size value
8479 to a specified size @var{nn}, which is expressed in bytes by default, or
8480 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8481 with @var{m}.
8482 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8483 in effect, to completing all task specs with
8484 @smallexample @c ada
8485    pragma Storage_Size (nn);
8486 @end smallexample
8487 When they do not already have such a pragma.
8489 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8490 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8491 This switch can be used to change the default secondary stack size value
8492 to a specified size @var{nn}, which is expressed in bytes by default, or
8493 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8494 with @var{m}.
8496 The secondary stack is used to deal with functions that return a variable
8497 sized result, for example a function returning an unconstrained
8498 String. There are two ways in which this secondary stack is allocated.
8500 For most targets, the secondary stack is growing on demand and is allocated
8501 as a chain of blocks in the heap. The -D option is not very
8502 relevant. It only give some control over the size of the allocated
8503 blocks (whose size is the minimum of the default secondary stack size value,
8504 and the actual size needed for the current allocation request).
8506 For certain targets, notably VxWorks 653,
8507 the secondary stack is allocated by carving off a fixed ratio chunk of the
8508 primary task stack. The -D option is used to define the
8509 size of the environment task's secondary stack.
8511 @item ^-e^/ELABORATION_DEPENDENCIES^
8512 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8513 Output complete list of elaboration-order dependencies.
8515 @item ^-E^/STORE_TRACEBACKS^
8516 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8517 Store tracebacks in exception occurrences when the target supports it.
8518 @ignore
8519 @c The following may get moved to an appendix
8520 This option is currently supported on the following targets:
8521 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8522 @end ignore
8523 See also the packages @code{GNAT.Traceback} and
8524 @code{GNAT.Traceback.Symbolic} for more information.
8525 @ifclear vms
8526 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8527 @command{gcc} option.
8528 @end ifclear
8530 @item ^-F^/FORCE_ELABS_FLAGS^
8531 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8532 Force the checks of elaboration flags. @command{gnatbind} does not normally
8533 generate checks of elaboration flags for the main executable, except when
8534 a Stand-Alone Library is used. However, there are cases when this cannot be
8535 detected by gnatbind. An example is importing an interface of a Stand-Alone
8536 Library through a pragma Import and only specifying through a linker switch
8537 this Stand-Alone Library. This switch is used to guarantee that elaboration
8538 flag checks are generated.
8540 @item ^-h^/HELP^
8541 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8542 Output usage (help) information
8544 @item ^-H32^/32_MALLOC^
8545 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8546 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8547 For further details see @ref{Dynamic Allocation Control}.
8549 @item ^-H64^/64_MALLOC^
8550 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8551 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8552 @cindex @code{__gnat_malloc}
8553 For further details see @ref{Dynamic Allocation Control}.
8555 @item ^-I^/SEARCH^
8556 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8557 Specify directory to be searched for source and ALI files.
8559 @item ^-I-^/NOCURRENT_DIRECTORY^
8560 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8561 Do not look for sources in the current directory where @code{gnatbind} was
8562 invoked, and do not look for ALI files in the directory containing the
8563 ALI file named in the @code{gnatbind} command line.
8565 @item ^-l^/ORDER_OF_ELABORATION^
8566 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8567 Output chosen elaboration order.
8569 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8570 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8571 Bind the units for library building. In this case the adainit and
8572 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8573 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8574 ^@var{xxx}final^@var{XXX}FINAL^.
8575 Implies ^-n^/NOCOMPILE^.
8576 @ifclear vms
8577 (@xref{GNAT and Libraries}, for more details.)
8578 @end ifclear
8579 @ifset vms
8580 On OpenVMS, these init and final procedures are exported in uppercase
8581 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8582 the init procedure will be "TOTOINIT" and the exported name of the final
8583 procedure will be "TOTOFINAL".
8584 @end ifset
8586 @item ^-Mxyz^/RENAME_MAIN=xyz^
8587 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8588 Rename generated main program from main to xyz. This option is
8589 supported on cross environments only.
8591 @item ^-m^/ERROR_LIMIT=^@var{n}
8592 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8593 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8594 in the range 1..999999. The default value if no switch is
8595 given is 9999. If the number of warnings reaches this limit, then a
8596 message is output and further warnings are suppressed, the bind
8597 continues in this case. If the number of errors reaches this
8598 limit, then a message is output and the bind is abandoned.
8599 A value of zero means that no limit is enforced. The equal
8600 sign is optional.
8602 @ifset unw
8603 Furthermore, under Windows, the sources pointed to by the libraries path
8604 set in the registry are not searched for.
8605 @end ifset
8607 @item ^-n^/NOMAIN^
8608 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8609 No main program.
8611 @item -nostdinc
8612 @cindex @option{-nostdinc} (@command{gnatbind})
8613 Do not look for sources in the system default directory.
8615 @item -nostdlib
8616 @cindex @option{-nostdlib} (@command{gnatbind})
8617 Do not look for library files in the system default directory.
8619 @item --RTS=@var{rts-path}
8620 @cindex @option{--RTS} (@code{gnatbind})
8621 Specifies the default location of the runtime library. Same meaning as the
8622 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8624 @item ^-o ^/OUTPUT=^@var{file}
8625 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8626 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8627 Note that if this option is used, then linking must be done manually,
8628 gnatlink cannot be used.
8630 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8631 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8632 Output object list (to standard output or to the named file).
8634 @item ^-p^/PESSIMISTIC_ELABORATION^
8635 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8636 Pessimistic (worst-case) elaboration order
8638 @item ^-P^-P^
8639 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8640 Generate binder file suitable for CodePeer.
8642 @item ^-R^-R^
8643 @cindex @option{^-R^-R^} (@command{gnatbind})
8644 Output closure source list.
8646 @item ^-s^/READ_SOURCES=ALL^
8647 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8648 Require all source files to be present.
8650 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8651 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8652 Specifies the value to be used when detecting uninitialized scalar
8653 objects with pragma Initialize_Scalars.
8654 The @var{xxx} ^string specified with the switch^option^ may be either
8655 @itemize @bullet
8656 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8657 @item ``@option{^lo^LOW^}'' for the lowest possible value
8658 @item ``@option{^hi^HIGH^}'' for the highest possible value
8659 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8660 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8661 @end itemize
8663 In addition, you can specify @option{-Sev} to indicate that the value is
8664 to be set at run time. In this case, the program will look for an environment
8665 @cindex GNAT_INIT_SCALARS
8666 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8667 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8668 If no environment variable is found, or if it does not have a valid value,
8669 then the default is @option{in} (invalid values).
8671 @ifclear vms
8672 @item -static
8673 @cindex @option{-static} (@code{gnatbind})
8674 Link against a static GNAT run time.
8676 @item -shared
8677 @cindex @option{-shared} (@code{gnatbind})
8678 Link against a shared GNAT run time when available.
8679 @end ifclear
8681 @item ^-t^/NOTIME_STAMP_CHECK^
8682 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8683 Tolerate time stamp and other consistency errors
8685 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8686 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8687 Set the time slice value to @var{n} milliseconds. If the system supports
8688 the specification of a specific time slice value, then the indicated value
8689 is used. If the system does not support specific time slice values, but
8690 does support some general notion of round-robin scheduling, then any
8691 nonzero value will activate round-robin scheduling.
8693 A value of zero is treated specially. It turns off time
8694 slicing, and in addition, indicates to the tasking run time that the
8695 semantics should match as closely as possible the Annex D
8696 requirements of the Ada RM, and in particular sets the default
8697 scheduling policy to @code{FIFO_Within_Priorities}.
8699 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8700 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8701 Enable dynamic stack usage, with @var{n} results stored and displayed
8702 at program termination. A result is generated when a task
8703 terminates. Results that can't be stored are displayed on the fly, at
8704 task termination. This option is currently not supported on Itanium
8705 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8707 @item ^-v^/REPORT_ERRORS=VERBOSE^
8708 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8709 Verbose mode. Write error messages, header, summary output to
8710 @file{stdout}.
8712 @ifclear vms
8713 @item -w@var{x}
8714 @cindex @option{-w} (@code{gnatbind})
8715 Warning mode (@var{x}=s/e for suppress/treat as error)
8716 @end ifclear
8718 @ifset vms
8719 @item /WARNINGS=NORMAL
8720 @cindex @option{/WARNINGS} (@code{gnatbind})
8721 Normal warnings mode. Warnings are issued but ignored
8723 @item /WARNINGS=SUPPRESS
8724 @cindex @option{/WARNINGS} (@code{gnatbind})
8725 All warning messages are suppressed
8727 @item /WARNINGS=ERROR
8728 @cindex @option{/WARNINGS} (@code{gnatbind})
8729 Warning messages are treated as fatal errors
8730 @end ifset
8732 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8733 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8734 Override default wide character encoding for standard Text_IO files.
8736 @item ^-x^/READ_SOURCES=NONE^
8737 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8738 Exclude source files (check object consistency only).
8740 @ifset vms
8741 @item /READ_SOURCES=AVAILABLE
8742 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8743 Default mode, in which sources are checked for consistency only if
8744 they are available.
8745 @end ifset
8747 @item ^-y^/ENABLE_LEAP_SECONDS^
8748 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8749 Enable leap seconds support in @code{Ada.Calendar} and its children.
8751 @item ^-z^/ZERO_MAIN^
8752 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8753 No main subprogram.
8754 @end table
8756 @ifclear vms
8757 @noindent
8758 You may obtain this listing of switches by running @code{gnatbind} with
8759 no arguments.
8760 @end ifclear
8762 @node Consistency-Checking Modes
8763 @subsection Consistency-Checking Modes
8765 @noindent
8766 As described earlier, by default @code{gnatbind} checks
8767 that object files are consistent with one another and are consistent
8768 with any source files it can locate. The following switches control binder
8769 access to sources.
8771 @table @option
8772 @c !sort!
8773 @item ^-s^/READ_SOURCES=ALL^
8774 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8775 Require source files to be present. In this mode, the binder must be
8776 able to locate all source files that are referenced, in order to check
8777 their consistency. In normal mode, if a source file cannot be located it
8778 is simply ignored. If you specify this switch, a missing source
8779 file is an error.
8781 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8782 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8783 Override default wide character encoding for standard Text_IO files.
8784 Normally the default wide character encoding method used for standard
8785 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8786 the main source input (see description of switch
8787 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8788 use of this switch for the binder (which has the same set of
8789 possible arguments) overrides this default as specified.
8791 @item ^-x^/READ_SOURCES=NONE^
8792 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8793 Exclude source files. In this mode, the binder only checks that ALI
8794 files are consistent with one another. Source files are not accessed.
8795 The binder runs faster in this mode, and there is still a guarantee that
8796 the resulting program is self-consistent.
8797 If a source file has been edited since it was last compiled, and you
8798 specify this switch, the binder will not detect that the object
8799 file is out of date with respect to the source file. Note that this is the
8800 mode that is automatically used by @command{gnatmake} because in this
8801 case the checking against sources has already been performed by
8802 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8804 @ifset vms
8805 @item /READ_SOURCES=AVAILABLE
8806 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8807 This is the default mode in which source files are checked if they are
8808 available, and ignored if they are not available.
8809 @end ifset
8810 @end table
8812 @node Binder Error Message Control
8813 @subsection Binder Error Message Control
8815 @noindent
8816 The following switches provide control over the generation of error
8817 messages from the binder:
8819 @table @option
8820 @c !sort!
8821 @item ^-v^/REPORT_ERRORS=VERBOSE^
8822 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8823 Verbose mode. In the normal mode, brief error messages are generated to
8824 @file{stderr}. If this switch is present, a header is written
8825 to @file{stdout} and any error messages are directed to @file{stdout}.
8826 All that is written to @file{stderr} is a brief summary message.
8828 @item ^-b^/REPORT_ERRORS=BRIEF^
8829 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8830 Generate brief error messages to @file{stderr} even if verbose mode is
8831 specified. This is relevant only when used with the
8832 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8834 @ifclear vms
8835 @item -m@var{n}
8836 @cindex @option{-m} (@code{gnatbind})
8837 Limits the number of error messages to @var{n}, a decimal integer in the
8838 range 1-999. The binder terminates immediately if this limit is reached.
8840 @item -M@var{xxx}
8841 @cindex @option{-M} (@code{gnatbind})
8842 Renames the generated main program from @code{main} to @code{xxx}.
8843 This is useful in the case of some cross-building environments, where
8844 the actual main program is separate from the one generated
8845 by @code{gnatbind}.
8846 @end ifclear
8848 @item ^-ws^/WARNINGS=SUPPRESS^
8849 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8850 @cindex Warnings
8851 Suppress all warning messages.
8853 @item ^-we^/WARNINGS=ERROR^
8854 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8855 Treat any warning messages as fatal errors.
8857 @ifset vms
8858 @item /WARNINGS=NORMAL
8859 Standard mode with warnings generated, but warnings do not get treated
8860 as errors.
8861 @end ifset
8863 @item ^-t^/NOTIME_STAMP_CHECK^
8864 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8865 @cindex Time stamp checks, in binder
8866 @cindex Binder consistency checks
8867 @cindex Consistency checks, in binder
8868 The binder performs a number of consistency checks including:
8870 @itemize @bullet
8871 @item
8872 Check that time stamps of a given source unit are consistent
8873 @item
8874 Check that checksums of a given source unit are consistent
8875 @item
8876 Check that consistent versions of @code{GNAT} were used for compilation
8877 @item
8878 Check consistency of configuration pragmas as required
8879 @end itemize
8881 @noindent
8882 Normally failure of such checks, in accordance with the consistency
8883 requirements of the Ada Reference Manual, causes error messages to be
8884 generated which abort the binder and prevent the output of a binder
8885 file and subsequent link to obtain an executable.
8887 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8888 into warnings, so that
8889 binding and linking can continue to completion even in the presence of such
8890 errors. The result may be a failed link (due to missing symbols), or a
8891 non-functional executable which has undefined semantics.
8892 @emph{This means that
8893 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8894 with extreme care.}
8895 @end table
8897 @node Elaboration Control
8898 @subsection Elaboration Control
8900 @noindent
8901 The following switches provide additional control over the elaboration
8902 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8904 @table @option
8905 @item ^-p^/PESSIMISTIC_ELABORATION^
8906 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8907 Normally the binder attempts to choose an elaboration order that is
8908 likely to minimize the likelihood of an elaboration order error resulting
8909 in raising a @code{Program_Error} exception. This switch reverses the
8910 action of the binder, and requests that it deliberately choose an order
8911 that is likely to maximize the likelihood of an elaboration error.
8912 This is useful in ensuring portability and avoiding dependence on
8913 accidental fortuitous elaboration ordering.
8915 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8916 switch if dynamic
8917 elaboration checking is used (@option{-gnatE} switch used for compilation).
8918 This is because in the default static elaboration mode, all necessary
8919 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8920 These implicit pragmas are still respected by the binder in
8921 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8922 safe elaboration order is assured.
8924 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8925 production use; it is more for debugging/experimental use.
8926 @end table
8928 @node Output Control
8929 @subsection Output Control
8931 @noindent
8932 The following switches allow additional control over the output
8933 generated by the binder.
8935 @table @option
8936 @c !sort!
8938 @item ^-c^/NOOUTPUT^
8939 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8940 Check only. Do not generate the binder output file. In this mode the
8941 binder performs all error checks but does not generate an output file.
8943 @item ^-e^/ELABORATION_DEPENDENCIES^
8944 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8945 Output complete list of elaboration-order dependencies, showing the
8946 reason for each dependency. This output can be rather extensive but may
8947 be useful in diagnosing problems with elaboration order. The output is
8948 written to @file{stdout}.
8950 @item ^-h^/HELP^
8951 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8952 Output usage information. The output is written to @file{stdout}.
8954 @item ^-K^/LINKER_OPTION_LIST^
8955 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8956 Output linker options to @file{stdout}. Includes library search paths,
8957 contents of pragmas Ident and Linker_Options, and libraries added
8958 by @code{gnatbind}.
8960 @item ^-l^/ORDER_OF_ELABORATION^
8961 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8962 Output chosen elaboration order. The output is written to @file{stdout}.
8964 @item ^-O^/OBJECT_LIST^
8965 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8966 Output full names of all the object files that must be linked to provide
8967 the Ada component of the program. The output is written to @file{stdout}.
8968 This list includes the files explicitly supplied and referenced by the user
8969 as well as implicitly referenced run-time unit files. The latter are
8970 omitted if the corresponding units reside in shared libraries. The
8971 directory names for the run-time units depend on the system configuration.
8973 @item ^-o ^/OUTPUT=^@var{file}
8974 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8975 Set name of output file to @var{file} instead of the normal
8976 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8977 binder generated body filename.
8978 Note that if this option is used, then linking must be done manually.
8979 It is not possible to use gnatlink in this case, since it cannot locate
8980 the binder file.
8982 @item ^-r^/RESTRICTION_LIST^
8983 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8984 Generate list of @code{pragma Restrictions} that could be applied to
8985 the current unit. This is useful for code audit purposes, and also may
8986 be used to improve code generation in some cases.
8988 @end table
8990 @node Dynamic Allocation Control
8991 @subsection Dynamic Allocation Control
8993 @noindent
8994 The heap control switches -- @option{-H32} and @option{-H64} --
8995 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8996 They only affect compiler-generated allocations via @code{__gnat_malloc};
8997 explicit calls to @code{malloc} and related functions from the C
8998 run-time library are unaffected.
9000 @table @option
9001 @item -H32
9002 Allocate memory on 32-bit heap
9004 @item -H64
9005 Allocate memory on 64-bit heap.  This is the default
9006 unless explicitly overridden by a @code{'Size} clause on the access type.
9007 @end table
9009 @ifset vms
9010 @noindent
9011 See also @ref{Access types and 32/64-bit allocation}.
9012 @end ifset
9013 @ifclear vms
9014 @noindent
9015 These switches are only effective on VMS platforms.
9016 @end ifclear
9019 @node Binding with Non-Ada Main Programs
9020 @subsection Binding with Non-Ada Main Programs
9022 @noindent
9023 In our description so far we have assumed that the main
9024 program is in Ada, and that the task of the binder is to generate a
9025 corresponding function @code{main} that invokes this Ada main
9026 program. GNAT also supports the building of executable programs where
9027 the main program is not in Ada, but some of the called routines are
9028 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
9029 The following switch is used in this situation:
9031 @table @option
9032 @item ^-n^/NOMAIN^
9033 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
9034 No main program. The main program is not in Ada.
9035 @end table
9037 @noindent
9038 In this case, most of the functions of the binder are still required,
9039 but instead of generating a main program, the binder generates a file
9040 containing the following callable routines:
9042 @table @code
9043 @item adainit
9044 @findex adainit
9045 You must call this routine to initialize the Ada part of the program by
9046 calling the necessary elaboration routines. A call to @code{adainit} is
9047 required before the first call to an Ada subprogram.
9049 Note that it is assumed that the basic execution environment must be setup
9050 to be appropriate for Ada execution at the point where the first Ada
9051 subprogram is called. In particular, if the Ada code will do any
9052 floating-point operations, then the FPU must be setup in an appropriate
9053 manner. For the case of the x86, for example, full precision mode is
9054 required. The procedure GNAT.Float_Control.Reset may be used to ensure
9055 that the FPU is in the right state.
9057 @item adafinal
9058 @findex adafinal
9059 You must call this routine to perform any library-level finalization
9060 required by the Ada subprograms. A call to @code{adafinal} is required
9061 after the last call to an Ada subprogram, and before the program
9062 terminates.
9063 @end table
9065 @noindent
9066 If the @option{^-n^/NOMAIN^} switch
9067 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
9068 @cindex Binder, multiple input files
9069 is given, more than one ALI file may appear on
9070 the command line for @code{gnatbind}. The normal @dfn{closure}
9071 calculation is performed for each of the specified units. Calculating
9072 the closure means finding out the set of units involved by tracing
9073 @code{with} references. The reason it is necessary to be able to
9074 specify more than one ALI file is that a given program may invoke two or
9075 more quite separate groups of Ada units.
9077 The binder takes the name of its output file from the last specified ALI
9078 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
9079 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
9080 The output is an Ada unit in source form that can be compiled with GNAT.
9081 This compilation occurs automatically as part of the @command{gnatlink}
9082 processing.
9084 Currently the GNAT run time requires a FPU using 80 bits mode
9085 precision. Under targets where this is not the default it is required to
9086 call GNAT.Float_Control.Reset before using floating point numbers (this
9087 include float computation, float input and output) in the Ada code. A
9088 side effect is that this could be the wrong mode for the foreign code
9089 where floating point computation could be broken after this call.
9091 @node Binding Programs with No Main Subprogram
9092 @subsection Binding Programs with No Main Subprogram
9094 @noindent
9095 It is possible to have an Ada program which does not have a main
9096 subprogram. This program will call the elaboration routines of all the
9097 packages, then the finalization routines.
9099 The following switch is used to bind programs organized in this manner:
9101 @table @option
9102 @item ^-z^/ZERO_MAIN^
9103 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
9104 Normally the binder checks that the unit name given on the command line
9105 corresponds to a suitable main subprogram. When this switch is used,
9106 a list of ALI files can be given, and the execution of the program
9107 consists of elaboration of these units in an appropriate order. Note
9108 that the default wide character encoding method for standard Text_IO
9109 files is always set to Brackets if this switch is set (you can use
9110 the binder switch
9111 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
9112 @end table
9114 @node Command-Line Access
9115 @section Command-Line Access
9117 @noindent
9118 The package @code{Ada.Command_Line} provides access to the command-line
9119 arguments and program name. In order for this interface to operate
9120 correctly, the two variables
9122 @smallexample
9123 @group
9124 int gnat_argc;
9125 char **gnat_argv;
9126 @end group
9127 @end smallexample
9129 @noindent
9130 @findex gnat_argv
9131 @findex gnat_argc
9132 are declared in one of the GNAT library routines. These variables must
9133 be set from the actual @code{argc} and @code{argv} values passed to the
9134 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
9135 generates the C main program to automatically set these variables.
9136 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
9137 set these variables. If they are not set, the procedures in
9138 @code{Ada.Command_Line} will not be available, and any attempt to use
9139 them will raise @code{Constraint_Error}. If command line access is
9140 required, your main program must set @code{gnat_argc} and
9141 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
9144 @node Search Paths for gnatbind
9145 @section Search Paths for @code{gnatbind}
9147 @noindent
9148 The binder takes the name of an ALI file as its argument and needs to
9149 locate source files as well as other ALI files to verify object consistency.
9151 For source files, it follows exactly the same search rules as @command{gcc}
9152 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
9153 directories searched are:
9155 @enumerate
9156 @item
9157 The directory containing the ALI file named in the command line, unless
9158 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
9160 @item
9161 All directories specified by @option{^-I^/SEARCH^}
9162 switches on the @code{gnatbind}
9163 command line, in the order given.
9165 @item
9166 @findex ADA_PRJ_OBJECTS_FILE
9167 Each of the directories listed in the text file whose name is given
9168 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
9170 @noindent
9171 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
9172 driver when project files are used. It should not normally be set
9173 by other means.
9175 @item
9176 @findex ADA_OBJECTS_PATH
9177 Each of the directories listed in the value of the
9178 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
9179 @ifset unw
9180 Construct this value
9181 exactly as the @env{PATH} environment variable: a list of directory
9182 names separated by colons (semicolons when working with the NT version
9183 of GNAT).
9184 @end ifset
9185 @ifset vms
9186 Normally, define this value as a logical name containing a comma separated
9187 list of directory names.
9189 This variable can also be defined by means of an environment string
9190 (an argument to the HP C exec* set of functions).
9192 Logical Name:
9193 @smallexample
9194 DEFINE ANOTHER_PATH FOO:[BAG]
9195 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9196 @end smallexample
9198 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9199 first, followed by the standard Ada
9200 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9201 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9202 (Text_IO, Sequential_IO, etc)
9203 instead of the standard Ada packages. Thus, in order to get the standard Ada
9204 packages by default, ADA_OBJECTS_PATH must be redefined.
9205 @end ifset
9207 @item
9208 The content of the @file{ada_object_path} file which is part of the GNAT
9209 installation tree and is used to store standard libraries such as the
9210 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9211 specified.
9212 @ifclear vms
9213 @ref{Installing a library}
9214 @end ifclear
9215 @end enumerate
9217 @noindent
9218 In the binder the switch @option{^-I^/SEARCH^}
9219 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9220 is used to specify both source and
9221 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9222 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9223 instead if you want to specify
9224 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9225 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9226 if you want to specify library paths
9227 only. This means that for the binder
9228 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9229 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9230 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9231 The binder generates the bind file (a C language source file) in the
9232 current working directory.
9234 @findex Ada
9235 @findex System
9236 @findex Interfaces
9237 @findex GNAT
9238 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9239 children make up the GNAT Run-Time Library, together with the package
9240 GNAT and its children, which contain a set of useful additional
9241 library functions provided by GNAT. The sources for these units are
9242 needed by the compiler and are kept together in one directory. The ALI
9243 files and object files generated by compiling the RTL are needed by the
9244 binder and the linker and are kept together in one directory, typically
9245 different from the directory containing the sources. In a normal
9246 installation, you need not specify these directory names when compiling
9247 or binding. Either the environment variables or the built-in defaults
9248 cause these files to be found.
9250 Besides simplifying access to the RTL, a major use of search paths is
9251 in compiling sources from multiple directories. This can make
9252 development environments much more flexible.
9254 @node Examples of gnatbind Usage
9255 @section Examples of @code{gnatbind} Usage
9257 @noindent
9258 This section contains a number of examples of using the GNAT binding
9259 utility @code{gnatbind}.
9261 @table @code
9262 @item gnatbind hello
9263 The main program @code{Hello} (source program in @file{hello.adb}) is
9264 bound using the standard switch settings. The generated main program is
9265 @file{b~hello.adb}. This is the normal, default use of the binder.
9267 @ifclear vms
9268 @item gnatbind hello -o mainprog.adb
9269 @end ifclear
9270 @ifset vms
9271 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9272 @end ifset
9273 The main program @code{Hello} (source program in @file{hello.adb}) is
9274 bound using the standard switch settings. The generated main program is
9275 @file{mainprog.adb} with the associated spec in
9276 @file{mainprog.ads}. Note that you must specify the body here not the
9277 spec. Note that if this option is used, then linking must be done manually,
9278 since gnatlink will not be able to find the generated file.
9279 @end table
9281 @c ------------------------------------
9282 @node Linking Using gnatlink
9283 @chapter Linking Using @command{gnatlink}
9284 @c ------------------------------------
9285 @findex gnatlink
9287 @noindent
9288 This chapter discusses @command{gnatlink}, a tool that links
9289 an Ada program and builds an executable file. This utility
9290 invokes the system linker ^(via the @command{gcc} command)^^
9291 with a correct list of object files and library references.
9292 @command{gnatlink} automatically determines the list of files and
9293 references for the Ada part of a program. It uses the binder file
9294 generated by the @command{gnatbind} to determine this list.
9296 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9297 driver (see @ref{The GNAT Driver and Project Files}).
9299 @menu
9300 * Running gnatlink::
9301 * Switches for gnatlink::
9302 @end menu
9304 @node Running gnatlink
9305 @section Running @command{gnatlink}
9307 @noindent
9308 The form of the @command{gnatlink} command is
9310 @smallexample
9311 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9312 @c            @ovar{non-Ada objects} @ovar{linker options}
9313 @c Expanding @ovar macro inline (explanation in macro def comments)
9314 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9315            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9317 @end smallexample
9319 @noindent
9320 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9321 non-Ada objects
9322 or linker options) may be in any order, provided that no non-Ada object may
9323 be mistaken for a main @file{ALI} file.
9324 Any file name @file{F} without the @file{.ali}
9325 extension will be taken as the main @file{ALI} file if a file exists
9326 whose name is the concatenation of @file{F} and @file{.ali}.
9328 @noindent
9329 @file{@var{mainprog}.ali} references the ALI file of the main program.
9330 The @file{.ali} extension of this file can be omitted. From this
9331 reference, @command{gnatlink} locates the corresponding binder file
9332 @file{b~@var{mainprog}.adb} and, using the information in this file along
9333 with the list of non-Ada objects and linker options, constructs a
9334 linker command file to create the executable.
9336 The arguments other than the @command{gnatlink} switches and the main
9337 @file{ALI} file are passed to the linker uninterpreted.
9338 They typically include the names of
9339 object files for units written in other languages than Ada and any library
9340 references required to resolve references in any of these foreign language
9341 units, or in @code{Import} pragmas in any Ada units.
9343 @var{linker options} is an optional list of linker specific
9344 switches.
9345 The default linker called by gnatlink is @command{gcc} which in
9346 turn calls the appropriate system linker.
9348 One useful option for the linker is @option{-s}: it reduces the size of the
9349 executable by removing all symbol table and relocation information from the
9350 executable.
9352 Standard options for the linker such as @option{-lmy_lib} or
9353 @option{-Ldir} can be added as is.
9354 For options that are not recognized by
9355 @command{gcc} as linker options, use the @command{gcc} switches
9356 @option{-Xlinker} or @option{-Wl,}.
9358 Refer to the GCC documentation for
9359 details.
9361 Here is an example showing how to generate a linker map:
9363 @smallexample
9364 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9365 @end smallexample
9367 Using @var{linker options} it is possible to set the program stack and
9368 heap size.
9369 @ifset unw
9370 See @ref{Setting Stack Size from gnatlink} and
9371 @ref{Setting Heap Size from gnatlink}.
9372 @end ifset
9374 @command{gnatlink} determines the list of objects required by the Ada
9375 program and prepends them to the list of objects passed to the linker.
9376 @command{gnatlink} also gathers any arguments set by the use of
9377 @code{pragma Linker_Options} and adds them to the list of arguments
9378 presented to the linker.
9380 @ifset vms
9381 @command{gnatlink} accepts the following types of extra files on the command
9382 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9383 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9384 handled according to their extension.
9385 @end ifset
9387 @node Switches for gnatlink
9388 @section Switches for @command{gnatlink}
9390 @noindent
9391 The following switches are available with the @command{gnatlink} utility:
9393 @table @option
9394 @c !sort!
9396 @item --version
9397 @cindex @option{--version} @command{gnatlink}
9398 Display Copyright and version, then exit disregarding all other options.
9400 @item --help
9401 @cindex @option{--help} @command{gnatlink}
9402 If @option{--version} was not used, display usage, then exit disregarding
9403 all other options.
9405 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9406 @cindex Command line length
9407 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9408 On some targets, the command line length is limited, and @command{gnatlink}
9409 will generate a separate file for the linker if the list of object files
9410 is too long.
9411 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9412 to be generated even if
9413 the limit is not exceeded. This is useful in some cases to deal with
9414 special situations where the command line length is exceeded.
9416 @item ^-g^/DEBUG^
9417 @cindex Debugging information, including
9418 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9419 The option to include debugging information causes the Ada bind file (in
9420 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9421 @option{^-g^/DEBUG^}.
9422 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9423 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9424 Without @option{^-g^/DEBUG^}, the binder removes these files by
9425 default. The same procedure apply if a C bind file was generated using
9426 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9427 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9429 @item ^-n^/NOCOMPILE^
9430 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9431 Do not compile the file generated by the binder. This may be used when
9432 a link is rerun with different options, but there is no need to recompile
9433 the binder file.
9435 @item ^-v^/VERBOSE^
9436 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9437 Causes additional information to be output, including a full list of the
9438 included object files. This switch option is most useful when you want
9439 to see what set of object files are being used in the link step.
9441 @item ^-v -v^/VERBOSE/VERBOSE^
9442 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9443 Very verbose mode. Requests that the compiler operate in verbose mode when
9444 it compiles the binder file, and that the system linker run in verbose mode.
9446 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9447 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9448 @var{exec-name} specifies an alternate name for the generated
9449 executable program. If this switch is omitted, the executable has the same
9450 name as the main unit. For example, @code{gnatlink try.ali} creates
9451 an executable called @file{^try^TRY.EXE^}.
9453 @ifclear vms
9454 @item -b @var{target}
9455 @cindex @option{-b} (@command{gnatlink})
9456 Compile your program to run on @var{target}, which is the name of a
9457 system configuration. You must have a GNAT cross-compiler built if
9458 @var{target} is not the same as your host system.
9460 @item -B@var{dir}
9461 @cindex @option{-B} (@command{gnatlink})
9462 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9463 from @var{dir} instead of the default location. Only use this switch
9464 when multiple versions of the GNAT compiler are available.
9465 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9466 for further details. You would normally use the @option{-b} or
9467 @option{-V} switch instead.
9469 @item -M
9470 When linking an executable, create a map file. The name of the map file
9471 has the same name as the executable with extension ".map".
9473 @item -M=mapfile
9474 When linking an executable, create a map file. The name of the map file is
9475 "mapfile".
9477 @item --GCC=@var{compiler_name}
9478 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9479 Program used for compiling the binder file. The default is
9480 @command{gcc}. You need to use quotes around @var{compiler_name} if
9481 @code{compiler_name} contains spaces or other separator characters.
9482 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9483 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9484 inserted after your command name. Thus in the above example the compiler
9485 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9486 A limitation of this syntax is that the name and path name of the executable
9487 itself must not include any embedded spaces. If the compiler executable is
9488 different from the default one (gcc or <prefix>-gcc), then the back-end
9489 switches in the ALI file are not used to compile the binder generated source.
9490 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9491 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9492 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9493 is taken into account. However, all the additional switches are also taken
9494 into account. Thus,
9495 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9496 @option{--GCC="bar -x -y -z -t"}.
9498 @item --LINK=@var{name}
9499 @cindex @option{--LINK=} (@command{gnatlink})
9500 @var{name} is the name of the linker to be invoked. This is especially
9501 useful in mixed language programs since languages such as C++ require
9502 their own linker to be used. When this switch is omitted, the default
9503 name for the linker is @command{gcc}. When this switch is used, the
9504 specified linker is called instead of @command{gcc} with exactly the same
9505 parameters that would have been passed to @command{gcc} so if the desired
9506 linker requires different parameters it is necessary to use a wrapper
9507 script that massages the parameters before invoking the real linker. It
9508 may be useful to control the exact invocation by using the verbose
9509 switch.
9511 @end ifclear
9513 @ifset vms
9514 @item /DEBUG=TRACEBACK
9515 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9516 This qualifier causes sufficient information to be included in the
9517 executable file to allow a traceback, but does not include the full
9518 symbol information needed by the debugger.
9520 @item /IDENTIFICATION="<string>"
9521 @code{"<string>"} specifies the string to be stored in the image file
9522 identification field in the image header.
9523 It overrides any pragma @code{Ident} specified string.
9525 @item /NOINHIBIT-EXEC
9526 Generate the executable file even if there are linker warnings.
9528 @item /NOSTART_FILES
9529 Don't link in the object file containing the ``main'' transfer address.
9530 Used when linking with a foreign language main program compiled with an
9531 HP compiler.
9533 @item /STATIC
9534 Prefer linking with object libraries over sharable images, even without
9535 /DEBUG.
9536 @end ifset
9538 @end table
9540 @node The GNAT Make Program gnatmake
9541 @chapter The GNAT Make Program @command{gnatmake}
9542 @findex gnatmake
9544 @menu
9545 * Running gnatmake::
9546 * Switches for gnatmake::
9547 * Mode Switches for gnatmake::
9548 * Notes on the Command Line::
9549 * How gnatmake Works::
9550 * Examples of gnatmake Usage::
9551 @end menu
9552 @noindent
9553 A typical development cycle when working on an Ada program consists of
9554 the following steps:
9556 @enumerate
9557 @item
9558 Edit some sources to fix bugs.
9560 @item
9561 Add enhancements.
9563 @item
9564 Compile all sources affected.
9566 @item
9567 Rebind and relink.
9569 @item
9570 Test.
9571 @end enumerate
9573 @noindent
9574 The third step can be tricky, because not only do the modified files
9575 @cindex Dependency rules
9576 have to be compiled, but any files depending on these files must also be
9577 recompiled. The dependency rules in Ada can be quite complex, especially
9578 in the presence of overloading, @code{use} clauses, generics and inlined
9579 subprograms.
9581 @command{gnatmake} automatically takes care of the third and fourth steps
9582 of this process. It determines which sources need to be compiled,
9583 compiles them, and binds and links the resulting object files.
9585 Unlike some other Ada make programs, the dependencies are always
9586 accurately recomputed from the new sources. The source based approach of
9587 the GNAT compilation model makes this possible. This means that if
9588 changes to the source program cause corresponding changes in
9589 dependencies, they will always be tracked exactly correctly by
9590 @command{gnatmake}.
9592 @node Running gnatmake
9593 @section Running @command{gnatmake}
9595 @noindent
9596 The usual form of the @command{gnatmake} command is
9598 @smallexample
9599 @c $ gnatmake @ovar{switches} @var{file_name}
9600 @c       @ovar{file_names} @ovar{mode_switches}
9601 @c Expanding @ovar macro inline (explanation in macro def comments)
9602 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9603       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9604 @end smallexample
9606 @noindent
9607 The only required argument is one @var{file_name}, which specifies
9608 a compilation unit that is a main program. Several @var{file_names} can be
9609 specified: this will result in several executables being built.
9610 If @code{switches} are present, they can be placed before the first
9611 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9612 If @var{mode_switches} are present, they must always be placed after
9613 the last @var{file_name} and all @code{switches}.
9615 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9616 extension may be omitted from the @var{file_name} arguments. However, if
9617 you are using non-standard extensions, then it is required that the
9618 extension be given. A relative or absolute directory path can be
9619 specified in a @var{file_name}, in which case, the input source file will
9620 be searched for in the specified directory only. Otherwise, the input
9621 source file will first be searched in the directory where
9622 @command{gnatmake} was invoked and if it is not found, it will be search on
9623 the source path of the compiler as described in
9624 @ref{Search Paths and the Run-Time Library (RTL)}.
9626 All @command{gnatmake} output (except when you specify
9627 @option{^-M^/DEPENDENCIES_LIST^}) is to
9628 @file{stderr}. The output produced by the
9629 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9630 @file{stdout}.
9632 @node Switches for gnatmake
9633 @section Switches for @command{gnatmake}
9635 @noindent
9636 You may specify any of the following switches to @command{gnatmake}:
9638 @table @option
9639 @c !sort!
9641 @item --version
9642 @cindex @option{--version} @command{gnatmake}
9643 Display Copyright and version, then exit disregarding all other options.
9645 @item --help
9646 @cindex @option{--help} @command{gnatmake}
9647 If @option{--version} was not used, display usage, then exit disregarding
9648 all other options.
9650 @ifclear vms
9651 @item --GCC=@var{compiler_name}
9652 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9653 Program used for compiling. The default is `@command{gcc}'. You need to use
9654 quotes around @var{compiler_name} if @code{compiler_name} contains
9655 spaces or other separator characters. As an example @option{--GCC="foo -x
9656 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9657 compiler. A limitation of this syntax is that the name and path name of
9658 the executable itself must not include any embedded spaces. Note that
9659 switch @option{-c} is always inserted after your command name. Thus in the
9660 above example the compiler command that will be used by @command{gnatmake}
9661 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9662 used, only the last @var{compiler_name} is taken into account. However,
9663 all the additional switches are also taken into account. Thus,
9664 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9665 @option{--GCC="bar -x -y -z -t"}.
9667 @item --GNATBIND=@var{binder_name}
9668 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9669 Program used for binding. The default is `@code{gnatbind}'. You need to
9670 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9671 or other separator characters. As an example @option{--GNATBIND="bar -x
9672 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9673 binder. Binder switches that are normally appended by @command{gnatmake}
9674 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9675 A limitation of this syntax is that the name and path name of the executable
9676 itself must not include any embedded spaces.
9678 @item --GNATLINK=@var{linker_name}
9679 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9680 Program used for linking. The default is `@command{gnatlink}'. You need to
9681 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9682 or other separator characters. As an example @option{--GNATLINK="lan -x
9683 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9684 linker. Linker switches that are normally appended by @command{gnatmake} to
9685 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9686 A limitation of this syntax is that the name and path name of the executable
9687 itself must not include any embedded spaces.
9689 @end ifclear
9691 @item ^--subdirs^/SUBDIRS^=subdir
9692 Actual object directory of each project file is the subdirectory subdir of the
9693 object directory specified or defaulted in the project file.
9695 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9696 Disallow simultaneous compilations in the same object directory when
9697 project files are used.
9699 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9700 By default, shared library projects are not allowed to import static library
9701 projects. When this switch is used on the command line, this restriction is
9702 relaxed.
9704 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9705 Specify a source info file. This switch is active only when project files
9706 are used. If the source info file is specified as a relative path, then it is
9707 relative to the object directory of the main project. If the source info file
9708 does not exist, then after the Project Manager has successfully parsed and
9709 processed the project files and found the sources, it creates the source info
9710 file. If the source info file already exists and can be read successfully,
9711 then the Project Manager will get all the needed information about the sources
9712 from the source info file and will not look for them. This reduces the time
9713 to process the project files, especially when looking for sources that take a
9714 long time. If the source info file exists but cannot be parsed successfully,
9715 the Project Manager will attempt to recreate it. If the Project Manager fails
9716 to create the source info file, a message is issued, but gnatmake does not
9717 fail. @command{gnatmake} "trusts" the source info file. This means that
9718 if the source files have changed (addition, deletion, moving to a different
9719 source directory), then the source info file need to be deleted and recreated.
9721 @ifclear vms
9722 @item --create-map-file
9723 When linking an executable, create a map file. The name of the map file
9724 has the same name as the executable with extension ".map".
9726 @item --create-map-file=mapfile
9727 When linking an executable, create a map file. The name of the map file is
9728 "mapfile".
9730 @end ifclear
9732 @item ^-a^/ALL_FILES^
9733 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9734 Consider all files in the make process, even the GNAT internal system
9735 files (for example, the predefined Ada library files), as well as any
9736 locked files. Locked files are files whose ALI file is write-protected.
9737 By default,
9738 @command{gnatmake} does not check these files,
9739 because the assumption is that the GNAT internal files are properly up
9740 to date, and also that any write protected ALI files have been properly
9741 installed. Note that if there is an installation problem, such that one
9742 of these files is not up to date, it will be properly caught by the
9743 binder.
9744 You may have to specify this switch if you are working on GNAT
9745 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9746 in conjunction with @option{^-f^/FORCE_COMPILE^}
9747 if you need to recompile an entire application,
9748 including run-time files, using special configuration pragmas,
9749 such as a @code{Normalize_Scalars} pragma.
9751 By default
9752 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9753 internal files with
9754 @ifclear vms
9755 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9756 @end ifclear
9757 @ifset vms
9758 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9759 @end ifset
9761 @item ^-b^/ACTIONS=BIND^
9762 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9763 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9764 compilation and binding, but no link.
9765 Can be combined with @option{^-l^/ACTIONS=LINK^}
9766 to do binding and linking. When not combined with
9767 @option{^-c^/ACTIONS=COMPILE^}
9768 all the units in the closure of the main program must have been previously
9769 compiled and must be up to date. The root unit specified by @var{file_name}
9770 may be given without extension, with the source extension or, if no GNAT
9771 Project File is specified, with the ALI file extension.
9773 @item ^-c^/ACTIONS=COMPILE^
9774 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9775 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9776 is also specified. Do not perform linking, except if both
9777 @option{^-b^/ACTIONS=BIND^} and
9778 @option{^-l^/ACTIONS=LINK^} are also specified.
9779 If the root unit specified by @var{file_name} is not a main unit, this is the
9780 default. Otherwise @command{gnatmake} will attempt binding and linking
9781 unless all objects are up to date and the executable is more recent than
9782 the objects.
9784 @item ^-C^/MAPPING^
9785 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9786 Use a temporary mapping file. A mapping file is a way to communicate
9787 to the compiler two mappings: from unit names to file names (without
9788 any directory information) and from file names to path names (with
9789 full directory information). A mapping file can make the compiler's
9790 file searches faster, especially if there are many source directories,
9791 or the sources are read over a slow network connection. If
9792 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9793 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9794 is initially populated based on the project file. If
9795 @option{^-C^/MAPPING^} is used without
9796 @option{^-P^/PROJECT_FILE^},
9797 the mapping file is initially empty. Each invocation of the compiler
9798 will add any newly accessed sources to the mapping file.
9800 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9801 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9802 Use a specific mapping file. The file, specified as a path name (absolute or
9803 relative) by this switch, should already exist, otherwise the switch is
9804 ineffective. The specified mapping file will be communicated to the compiler.
9805 This switch is not compatible with a project file
9806 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9807 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9809 @item ^-d^/DISPLAY_PROGRESS^
9810 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9811 Display progress for each source, up to date or not, as a single line
9813 @smallexample
9814 completed x out of y (zz%)
9815 @end smallexample
9817 If the file needs to be compiled this is displayed after the invocation of
9818 the compiler. These lines are displayed even in quiet output mode.
9820 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9821 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9822 Put all object files and ALI file in directory @var{dir}.
9823 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9824 and ALI files go in the current working directory.
9826 This switch cannot be used when using a project file.
9828 @item -eInnn
9829 @cindex @option{-eI} (@command{gnatmake})
9830 Indicates that the main source is a multi-unit source and the rank of the unit
9831 in the source file is nnn. nnn needs to be a positive number and a valid
9832 index in the source. This switch cannot be used when @command{gnatmake} is
9833 invoked for several mains.
9835 @ifclear vms
9836 @item -eL
9837 @cindex @option{-eL} (@command{gnatmake})
9838 @cindex symbolic links
9839 Follow all symbolic links when processing project files.
9840 This should be used if your project uses symbolic links for files or
9841 directories, but is not needed in other cases.
9843 @cindex naming scheme
9844 This also assumes that no directory matches the naming scheme for files (for
9845 instance that you do not have a directory called "sources.ads" when using the
9846 default GNAT naming scheme).
9848 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9849 save a lot of system calls (several per source file and object file), which
9850 can result in a significant speed up to load and manipulate a project file,
9851 especially when using source files from a remote system.
9853 @end ifclear
9855 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9856 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9857 Output the commands for the compiler, the binder and the linker
9858 on ^standard output^SYS$OUTPUT^,
9859 instead of ^standard error^SYS$ERROR^.
9861 @item ^-f^/FORCE_COMPILE^
9862 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9863 Force recompilations. Recompile all sources, even though some object
9864 files may be up to date, but don't recompile predefined or GNAT internal
9865 files or locked files (files with a write-protected ALI file),
9866 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9868 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9869 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9870 When using project files, if some errors or warnings are detected during
9871 parsing and verbose mode is not in effect (no use of switch
9872 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9873 file, rather than its simple file name.
9875 @item ^-g^/DEBUG^
9876 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9877 Enable debugging. This switch is simply passed to the compiler and to the
9878 linker.
9880 @item ^-i^/IN_PLACE^
9881 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9882 In normal mode, @command{gnatmake} compiles all object files and ALI files
9883 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9884 then instead object files and ALI files that already exist are overwritten
9885 in place. This means that once a large project is organized into separate
9886 directories in the desired manner, then @command{gnatmake} will automatically
9887 maintain and update this organization. If no ALI files are found on the
9888 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9889 the new object and ALI files are created in the
9890 directory containing the source being compiled. If another organization
9891 is desired, where objects and sources are kept in different directories,
9892 a useful technique is to create dummy ALI files in the desired directories.
9893 When detecting such a dummy file, @command{gnatmake} will be forced to
9894 recompile the corresponding source file, and it will be put the resulting
9895 object and ALI files in the directory where it found the dummy file.
9897 @item ^-j^/PROCESSES=^@var{n}
9898 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9899 @cindex Parallel make
9900 Use @var{n} processes to carry out the (re)compilations. On a
9901 multiprocessor machine compilations will occur in parallel. In the
9902 event of compilation errors, messages from various compilations might
9903 get interspersed (but @command{gnatmake} will give you the full ordered
9904 list of failing compiles at the end). If this is problematic, rerun
9905 the make process with n set to 1 to get a clean list of messages.
9907 @item ^-k^/CONTINUE_ON_ERROR^
9908 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9909 Keep going. Continue as much as possible after a compilation error. To
9910 ease the programmer's task in case of compilation errors, the list of
9911 sources for which the compile fails is given when @command{gnatmake}
9912 terminates.
9914 If @command{gnatmake} is invoked with several @file{file_names} and with this
9915 switch, if there are compilation errors when building an executable,
9916 @command{gnatmake} will not attempt to build the following executables.
9918 @item ^-l^/ACTIONS=LINK^
9919 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9920 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9921 and linking. Linking will not be performed if combined with
9922 @option{^-c^/ACTIONS=COMPILE^}
9923 but not with @option{^-b^/ACTIONS=BIND^}.
9924 When not combined with @option{^-b^/ACTIONS=BIND^}
9925 all the units in the closure of the main program must have been previously
9926 compiled and must be up to date, and the main program needs to have been bound.
9927 The root unit specified by @var{file_name}
9928 may be given without extension, with the source extension or, if no GNAT
9929 Project File is specified, with the ALI file extension.
9931 @item ^-m^/MINIMAL_RECOMPILATION^
9932 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9933 Specify that the minimum necessary amount of recompilations
9934 be performed. In this mode @command{gnatmake} ignores time
9935 stamp differences when the only
9936 modifications to a source file consist in adding/removing comments,
9937 empty lines, spaces or tabs. This means that if you have changed the
9938 comments in a source file or have simply reformatted it, using this
9939 switch will tell @command{gnatmake} not to recompile files that depend on it
9940 (provided other sources on which these files depend have undergone no
9941 semantic modifications). Note that the debugging information may be
9942 out of date with respect to the sources if the @option{-m} switch causes
9943 a compilation to be switched, so the use of this switch represents a
9944 trade-off between compilation time and accurate debugging information.
9946 @item ^-M^/DEPENDENCIES_LIST^
9947 @cindex Dependencies, producing list
9948 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9949 Check if all objects are up to date. If they are, output the object
9950 dependences to @file{stdout} in a form that can be directly exploited in
9951 a @file{Makefile}. By default, each source file is prefixed with its
9952 (relative or absolute) directory name. This name is whatever you
9953 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9954 and @option{^-I^/SEARCH^} switches. If you use
9955 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9956 @option{^-q^/QUIET^}
9957 (see below), only the source file names,
9958 without relative paths, are output. If you just specify the
9959 @option{^-M^/DEPENDENCIES_LIST^}
9960 switch, dependencies of the GNAT internal system files are omitted. This
9961 is typically what you want. If you also specify
9962 the @option{^-a^/ALL_FILES^} switch,
9963 dependencies of the GNAT internal files are also listed. Note that
9964 dependencies of the objects in external Ada libraries (see switch
9965 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9966 are never reported.
9968 @item ^-n^/DO_OBJECT_CHECK^
9969 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9970 Don't compile, bind, or link. Checks if all objects are up to date.
9971 If they are not, the full name of the first file that needs to be
9972 recompiled is printed.
9973 Repeated use of this option, followed by compiling the indicated source
9974 file, will eventually result in recompiling all required units.
9976 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9977 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9978 Output executable name. The name of the final executable program will be
9979 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9980 name for the executable will be the name of the input file in appropriate form
9981 for an executable file on the host system.
9983 This switch cannot be used when invoking @command{gnatmake} with several
9984 @file{file_names}.
9986 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9987 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9988 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9989 automatically missing object directories, library directories and exec
9990 directories.
9992 @item ^-P^/PROJECT_FILE=^@var{project}
9993 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9994 Use project file @var{project}. Only one such switch can be used.
9995 @xref{gnatmake and Project Files}.
9997 @item ^-q^/QUIET^
9998 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9999 Quiet. When this flag is not set, the commands carried out by
10000 @command{gnatmake} are displayed.
10002 @item ^-s^/SWITCH_CHECK/^
10003 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
10004 Recompile if compiler switches have changed since last compilation.
10005 All compiler switches but -I and -o are taken into account in the
10006 following way:
10007 orders between different ``first letter'' switches are ignored, but
10008 orders between same switches are taken into account. For example,
10009 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
10010 is equivalent to @option{-O -g}.
10012 This switch is recommended when Integrated Preprocessing is used.
10014 @item ^-u^/UNIQUE^
10015 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
10016 Unique. Recompile at most the main files. It implies -c. Combined with
10017 -f, it is equivalent to calling the compiler directly. Note that using
10018 ^-u^/UNIQUE^ with a project file and no main has a special meaning
10019 (@pxref{Project Files and Main Subprograms}).
10021 @item ^-U^/ALL_PROJECTS^
10022 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
10023 When used without a project file or with one or several mains on the command
10024 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
10025 on the command line, all sources of all project files are checked and compiled
10026 if not up to date, and libraries are rebuilt, if necessary.
10028 @item ^-v^/REASONS^
10029 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
10030 Verbose. Display the reason for all recompilations @command{gnatmake}
10031 decides are necessary, with the highest verbosity level.
10033 @item ^-vl^/LOW_VERBOSITY^
10034 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
10035 Verbosity level Low. Display fewer lines than in verbosity Medium.
10037 @item ^-vm^/MEDIUM_VERBOSITY^
10038 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
10039 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
10041 @item ^-vh^/HIGH_VERBOSITY^
10042 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
10043 Verbosity level High. Equivalent to ^-v^/REASONS^.
10045 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
10046 Indicate the verbosity of the parsing of GNAT project files.
10047 @xref{Switches Related to Project Files}.
10049 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
10050 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
10051 Indicate that sources that are not part of any Project File may be compiled.
10052 Normally, when using Project Files, only sources that are part of a Project
10053 File may be compile. When this switch is used, a source outside of all Project
10054 Files may be compiled. The ALI file and the object file will be put in the
10055 object directory of the main Project. The compilation switches used will only
10056 be those specified on the command line. Even when
10057 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
10058 command line need to be sources of a project file.
10060 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
10061 Indicate that external variable @var{name} has the value @var{value}.
10062 The Project Manager will use this value for occurrences of
10063 @code{external(name)} when parsing the project file.
10064 @xref{Switches Related to Project Files}.
10066 @item ^-z^/NOMAIN^
10067 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
10068 No main subprogram. Bind and link the program even if the unit name
10069 given on the command line is a package name. The resulting executable
10070 will execute the elaboration routines of the package and its closure,
10071 then the finalization routines.
10073 @end table
10075 @table @asis
10076 @item @command{gcc} @asis{switches}
10077 @ifclear vms
10078 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
10079 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
10080 @end ifclear
10081 @ifset vms
10082 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
10083 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
10084 automatically treated as a compiler switch, and passed on to all
10085 compilations that are carried out.
10086 @end ifset
10087 @end table
10089 @noindent
10090 Source and library search path switches:
10092 @table @option
10093 @c !sort!
10094 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
10095 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
10096 When looking for source files also look in directory @var{dir}.
10097 The order in which source files search is undertaken is
10098 described in @ref{Search Paths and the Run-Time Library (RTL)}.
10100 @item ^-aL^/SKIP_MISSING=^@var{dir}
10101 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
10102 Consider @var{dir} as being an externally provided Ada library.
10103 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
10104 files have been located in directory @var{dir}. This allows you to have
10105 missing bodies for the units in @var{dir} and to ignore out of date bodies
10106 for the same units. You still need to specify
10107 the location of the specs for these units by using the switches
10108 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
10109 or @option{^-I^/SEARCH=^@var{dir}}.
10110 Note: this switch is provided for compatibility with previous versions
10111 of @command{gnatmake}. The easier method of causing standard libraries
10112 to be excluded from consideration is to write-protect the corresponding
10113 ALI files.
10115 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
10116 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
10117 When searching for library and object files, look in directory
10118 @var{dir}. The order in which library files are searched is described in
10119 @ref{Search Paths for gnatbind}.
10121 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
10122 @cindex Search paths, for @command{gnatmake}
10123 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
10124 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
10125 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10127 @item ^-I^/SEARCH=^@var{dir}
10128 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
10129 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
10130 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10132 @item ^-I-^/NOCURRENT_DIRECTORY^
10133 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
10134 @cindex Source files, suppressing search
10135 Do not look for source files in the directory containing the source
10136 file named in the command line.
10137 Do not look for ALI or object files in the directory
10138 where @command{gnatmake} was invoked.
10140 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
10141 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
10142 @cindex Linker libraries
10143 Add directory @var{dir} to the list of directories in which the linker
10144 will search for libraries. This is equivalent to
10145 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
10146 @ifclear vms
10147 Furthermore, under Windows, the sources pointed to by the libraries path
10148 set in the registry are not searched for.
10149 @end ifclear
10151 @item -nostdinc
10152 @cindex @option{-nostdinc} (@command{gnatmake})
10153 Do not look for source files in the system default directory.
10155 @item -nostdlib
10156 @cindex @option{-nostdlib} (@command{gnatmake})
10157 Do not look for library files in the system default directory.
10159 @item --RTS=@var{rts-path}
10160 @cindex @option{--RTS} (@command{gnatmake})
10161 Specifies the default location of the runtime library. GNAT looks for the
10162 runtime
10163 in the following directories, and stops as soon as a valid runtime is found
10164 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
10165 @file{ada_object_path} present):
10167 @itemize @bullet
10168 @item <current directory>/$rts_path
10170 @item <default-search-dir>/$rts_path
10172 @item <default-search-dir>/rts-$rts_path
10173 @end itemize
10175 @noindent
10176 The selected path is handled like a normal RTS path.
10178 @end table
10180 @node Mode Switches for gnatmake
10181 @section Mode Switches for @command{gnatmake}
10183 @noindent
10184 The mode switches (referred to as @code{mode_switches}) allow the
10185 inclusion of switches that are to be passed to the compiler itself, the
10186 binder or the linker. The effect of a mode switch is to cause all
10187 subsequent switches up to the end of the switch list, or up to the next
10188 mode switch, to be interpreted as switches to be passed on to the
10189 designated component of GNAT.
10191 @table @option
10192 @c !sort!
10193 @item -cargs @var{switches}
10194 @cindex @option{-cargs} (@command{gnatmake})
10195 Compiler switches. Here @var{switches} is a list of switches
10196 that are valid switches for @command{gcc}. They will be passed on to
10197 all compile steps performed by @command{gnatmake}.
10199 @item -bargs @var{switches}
10200 @cindex @option{-bargs} (@command{gnatmake})
10201 Binder switches. Here @var{switches} is a list of switches
10202 that are valid switches for @code{gnatbind}. They will be passed on to
10203 all bind steps performed by @command{gnatmake}.
10205 @item -largs @var{switches}
10206 @cindex @option{-largs} (@command{gnatmake})
10207 Linker switches. Here @var{switches} is a list of switches
10208 that are valid switches for @command{gnatlink}. They will be passed on to
10209 all link steps performed by @command{gnatmake}.
10211 @item -margs @var{switches}
10212 @cindex @option{-margs} (@command{gnatmake})
10213 Make switches. The switches are directly interpreted by @command{gnatmake},
10214 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10215 or @option{-largs}.
10216 @end table
10218 @node Notes on the Command Line
10219 @section Notes on the Command Line
10221 @noindent
10222 This section contains some additional useful notes on the operation
10223 of the @command{gnatmake} command.
10225 @itemize @bullet
10226 @item
10227 @cindex Recompilation, by @command{gnatmake}
10228 If @command{gnatmake} finds no ALI files, it recompiles the main program
10229 and all other units required by the main program.
10230 This means that @command{gnatmake}
10231 can be used for the initial compile, as well as during subsequent steps of
10232 the development cycle.
10234 @item
10235 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10236 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10237 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10238 warning.
10240 @item
10241 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10242 is used to specify both source and
10243 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10244 instead if you just want to specify
10245 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10246 if you want to specify library paths
10247 only.
10249 @item
10250 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10251 This may conveniently be used to exclude standard libraries from
10252 consideration and in particular it means that the use of the
10253 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10254 unless @option{^-a^/ALL_FILES^} is also specified.
10256 @item
10257 @command{gnatmake} has been designed to make the use of Ada libraries
10258 particularly convenient. Assume you have an Ada library organized
10259 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10260 of your Ada compilation units,
10261 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10262 specs of these units, but no bodies. Then to compile a unit
10263 stored in @code{main.adb}, which uses this Ada library you would just type
10265 @smallexample
10266 @ifclear vms
10267 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
10268 @end ifclear
10269 @ifset vms
10270 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10271            /SKIP_MISSING=@i{[OBJ_DIR]} main
10272 @end ifset
10273 @end smallexample
10275 @item
10276 Using @command{gnatmake} along with the
10277 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10278 switch provides a mechanism for avoiding unnecessary recompilations. Using
10279 this switch,
10280 you can update the comments/format of your
10281 source files without having to recompile everything. Note, however, that
10282 adding or deleting lines in a source files may render its debugging
10283 info obsolete. If the file in question is a spec, the impact is rather
10284 limited, as that debugging info will only be useful during the
10285 elaboration phase of your program. For bodies the impact can be more
10286 significant. In all events, your debugger will warn you if a source file
10287 is more recent than the corresponding object, and alert you to the fact
10288 that the debugging information may be out of date.
10289 @end itemize
10291 @node How gnatmake Works
10292 @section How @command{gnatmake} Works
10294 @noindent
10295 Generally @command{gnatmake} automatically performs all necessary
10296 recompilations and you don't need to worry about how it works. However,
10297 it may be useful to have some basic understanding of the @command{gnatmake}
10298 approach and in particular to understand how it uses the results of
10299 previous compilations without incorrectly depending on them.
10301 First a definition: an object file is considered @dfn{up to date} if the
10302 corresponding ALI file exists and if all the source files listed in the
10303 dependency section of this ALI file have time stamps matching those in
10304 the ALI file. This means that neither the source file itself nor any
10305 files that it depends on have been modified, and hence there is no need
10306 to recompile this file.
10308 @command{gnatmake} works by first checking if the specified main unit is up
10309 to date. If so, no compilations are required for the main unit. If not,
10310 @command{gnatmake} compiles the main program to build a new ALI file that
10311 reflects the latest sources. Then the ALI file of the main unit is
10312 examined to find all the source files on which the main program depends,
10313 and @command{gnatmake} recursively applies the above procedure on all these
10314 files.
10316 This process ensures that @command{gnatmake} only trusts the dependencies
10317 in an existing ALI file if they are known to be correct. Otherwise it
10318 always recompiles to determine a new, guaranteed accurate set of
10319 dependencies. As a result the program is compiled ``upside down'' from what may
10320 be more familiar as the required order of compilation in some other Ada
10321 systems. In particular, clients are compiled before the units on which
10322 they depend. The ability of GNAT to compile in any order is critical in
10323 allowing an order of compilation to be chosen that guarantees that
10324 @command{gnatmake} will recompute a correct set of new dependencies if
10325 necessary.
10327 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10328 imported by several of the executables, it will be recompiled at most once.
10330 Note: when using non-standard naming conventions
10331 (@pxref{Using Other File Names}), changing through a configuration pragmas
10332 file the version of a source and invoking @command{gnatmake} to recompile may
10333 have no effect, if the previous version of the source is still accessible
10334 by @command{gnatmake}. It may be necessary to use the switch
10335 ^-f^/FORCE_COMPILE^.
10337 @node Examples of gnatmake Usage
10338 @section Examples of @command{gnatmake} Usage
10340 @table @code
10341 @item gnatmake hello.adb
10342 Compile all files necessary to bind and link the main program
10343 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10344 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10346 @item gnatmake main1 main2 main3
10347 Compile all files necessary to bind and link the main programs
10348 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10349 (containing unit @code{Main2}) and @file{main3.adb}
10350 (containing unit @code{Main3}) and bind and link the resulting object files
10351 to generate three executable files @file{^main1^MAIN1.EXE^},
10352 @file{^main2^MAIN2.EXE^}
10353 and @file{^main3^MAIN3.EXE^}.
10355 @ifclear vms
10356 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10357 @end ifclear
10359 @ifset vms
10360 @item gnatmake Main_Unit /QUIET
10361 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10362 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10363 @end ifset
10364 Compile all files necessary to bind and link the main program unit
10365 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10366 be done with optimization level 2 and the order of elaboration will be
10367 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10368 displaying commands it is executing.
10369 @end table
10371 @c *************************
10372 @node Improving Performance
10373 @chapter Improving Performance
10374 @cindex Improving performance
10376 @noindent
10377 This chapter presents several topics related to program performance.
10378 It first describes some of the tradeoffs that need to be considered
10379 and some of the techniques for making your program run faster.
10380 It then documents the @command{gnatelim} tool and unused subprogram/data
10381 elimination feature, which can reduce the size of program executables.
10383 @ifnottex
10384 @menu
10385 * Performance Considerations::
10386 * Text_IO Suggestions::
10387 * Reducing Size of Ada Executables with gnatelim::
10388 * Reducing Size of Executables with unused subprogram/data elimination::
10389 @end menu
10390 @end ifnottex
10392 @c *****************************
10393 @node Performance Considerations
10394 @section Performance Considerations
10396 @noindent
10397 The GNAT system provides a number of options that allow a trade-off
10398 between
10400 @itemize @bullet
10401 @item
10402 performance of the generated code
10404 @item
10405 speed of compilation
10407 @item
10408 minimization of dependences and recompilation
10410 @item
10411 the degree of run-time checking.
10412 @end itemize
10414 @noindent
10415 The defaults (if no options are selected) aim at improving the speed
10416 of compilation and minimizing dependences, at the expense of performance
10417 of the generated code:
10419 @itemize @bullet
10420 @item
10421 no optimization
10423 @item
10424 no inlining of subprogram calls
10426 @item
10427 all run-time checks enabled except overflow and elaboration checks
10428 @end itemize
10430 @noindent
10431 These options are suitable for most program development purposes. This
10432 chapter describes how you can modify these choices, and also provides
10433 some guidelines on debugging optimized code.
10435 @menu
10436 * Controlling Run-Time Checks::
10437 * Use of Restrictions::
10438 * Optimization Levels::
10439 * Debugging Optimized Code::
10440 * Inlining of Subprograms::
10441 * Vectorization of loops::
10442 * Other Optimization Switches::
10443 * Optimization and Strict Aliasing::
10445 @ifset vms
10446 * Coverage Analysis::
10447 @end ifset
10448 @end menu
10450 @node Controlling Run-Time Checks
10451 @subsection Controlling Run-Time Checks
10453 @noindent
10454 By default, GNAT generates all run-time checks, except integer overflow
10455 checks, stack overflow checks, and checks for access before elaboration on
10456 subprogram calls. The latter are not required in default mode, because all
10457 necessary checking is done at compile time.
10458 @cindex @option{-gnatp} (@command{gcc})
10459 @cindex @option{-gnato} (@command{gcc})
10460 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10461 be modified. @xref{Run-Time Checks}.
10463 Our experience is that the default is suitable for most development
10464 purposes.
10466 We treat integer overflow specially because these
10467 are quite expensive and in our experience are not as important as other
10468 run-time checks in the development process. Note that division by zero
10469 is not considered an overflow check, and divide by zero checks are
10470 generated where required by default.
10472 Elaboration checks are off by default, and also not needed by default, since
10473 GNAT uses a static elaboration analysis approach that avoids the need for
10474 run-time checking. This manual contains a full chapter discussing the issue
10475 of elaboration checks, and if the default is not satisfactory for your use,
10476 you should read this chapter.
10478 For validity checks, the minimal checks required by the Ada Reference
10479 Manual (for case statements and assignments to array elements) are on
10480 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10481 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10482 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10483 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10484 are also suppressed entirely if @option{-gnatp} is used.
10486 @cindex Overflow checks
10487 @cindex Checks, overflow
10488 @findex Suppress
10489 @findex Unsuppress
10490 @cindex pragma Suppress
10491 @cindex pragma Unsuppress
10492 Note that the setting of the switches controls the default setting of
10493 the checks. They may be modified using either @code{pragma Suppress} (to
10494 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10495 checks) in the program source.
10497 @node Use of Restrictions
10498 @subsection Use of Restrictions
10500 @noindent
10501 The use of pragma Restrictions allows you to control which features are
10502 permitted in your program. Apart from the obvious point that if you avoid
10503 relatively expensive features like finalization (enforceable by the use
10504 of pragma Restrictions (No_Finalization), the use of this pragma does not
10505 affect the generated code in most cases.
10507 One notable exception to this rule is that the possibility of task abort
10508 results in some distributed overhead, particularly if finalization or
10509 exception handlers are used. The reason is that certain sections of code
10510 have to be marked as non-abortable.
10512 If you use neither the @code{abort} statement, nor asynchronous transfer
10513 of control (@code{select @dots{} then abort}), then this distributed overhead
10514 is removed, which may have a general positive effect in improving
10515 overall performance.  Especially code involving frequent use of tasking
10516 constructs and controlled types will show much improved performance.
10517 The relevant restrictions pragmas are
10519 @smallexample @c ada
10520    pragma Restrictions (No_Abort_Statements);
10521    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10522 @end smallexample
10524 @noindent
10525 It is recommended that these restriction pragmas be used if possible. Note
10526 that this also means that you can write code without worrying about the
10527 possibility of an immediate abort at any point.
10529 @node Optimization Levels
10530 @subsection Optimization Levels
10531 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10533 @noindent
10534 Without any optimization ^option,^qualifier,^
10535 the compiler's goal is to reduce the cost of
10536 compilation and to make debugging produce the expected results.
10537 Statements are independent: if you stop the program with a breakpoint between
10538 statements, you can then assign a new value to any variable or change
10539 the program counter to any other statement in the subprogram and get exactly
10540 the results you would expect from the source code.
10542 Turning on optimization makes the compiler attempt to improve the
10543 performance and/or code size at the expense of compilation time and
10544 possibly the ability to debug the program.
10546 If you use multiple
10547 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10548 the last such option is the one that is effective.
10550 @noindent
10551 The default is optimization off. This results in the fastest compile
10552 times, but GNAT makes absolutely no attempt to optimize, and the
10553 generated programs are considerably larger and slower than when
10554 optimization is enabled. You can use the
10555 @ifclear vms
10556 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10557 @option{-O2}, @option{-O3}, and @option{-Os})
10558 @end ifclear
10559 @ifset vms
10560 @code{OPTIMIZE} qualifier
10561 @end ifset
10562 to @command{gcc} to control the optimization level:
10564 @table @option
10565 @item ^-O0^/OPTIMIZE=NONE^
10566 No optimization (the default);
10567 generates unoptimized code but has
10568 the fastest compilation time.
10570 Note that many other compilers do fairly extensive optimization
10571 even if ``no optimization'' is specified. With gcc, it is
10572 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10573 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10574 really does mean no optimization at all. This difference between
10575 gcc and other compilers should be kept in mind when doing
10576 performance comparisons.
10578 @item ^-O1^/OPTIMIZE=SOME^
10579 Moderate optimization;
10580 optimizes reasonably well but does not
10581 degrade compilation time significantly.
10583 @item ^-O2^/OPTIMIZE=ALL^
10584 @ifset vms
10585 @itemx /OPTIMIZE=DEVELOPMENT
10586 @end ifset
10587 Full optimization;
10588 generates highly optimized code and has
10589 the slowest compilation time.
10591 @item ^-O3^/OPTIMIZE=INLINING^
10592 Full optimization as in @option{-O2};
10593 also uses more aggressive automatic inlining of subprograms within a unit
10594 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10596 @item ^-Os^/OPTIMIZE=SPACE^
10597 Optimize space usage (code and data) of resulting program.
10598 @end table
10600 @noindent
10601 Higher optimization levels perform more global transformations on the
10602 program and apply more expensive analysis algorithms in order to generate
10603 faster and more compact code. The price in compilation time, and the
10604 resulting improvement in execution time,
10605 both depend on the particular application and the hardware environment.
10606 You should experiment to find the best level for your application.
10608 Since the precise set of optimizations done at each level will vary from
10609 release to release (and sometime from target to target), it is best to think
10610 of the optimization settings in general terms.
10611 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10612 the GNU Compiler Collection (GCC)}, for details about
10613 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10614 individually enable or disable specific optimizations.
10616 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10617 been tested extensively at all optimization levels. There are some bugs
10618 which appear only with optimization turned on, but there have also been
10619 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10620 level of optimization does not improve the reliability of the code
10621 generator, which in practice is highly reliable at all optimization
10622 levels.
10624 Note regarding the use of @option{-O3}: The use of this optimization level
10625 is generally discouraged with GNAT, since it often results in larger
10626 executables which may run more slowly. See further discussion of this point
10627 in @ref{Inlining of Subprograms}.
10629 @node Debugging Optimized Code
10630 @subsection Debugging Optimized Code
10631 @cindex Debugging optimized code
10632 @cindex Optimization and debugging
10634 @noindent
10635 Although it is possible to do a reasonable amount of debugging at
10636 @ifclear vms
10637 nonzero optimization levels,
10638 the higher the level the more likely that
10639 @end ifclear
10640 @ifset vms
10641 @option{/OPTIMIZE} settings other than @code{NONE},
10642 such settings will make it more likely that
10643 @end ifset
10644 source-level constructs will have been eliminated by optimization.
10645 For example, if a loop is strength-reduced, the loop
10646 control variable may be completely eliminated and thus cannot be
10647 displayed in the debugger.
10648 This can only happen at @option{-O2} or @option{-O3}.
10649 Explicit temporary variables that you code might be eliminated at
10650 ^level^setting^ @option{-O1} or higher.
10652 The use of the @option{^-g^/DEBUG^} switch,
10653 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10654 which is needed for source-level debugging,
10655 affects the size of the program executable on disk,
10656 and indeed the debugging information can be quite large.
10657 However, it has no effect on the generated code (and thus does not
10658 degrade performance)
10660 Since the compiler generates debugging tables for a compilation unit before
10661 it performs optimizations, the optimizing transformations may invalidate some
10662 of the debugging data.  You therefore need to anticipate certain
10663 anomalous situations that may arise while debugging optimized code.
10664 These are the most common cases:
10666 @enumerate
10667 @item
10668 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10669 commands show
10670 the PC bouncing back and forth in the code.  This may result from any of
10671 the following optimizations:
10673 @itemize @bullet
10674 @item
10675 @i{Common subexpression elimination:} using a single instance of code for a
10676 quantity that the source computes several times.  As a result you
10677 may not be able to stop on what looks like a statement.
10679 @item
10680 @i{Invariant code motion:} moving an expression that does not change within a
10681 loop, to the beginning of the loop.
10683 @item
10684 @i{Instruction scheduling:} moving instructions so as to
10685 overlap loads and stores (typically) with other code, or in
10686 general to move computations of values closer to their uses. Often
10687 this causes you to pass an assignment statement without the assignment
10688 happening and then later bounce back to the statement when the
10689 value is actually needed.  Placing a breakpoint on a line of code
10690 and then stepping over it may, therefore, not always cause all the
10691 expected side-effects.
10692 @end itemize
10694 @item
10695 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10696 two identical pieces of code are merged and the program counter suddenly
10697 jumps to a statement that is not supposed to be executed, simply because
10698 it (and the code following) translates to the same thing as the code
10699 that @emph{was} supposed to be executed.  This effect is typically seen in
10700 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10701 a @code{break} in a C @code{^switch^switch^} statement.
10703 @item
10704 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10705 There are various reasons for this effect:
10707 @itemize @bullet
10708 @item
10709 In a subprogram prologue, a parameter may not yet have been moved to its
10710 ``home''.
10712 @item
10713 A variable may be dead, and its register re-used.  This is
10714 probably the most common cause.
10716 @item
10717 As mentioned above, the assignment of a value to a variable may
10718 have been moved.
10720 @item
10721 A variable may be eliminated entirely by value propagation or
10722 other means.  In this case, GCC may incorrectly generate debugging
10723 information for the variable
10724 @end itemize
10726 @noindent
10727 In general, when an unexpected value appears for a local variable or parameter
10728 you should first ascertain if that value was actually computed by
10729 your program, as opposed to being incorrectly reported by the debugger.
10730 Record fields or
10731 array elements in an object designated by an access value
10732 are generally less of a problem, once you have ascertained that the access
10733 value is sensible.
10734 Typically, this means checking variables in the preceding code and in the
10735 calling subprogram to verify that the value observed is explainable from other
10736 values (one must apply the procedure recursively to those
10737 other values); or re-running the code and stopping a little earlier
10738 (perhaps before the call) and stepping to better see how the variable obtained
10739 the value in question; or continuing to step @emph{from} the point of the
10740 strange value to see if code motion had simply moved the variable's
10741 assignments later.
10742 @end enumerate
10744 @noindent
10745 In light of such anomalies, a recommended technique is to use @option{-O0}
10746 early in the software development cycle, when extensive debugging capabilities
10747 are most needed, and then move to @option{-O1} and later @option{-O2} as
10748 the debugger becomes less critical.
10749 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10750 a release management issue.
10751 @ifclear vms
10752 Note that if you use @option{-g} you can then use the @command{strip} program
10753 on the resulting executable,
10754 which removes both debugging information and global symbols.
10755 @end ifclear
10757 @node Inlining of Subprograms
10758 @subsection Inlining of Subprograms
10760 @noindent
10761 A call to a subprogram in the current unit is inlined if all the
10762 following conditions are met:
10764 @itemize @bullet
10765 @item
10766 The optimization level is at least @option{-O1}.
10768 @item
10769 The called subprogram is suitable for inlining: It must be small enough
10770 and not contain something that @command{gcc} cannot support in inlined
10771 subprograms.
10773 @item
10774 @cindex pragma Inline
10775 @findex Inline
10776 Any one of the following applies: @code{pragma Inline} is applied to the
10777 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10778 subprogram is local to the unit and called once from within it; the
10779 subprogram is small and optimization level @option{-O2} is specified;
10780 optimization level @option{-O3} is specified.
10781 @end itemize
10783 @noindent
10784 Calls to subprograms in @code{with}'ed units are normally not inlined.
10785 To achieve actual inlining (that is, replacement of the call by the code
10786 in the body of the subprogram), the following conditions must all be true:
10788 @itemize @bullet
10789 @item
10790 The optimization level is at least @option{-O1}.
10792 @item
10793 The called subprogram is suitable for inlining: It must be small enough
10794 and not contain something that @command{gcc} cannot support in inlined
10795 subprograms.
10797 @item
10798 The call appears in a body (not in a package spec).
10800 @item
10801 There is a @code{pragma Inline} for the subprogram.
10803 @item
10804 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10805 @end itemize
10807 Even if all these conditions are met, it may not be possible for
10808 the compiler to inline the call, due to the length of the body,
10809 or features in the body that make it impossible for the compiler
10810 to do the inlining.
10812 Note that specifying the @option{-gnatn} switch causes additional
10813 compilation dependencies. Consider the following:
10815 @smallexample @c ada
10816 @cartouche
10817 package R is
10818    procedure Q;
10819    pragma Inline (Q);
10820 end R;
10821 package body R is
10822    @dots{}
10823 end R;
10825 with R;
10826 procedure Main is
10827 begin
10828    @dots{}
10829    R.Q;
10830 end Main;
10831 @end cartouche
10832 @end smallexample
10834 @noindent
10835 With the default behavior (no @option{-gnatn} switch specified), the
10836 compilation of the @code{Main} procedure depends only on its own source,
10837 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10838 means that editing the body of @code{R} does not require recompiling
10839 @code{Main}.
10841 On the other hand, the call @code{R.Q} is not inlined under these
10842 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10843 is compiled, the call will be inlined if the body of @code{Q} is small
10844 enough, but now @code{Main} depends on the body of @code{R} in
10845 @file{r.adb} as well as on the spec. This means that if this body is edited,
10846 the main program must be recompiled. Note that this extra dependency
10847 occurs whether or not the call is in fact inlined by @command{gcc}.
10849 The use of front end inlining with @option{-gnatN} generates similar
10850 additional dependencies.
10852 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10853 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10854 can be used to prevent
10855 all inlining. This switch overrides all other conditions and ensures
10856 that no inlining occurs. The extra dependences resulting from
10857 @option{-gnatn} will still be active, even if
10858 this switch is used to suppress the resulting inlining actions.
10860 @cindex @option{-fno-inline-functions} (@command{gcc})
10861 Note: The @option{-fno-inline-functions} switch can be used to prevent
10862 automatic inlining of subprograms if @option{-O3} is used.
10864 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10865 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10866 automatic inlining of small subprograms if @option{-O2} is used.
10868 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10869 Note: The @option{-fno-inline-functions-called-once} switch
10870 can be used to prevent inlining of subprograms local to the unit
10871 and called once from within it if @option{-O1} is used.
10873 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10874 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10875 specified in lieu of it, @option{-gnatn} being translated into one of them
10876 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10877 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10878 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10879 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10880 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
10881 effect of inlining subprograms you did not think should be inlined. We have
10882 found that the use of @option{-O3} may slow down the compilation and increase
10883 the code size by performing excessive inlining, leading to increased
10884 instruction cache pressure from the increased code size and thus minor
10885 performance improvements. So the bottom line here is that you should not
10886 automatically assume that @option{-O3} is better than @option{-O2}, and
10887 indeed you should use @option{-O3} only if tests show that it actually
10888 improves performance for your program.
10890 @node Vectorization of loops
10891 @subsection Vectorization of loops
10892 @cindex Optimization Switches
10894 You can take advantage of the auto-vectorizer present in the @command{gcc}
10895 back end to vectorize loops with GNAT.  The corresponding command line switch
10896 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10897 and other aggressive optimizations helpful for vectorization also are enabled
10898 by default at this level, using @option{-O3} directly is recommended.
10900 You also need to make sure that the target architecture features a supported
10901 SIMD instruction set.  For example, for the x86 architecture, you should at
10902 least specify @option{-msse2} to get significant vectorization (but you don't
10903 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10904 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10906 The preferred loop form for vectorization is the @code{for} iteration scheme.
10907 Loops with a @code{while} iteration scheme can also be vectorized if they are
10908 very simple, but the vectorizer will quickly give up otherwise.  With either
10909 iteration scheme, the flow of control must be straight, in particular no
10910 @code{exit} statement may appear in the loop body.  The loop may however
10911 contain a single nested loop, if it can be vectorized when considered alone:
10913 @smallexample @c ada
10914 @cartouche
10915    A : array (1..4, 1..4) of Long_Float;
10916    S : array (1..4) of Long_Float;
10918    procedure Sum is
10919    begin
10920       for I in A'Range(1) loop
10921          for J in A'Range(2) loop
10922             S (I) := S (I) + A (I, J);
10923          end loop;
10924       end loop;
10925    end Sum;
10926 @end cartouche
10927 @end smallexample
10929 The vectorizable operations depend on the targeted SIMD instruction set, but
10930 the adding and some of the multiplying operators are generally supported, as
10931 well as the logical operators for modular types.  Note that, in the former
10932 case, enabling overflow checks, for example with @option{-gnato}, totally
10933 disables vectorization.  The other checks are not supposed to have the same
10934 definitive effect, although compiling with @option{-gnatp} might well reveal
10935 cases where some checks do thwart vectorization.
10937 Type conversions may also prevent vectorization if they involve semantics that
10938 are not directly supported by the code generator or the SIMD instruction set.
10939 A typical example is direct conversion from floating-point to integer types.
10940 The solution in this case is to use the following idiom:
10942 @smallexample @c ada
10943    Integer (S'Truncation (F))
10944 @end smallexample
10946 @noindent
10947 if @code{S} is the subtype of floating-point object @code{F}.
10949 In most cases, the vectorizable loops are loops that iterate over arrays.
10950 All kinds of array types are supported, i.e. constrained array types with
10951 static bounds:
10953 @smallexample @c ada
10954    type Array_Type is array (1 .. 4) of Long_Float;
10955 @end smallexample
10957 @noindent
10958 constrained array types with dynamic bounds:
10960 @smallexample @c ada
10961    type Array_Type is array (1 .. Q.N) of Long_Float;
10963    type Array_Type is array (Q.K .. 4) of Long_Float;
10965    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10966 @end smallexample
10968 @noindent
10969 or unconstrained array types:
10971 @smallexample @c ada
10972   type Array_Type is array (Positive range <>) of Long_Float;
10973 @end smallexample
10975 @noindent
10976 The quality of the generated code decreases when the dynamic aspect of the
10977 array type increases, the worst code being generated for unconstrained array
10978 types.  This is so because, the less information the compiler has about the
10979 bounds of the array, the more fallback code it needs to generate in order to
10980 fix things up at run time.
10982 It is possible to specify that a given loop should be subject to vectorization
10983 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10985 @smallexample @c ada
10986   pragma Loop_Optimize (Vector);
10987 @end smallexample
10989 @noindent
10990 placed immediately within the loop will convey the appropriate hint to the
10991 compiler for this loop.
10993 You can obtain information about the vectorization performed by the compiler
10994 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10995 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10996 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10998 @node Other Optimization Switches
10999 @subsection Other Optimization Switches
11000 @cindex Optimization Switches
11002 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
11003 @command{gcc} optimization switches are potentially usable. These switches
11004 have not been extensively tested with GNAT but can generally be expected
11005 to work. Examples of switches in this category are @option{-funroll-loops}
11006 and the various target-specific @option{-m} options (in particular, it has
11007 been observed that @option{-march=xxx} can significantly improve performance
11008 on appropriate machines). For full details of these switches, see
11009 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
11010 the GNU Compiler Collection (GCC)}.
11012 @node Optimization and Strict Aliasing
11013 @subsection Optimization and Strict Aliasing
11014 @cindex Aliasing
11015 @cindex Strict Aliasing
11016 @cindex No_Strict_Aliasing
11018 @noindent
11019 The strong typing capabilities of Ada allow an optimizer to generate
11020 efficient code in situations where other languages would be forced to
11021 make worst case assumptions preventing such optimizations. Consider
11022 the following example:
11024 @smallexample @c ada
11025 @cartouche
11026 procedure R is
11027    type Int1 is new Integer;
11028    type Int2 is new Integer;
11029    type Int1A is access Int1;
11030    type Int2A is access Int2;
11031    Int1V : Int1A;
11032    Int2V : Int2A;
11033    @dots{}
11035 begin
11036    @dots{}
11037    for J in Data'Range loop
11038       if Data (J) = Int1V.all then
11039          Int2V.all := Int2V.all + 1;
11040       end if;
11041    end loop;
11042    @dots{}
11043 end R;
11044 @end cartouche
11045 @end smallexample
11047 @noindent
11048 In this example, since the variable @code{Int1V} can only access objects
11049 of type @code{Int1}, and @code{Int2V} can only access objects of type
11050 @code{Int2}, there is no possibility that the assignment to
11051 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
11052 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
11053 for all iterations of the loop and avoid the extra memory reference
11054 required to dereference it each time through the loop.
11056 This kind of optimization, called strict aliasing analysis, is
11057 triggered by specifying an optimization level of @option{-O2} or
11058 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
11059 when access values are involved.
11061 However, although this optimization is always correct in terms of
11062 the formal semantics of the Ada Reference Manual, difficulties can
11063 arise if features like @code{Unchecked_Conversion} are used to break
11064 the typing system. Consider the following complete program example:
11066 @smallexample @c ada
11067 @cartouche
11068 package p1 is
11069    type int1 is new integer;
11070    type int2 is new integer;
11071    type a1 is access int1;
11072    type a2 is access int2;
11073 end p1;
11075 with p1; use p1;
11076 package p2 is
11077    function to_a2 (Input : a1) return a2;
11078 end p2;
11080 with Unchecked_Conversion;
11081 package body p2 is
11082    function to_a2 (Input : a1) return a2 is
11083       function to_a2u is
11084         new Unchecked_Conversion (a1, a2);
11085    begin
11086       return to_a2u (Input);
11087    end to_a2;
11088 end p2;
11090 with p2; use p2;
11091 with p1; use p1;
11092 with Text_IO; use Text_IO;
11093 procedure m is
11094    v1 : a1 := new int1;
11095    v2 : a2 := to_a2 (v1);
11096 begin
11097    v1.all := 1;
11098    v2.all := 0;
11099    put_line (int1'image (v1.all));
11100 end;
11101 @end cartouche
11102 @end smallexample
11104 @noindent
11105 This program prints out 0 in @option{-O0} or @option{-O1}
11106 mode, but it prints out 1 in @option{-O2} mode. That's
11107 because in strict aliasing mode, the compiler can and
11108 does assume that the assignment to @code{v2.all} could not
11109 affect the value of @code{v1.all}, since different types
11110 are involved.
11112 This behavior is not a case of non-conformance with the standard, since
11113 the Ada RM specifies that an unchecked conversion where the resulting
11114 bit pattern is not a correct value of the target type can result in an
11115 abnormal value and attempting to reference an abnormal value makes the
11116 execution of a program erroneous.  That's the case here since the result
11117 does not point to an object of type @code{int2}.  This means that the
11118 effect is entirely unpredictable.
11120 However, although that explanation may satisfy a language
11121 lawyer, in practice an applications programmer expects an
11122 unchecked conversion involving pointers to create true
11123 aliases and the behavior of printing 1 seems plain wrong.
11124 In this case, the strict aliasing optimization is unwelcome.
11126 Indeed the compiler recognizes this possibility, and the
11127 unchecked conversion generates a warning:
11129 @smallexample
11130 p2.adb:5:07: warning: possible aliasing problem with type "a2"
11131 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
11132 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
11133 @end smallexample
11135 @noindent
11136 Unfortunately the problem is recognized when compiling the body of
11137 package @code{p2}, but the actual "bad" code is generated while
11138 compiling the body of @code{m} and this latter compilation does not see
11139 the suspicious @code{Unchecked_Conversion}.
11141 As implied by the warning message, there are approaches you can use to
11142 avoid the unwanted strict aliasing optimization in a case like this.
11144 One possibility is to simply avoid the use of @option{-O2}, but
11145 that is a bit drastic, since it throws away a number of useful
11146 optimizations that do not involve strict aliasing assumptions.
11148 A less drastic approach is to compile the program using the
11149 option @option{-fno-strict-aliasing}. Actually it is only the
11150 unit containing the dereferencing of the suspicious pointer
11151 that needs to be compiled. So in this case, if we compile
11152 unit @code{m} with this switch, then we get the expected
11153 value of zero printed. Analyzing which units might need
11154 the switch can be painful, so a more reasonable approach
11155 is to compile the entire program with options @option{-O2}
11156 and @option{-fno-strict-aliasing}. If the performance is
11157 satisfactory with this combination of options, then the
11158 advantage is that the entire issue of possible "wrong"
11159 optimization due to strict aliasing is avoided.
11161 To avoid the use of compiler switches, the configuration
11162 pragma @code{No_Strict_Aliasing} with no parameters may be
11163 used to specify that for all access types, the strict
11164 aliasing optimization should be suppressed.
11166 However, these approaches are still overkill, in that they causes
11167 all manipulations of all access values to be deoptimized. A more
11168 refined approach is to concentrate attention on the specific
11169 access type identified as problematic.
11171 First, if a careful analysis of uses of the pointer shows
11172 that there are no possible problematic references, then
11173 the warning can be suppressed by bracketing the
11174 instantiation of @code{Unchecked_Conversion} to turn
11175 the warning off:
11177 @smallexample @c ada
11178    pragma Warnings (Off);
11179    function to_a2u is
11180      new Unchecked_Conversion (a1, a2);
11181    pragma Warnings (On);
11182 @end smallexample
11184 @noindent
11185 Of course that approach is not appropriate for this particular
11186 example, since indeed there is a problematic reference. In this
11187 case we can take one of two other approaches.
11189 The first possibility is to move the instantiation of unchecked
11190 conversion to the unit in which the type is declared. In
11191 this example, we would move the instantiation of
11192 @code{Unchecked_Conversion} from the body of package
11193 @code{p2} to the spec of package @code{p1}. Now the
11194 warning disappears. That's because any use of the
11195 access type knows there is a suspicious unchecked
11196 conversion, and the strict aliasing optimization
11197 is automatically suppressed for the type.
11199 If it is not practical to move the unchecked conversion to the same unit
11200 in which the destination access type is declared (perhaps because the
11201 source type is not visible in that unit), you may use pragma
11202 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11203 same declarative sequence as the declaration of the access type:
11205 @smallexample @c ada
11206    type a2 is access int2;
11207    pragma No_Strict_Aliasing (a2);
11208 @end smallexample
11210 @noindent
11211 Here again, the compiler now knows that the strict aliasing optimization
11212 should be suppressed for any reference to type @code{a2} and the
11213 expected behavior is obtained.
11215 Finally, note that although the compiler can generate warnings for
11216 simple cases of unchecked conversions, there are tricker and more
11217 indirect ways of creating type incorrect aliases which the compiler
11218 cannot detect. Examples are the use of address overlays and unchecked
11219 conversions involving composite types containing access types as
11220 components. In such cases, no warnings are generated, but there can
11221 still be aliasing problems. One safe coding practice is to forbid the
11222 use of address clauses for type overlaying, and to allow unchecked
11223 conversion only for primitive types. This is not really a significant
11224 restriction since any possible desired effect can be achieved by
11225 unchecked conversion of access values.
11227 The aliasing analysis done in strict aliasing mode can certainly
11228 have significant benefits. We have seen cases of large scale
11229 application code where the time is increased by up to 5% by turning
11230 this optimization off. If you have code that includes significant
11231 usage of unchecked conversion, you might want to just stick with
11232 @option{-O1} and avoid the entire issue. If you get adequate
11233 performance at this level of optimization level, that's probably
11234 the safest approach. If tests show that you really need higher
11235 levels of optimization, then you can experiment with @option{-O2}
11236 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11237 has on size and speed of the code. If you really need to use
11238 @option{-O2} with strict aliasing in effect, then you should
11239 review any uses of unchecked conversion of access types,
11240 particularly if you are getting the warnings described above.
11242 @ifset vms
11243 @node Coverage Analysis
11244 @subsection Coverage Analysis
11246 @noindent
11247 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11248 the user to determine the distribution of execution time across a program,
11249 @pxref{Profiling} for details of usage.
11250 @end ifset
11253 @node Text_IO Suggestions
11254 @section @code{Text_IO} Suggestions
11255 @cindex @code{Text_IO} and performance
11257 @noindent
11258 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11259 the requirement of maintaining page and line counts. If performance
11260 is critical, a recommendation is to use @code{Stream_IO} instead of
11261 @code{Text_IO} for volume output, since this package has less overhead.
11263 If @code{Text_IO} must be used, note that by default output to the standard
11264 output and standard error files is unbuffered (this provides better
11265 behavior when output statements are used for debugging, or if the
11266 progress of a program is observed by tracking the output, e.g. by
11267 using the Unix @command{tail -f} command to watch redirected output.
11269 If you are generating large volumes of output with @code{Text_IO} and
11270 performance is an important factor, use a designated file instead
11271 of the standard output file, or change the standard output file to
11272 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11276 @node Reducing Size of Ada Executables with gnatelim
11277 @section Reducing Size of Ada Executables with @code{gnatelim}
11278 @findex gnatelim
11280 @noindent
11281 This section describes @command{gnatelim}, a tool which detects unused
11282 subprograms and helps the compiler to create a smaller executable for your
11283 program.
11285 @menu
11286 * About gnatelim::
11287 * Running gnatelim::
11288 * Processing Precompiled Libraries::
11289 * Correcting the List of Eliminate Pragmas::
11290 * Making Your Executables Smaller::
11291 * Summary of the gnatelim Usage Cycle::
11292 @end menu
11294 @node About gnatelim
11295 @subsection About @code{gnatelim}
11297 @noindent
11298 When a program shares a set of Ada
11299 packages with other programs, it may happen that this program uses
11300 only a fraction of the subprograms defined in these packages. The code
11301 created for these unused subprograms increases the size of the executable.
11303 @code{gnatelim} tracks unused subprograms in an Ada program and
11304 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11305 subprograms that are declared but never called. By placing the list of
11306 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11307 recompiling your program, you may decrease the size of its executable,
11308 because the compiler will not generate the code for 'eliminated' subprograms.
11309 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11310 information about this pragma.
11312 @code{gnatelim} needs as its input data the name of the main subprogram.
11314 If a set of source files is specified as @code{gnatelim} arguments, it
11315 treats these files as a complete set of sources making up a program to
11316 analyse, and analyses only these sources.
11318 After a full successful build of the main subprogram @code{gnatelim} can be
11319 called without  specifying sources to analyse, in this case it computes
11320 the source closure of the main unit from the @file{ALI} files.
11322 The following command will create the set of @file{ALI} files needed for
11323 @code{gnatelim}:
11325 @smallexample
11326 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11327 @end smallexample
11329 Note that @code{gnatelim} does not need object files.
11331 @node Running gnatelim
11332 @subsection Running @code{gnatelim}
11334 @noindent
11335 @code{gnatelim} has the following command-line interface:
11337 @smallexample
11338 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11339 @end smallexample
11341 @noindent
11342 @var{main_unit_name} should be a name of a source file that contains the main
11343 subprogram of a program (partition).
11345 Each @var{filename} is the name (including the extension) of a source
11346 file to process. ``Wildcards'' are allowed, and
11347 the file name may contain path information.
11349 @samp{@var{gcc_switches}} is a list of switches for
11350 @command{gcc}. They will be passed on to all compiler invocations made by
11351 @command{gnatelim} to generate the ASIS trees. Here you can provide
11352 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11353 use the @option{-gnatec} switch to set the configuration file,
11354 use the @option{-gnat05} switch if sources should be compiled in
11355 Ada 2005 mode etc.
11357 @code{gnatelim} has the following switches:
11359 @table @option
11360 @c !sort!
11361 @item ^-files^/FILES^=@var{filename}
11362 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11363 Take the argument source files from the specified file. This file should be an
11364 ordinary text file containing file names separated by spaces or
11365 line breaks. You can use this switch more than once in the same call to
11366 @command{gnatelim}. You also can combine this switch with
11367 an explicit list of files.
11369 @item ^-log^/LOG^
11370 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11371 Duplicate all the output sent to @file{stderr} into a log file. The log file
11372 is named @file{gnatelim.log} and is located in the current directory.
11374 @item ^-log^/LOGFILE^=@var{filename}
11375 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11376 Duplicate all the output sent to @file{stderr} into a specified log file.
11378 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11379 @item ^--no-elim-dispatch^/NO_DISPATCH^
11380 Do not generate pragmas for dispatching operations.
11382 @item ^--ignore^/IGNORE^=@var{filename}
11383 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11384 Do not generate pragmas for subprograms declared in the sources
11385 listed in a specified file
11387 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11388 @item ^-o^/OUTPUT^=@var{report_file}
11389 Put @command{gnatelim} output into a specified file. If this file already exists,
11390 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11391 into @file{stderr}
11393 @item ^-q^/QUIET^
11394 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11395 Quiet mode: by default @code{gnatelim} outputs to the standard error
11396 stream the number of program units left to be processed. This option turns
11397 this trace off.
11399 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11400 @item ^-t^/TIME^
11401 Print out execution time.
11403 @item ^-v^/VERBOSE^
11404 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11405 Verbose mode: @code{gnatelim} version information is printed as Ada
11406 comments to the standard output stream. Also, in addition to the number of
11407 program units left @code{gnatelim} will output the name of the current unit
11408 being processed.
11410 @item ^-wq^/WARNINGS=QUIET^
11411 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11412 Quiet warning mode - some warnings are suppressed. In particular warnings that
11413 indicate that the analysed set of sources is incomplete to make up a
11414 partition and that some subprogram bodies are missing are not generated.
11415 @end table
11417 @noindent
11418 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11419 driver (see @ref{The GNAT Driver and Project Files}).
11421 @node Processing Precompiled Libraries
11422 @subsection Processing Precompiled Libraries
11424 @noindent
11425 If some program uses a precompiled Ada library, it can be processed by
11426 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11427 Eliminate pragma for a subprogram if the body of this subprogram has not
11428 been analysed, this is a typical case for subprograms from precompiled
11429 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11430 warnings about missing source files and non-analyzed subprogram bodies
11431 that can be generated when processing precompiled Ada libraries.
11433 @node Correcting the List of Eliminate Pragmas
11434 @subsection Correcting the List of Eliminate Pragmas
11436 @noindent
11437 In some rare cases @code{gnatelim} may try to eliminate
11438 subprograms that are actually called in the program. In this case, the
11439 compiler will generate an error message of the form:
11441 @smallexample
11442 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11443 @end smallexample
11445 @noindent
11446 You will need to manually remove the wrong @code{Eliminate} pragmas from
11447 the configuration file indicated in the error message. You should recompile
11448 your program from scratch after that, because you need a consistent
11449 configuration file(s) during the entire compilation.
11451 @node Making Your Executables Smaller
11452 @subsection Making Your Executables Smaller
11454 @noindent
11455 In order to get a smaller executable for your program you now have to
11456 recompile the program completely with the configuration file containing
11457 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11458 @file{gnat.adc} file located in your current directory, just do:
11460 @smallexample
11461 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11462 @end smallexample
11464 @noindent
11465 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11466 recompile everything
11467 with the set of pragmas @code{Eliminate} that you have obtained with
11468 @command{gnatelim}).
11470 Be aware that the set of @code{Eliminate} pragmas is specific to each
11471 program. It is not recommended to merge sets of @code{Eliminate}
11472 pragmas created for different programs in one configuration file.
11474 @node Summary of the gnatelim Usage Cycle
11475 @subsection Summary of the @code{gnatelim} Usage Cycle
11477 @noindent
11478 Here is a quick summary of the steps to be taken in order to reduce
11479 the size of your executables with @code{gnatelim}. You may use
11480 other GNAT options to control the optimization level,
11481 to produce the debugging information, to set search path, etc.
11483 @enumerate
11484 @item
11485 Create a complete set of @file{ALI} files (if the program has not been
11486 built already)
11488 @smallexample
11489 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11490 @end smallexample
11492 @item
11493 Generate a list of @code{Eliminate} pragmas in default configuration file
11494 @file{gnat.adc} in the current directory
11495 @smallexample
11496 @ifset vms
11497 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11498 @end ifset
11499 @ifclear vms
11500 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11501 @end ifclear
11502 @end smallexample
11504 @item
11505 Recompile the application
11507 @smallexample
11508 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11509 @end smallexample
11511 @end enumerate
11513 @node Reducing Size of Executables with unused subprogram/data elimination
11514 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11515 @findex unused subprogram/data elimination
11517 @noindent
11518 This section describes how you can eliminate unused subprograms and data from
11519 your executable just by setting options at compilation time.
11521 @menu
11522 * About unused subprogram/data elimination::
11523 * Compilation options::
11524 * Example of unused subprogram/data elimination::
11525 @end menu
11527 @node About unused subprogram/data elimination
11528 @subsection About unused subprogram/data elimination
11530 @noindent
11531 By default, an executable contains all code and data of its composing objects
11532 (directly linked or coming from statically linked libraries), even data or code
11533 never used by this executable.
11535 This feature will allow you to eliminate such unused code from your
11536 executable, making it smaller (in disk and in memory).
11538 This functionality is available on all Linux platforms except for the IA-64
11539 architecture and on all cross platforms using the ELF binary file format.
11540 In both cases GNU binutils version 2.16 or later are required to enable it.
11542 @node Compilation options
11543 @subsection Compilation options
11545 @noindent
11546 The operation of eliminating the unused code and data from the final executable
11547 is directly performed by the linker.
11549 In order to do this, it has to work with objects compiled with the
11550 following options:
11551 @option{-ffunction-sections} @option{-fdata-sections}.
11552 @cindex @option{-ffunction-sections} (@command{gcc})
11553 @cindex @option{-fdata-sections} (@command{gcc})
11554 These options are usable with C and Ada files.
11555 They will place respectively each
11556 function or data in a separate section in the resulting object file.
11558 Once the objects and static libraries are created with these options, the
11559 linker can perform the dead code elimination. You can do this by setting
11560 the @option{-Wl,--gc-sections} option to gcc command or in the
11561 @option{-largs} section of @command{gnatmake}. This will perform a
11562 garbage collection of code and data never referenced.
11564 If the linker performs a partial link (@option{-r} ld linker option), then you
11565 will need to provide one or several entry point using the
11566 @option{-e} / @option{--entry} ld option.
11568 Note that objects compiled without the @option{-ffunction-sections} and
11569 @option{-fdata-sections} options can still be linked with the executable.
11570 However, no dead code elimination will be performed on those objects (they will
11571 be linked as is).
11573 The GNAT static library is now compiled with -ffunction-sections and
11574 -fdata-sections on some platforms. This allows you to eliminate the unused code
11575 and data of the GNAT library from your executable.
11577 @node Example of unused subprogram/data elimination
11578 @subsection Example of unused subprogram/data elimination
11580 @noindent
11581 Here is a simple example:
11583 @smallexample @c ada
11584 with Aux;
11586 procedure Test is
11587 begin
11588    Aux.Used (10);
11589 end Test;
11591 package Aux is
11592    Used_Data   : Integer;
11593    Unused_Data : Integer;
11595    procedure Used   (Data : Integer);
11596    procedure Unused (Data : Integer);
11597 end Aux;
11599 package body Aux is
11600    procedure Used (Data : Integer) is
11601    begin
11602       Used_Data := Data;
11603    end Used;
11605    procedure Unused (Data : Integer) is
11606    begin
11607       Unused_Data := Data;
11608    end Unused;
11609 end Aux;
11610 @end smallexample
11612 @noindent
11613 @code{Unused} and @code{Unused_Data} are never referenced in this code
11614 excerpt, and hence they may be safely removed from the final executable.
11616 @smallexample
11617 $ gnatmake test
11619 $ nm test | grep used
11620 020015f0 T aux__unused
11621 02005d88 B aux__unused_data
11622 020015cc T aux__used
11623 02005d84 B aux__used_data
11625 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11626      -largs -Wl,--gc-sections
11628 $ nm test | grep used
11629 02005350 T aux__used
11630 0201ffe0 B aux__used_data
11631 @end smallexample
11633 @noindent
11634 It can be observed that the procedure @code{Unused} and the object
11635 @code{Unused_Data} are removed by the linker when using the
11636 appropriate options.
11638 @c ********************************
11639 @node Renaming Files Using gnatchop
11640 @chapter Renaming Files Using @code{gnatchop}
11641 @findex gnatchop
11643 @noindent
11644 This chapter discusses how to handle files with multiple units by using
11645 the @code{gnatchop} utility. This utility is also useful in renaming
11646 files to meet the standard GNAT default file naming conventions.
11648 @menu
11649 * Handling Files with Multiple Units::
11650 * Operating gnatchop in Compilation Mode::
11651 * Command Line for gnatchop::
11652 * Switches for gnatchop::
11653 * Examples of gnatchop Usage::
11654 @end menu
11656 @node Handling Files with Multiple Units
11657 @section Handling Files with Multiple Units
11659 @noindent
11660 The basic compilation model of GNAT requires that a file submitted to the
11661 compiler have only one unit and there be a strict correspondence
11662 between the file name and the unit name.
11664 The @code{gnatchop} utility allows both of these rules to be relaxed,
11665 allowing GNAT to process files which contain multiple compilation units
11666 and files with arbitrary file names. @code{gnatchop}
11667 reads the specified file and generates one or more output files,
11668 containing one unit per file. The unit and the file name correspond,
11669 as required by GNAT.
11671 If you want to permanently restructure a set of ``foreign'' files so that
11672 they match the GNAT rules, and do the remaining development using the
11673 GNAT structure, you can simply use @command{gnatchop} once, generate the
11674 new set of files and work with them from that point on.
11676 Alternatively, if you want to keep your files in the ``foreign'' format,
11677 perhaps to maintain compatibility with some other Ada compilation
11678 system, you can set up a procedure where you use @command{gnatchop} each
11679 time you compile, regarding the source files that it writes as temporary
11680 files that you throw away.
11682 Note that if your file containing multiple units starts with a byte order
11683 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11684 will each start with a copy of this BOM, meaning that they can be compiled
11685 automatically in UTF-8 mode without needing to specify an explicit encoding.
11687 @node Operating gnatchop in Compilation Mode
11688 @section Operating gnatchop in Compilation Mode
11690 @noindent
11691 The basic function of @code{gnatchop} is to take a file with multiple units
11692 and split it into separate files. The boundary between files is reasonably
11693 clear, except for the issue of comments and pragmas. In default mode, the
11694 rule is that any pragmas between units belong to the previous unit, except
11695 that configuration pragmas always belong to the following unit. Any comments
11696 belong to the following unit. These rules
11697 almost always result in the right choice of
11698 the split point without needing to mark it explicitly and most users will
11699 find this default to be what they want. In this default mode it is incorrect to
11700 submit a file containing only configuration pragmas, or one that ends in
11701 configuration pragmas, to @code{gnatchop}.
11703 However, using a special option to activate ``compilation mode'',
11704 @code{gnatchop}
11705 can perform another function, which is to provide exactly the semantics
11706 required by the RM for handling of configuration pragmas in a compilation.
11707 In the absence of configuration pragmas (at the main file level), this
11708 option has no effect, but it causes such configuration pragmas to be handled
11709 in a quite different manner.
11711 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11712 only configuration pragmas, then this file is appended to the
11713 @file{gnat.adc} file in the current directory. This behavior provides
11714 the required behavior described in the RM for the actions to be taken
11715 on submitting such a file to the compiler, namely that these pragmas
11716 should apply to all subsequent compilations in the same compilation
11717 environment. Using GNAT, the current directory, possibly containing a
11718 @file{gnat.adc} file is the representation
11719 of a compilation environment. For more information on the
11720 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11722 Second, in compilation mode, if @code{gnatchop}
11723 is given a file that starts with
11724 configuration pragmas, and contains one or more units, then these
11725 configuration pragmas are prepended to each of the chopped files. This
11726 behavior provides the required behavior described in the RM for the
11727 actions to be taken on compiling such a file, namely that the pragmas
11728 apply to all units in the compilation, but not to subsequently compiled
11729 units.
11731 Finally, if configuration pragmas appear between units, they are appended
11732 to the previous unit. This results in the previous unit being illegal,
11733 since the compiler does not accept configuration pragmas that follow
11734 a unit. This provides the required RM behavior that forbids configuration
11735 pragmas other than those preceding the first compilation unit of a
11736 compilation.
11738 For most purposes, @code{gnatchop} will be used in default mode. The
11739 compilation mode described above is used only if you need exactly
11740 accurate behavior with respect to compilations, and you have files
11741 that contain multiple units and configuration pragmas. In this
11742 circumstance the use of @code{gnatchop} with the compilation mode
11743 switch provides the required behavior, and is for example the mode
11744 in which GNAT processes the ACVC tests.
11746 @node Command Line for gnatchop
11747 @section Command Line for @code{gnatchop}
11749 @noindent
11750 The @code{gnatchop} command has the form:
11752 @smallexample
11753 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11754 @c      @ovar{directory}
11755 @c Expanding @ovar macro inline (explanation in macro def comments)
11756 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11757       @r{[}@var{directory}@r{]}
11758 @end smallexample
11760 @noindent
11761 The only required argument is the file name of the file to be chopped.
11762 There are no restrictions on the form of this file name. The file itself
11763 contains one or more Ada units, in normal GNAT format, concatenated
11764 together. As shown, more than one file may be presented to be chopped.
11766 When run in default mode, @code{gnatchop} generates one output file in
11767 the current directory for each unit in each of the files.
11769 @var{directory}, if specified, gives the name of the directory to which
11770 the output files will be written. If it is not specified, all files are
11771 written to the current directory.
11773 For example, given a
11774 file called @file{hellofiles} containing
11776 @smallexample @c ada
11777 @group
11778 @cartouche
11779 procedure hello;
11781 with Text_IO; use Text_IO;
11782 procedure hello is
11783 begin
11784    Put_Line ("Hello");
11785 end hello;
11786 @end cartouche
11787 @end group
11788 @end smallexample
11790 @noindent
11791 the command
11793 @smallexample
11794 $ gnatchop ^hellofiles^HELLOFILES.^
11795 @end smallexample
11797 @noindent
11798 generates two files in the current directory, one called
11799 @file{hello.ads} containing the single line that is the procedure spec,
11800 and the other called @file{hello.adb} containing the remaining text. The
11801 original file is not affected. The generated files can be compiled in
11802 the normal manner.
11804 @noindent
11805 When gnatchop is invoked on a file that is empty or that contains only empty
11806 lines and/or comments, gnatchop will not fail, but will not produce any
11807 new sources.
11809 For example, given a
11810 file called @file{toto.txt} containing
11812 @smallexample @c ada
11813 @group
11814 @cartouche
11815 --  Just a comment
11816 @end cartouche
11817 @end group
11818 @end smallexample
11820 @noindent
11821 the command
11823 @smallexample
11824 $ gnatchop ^toto.txt^TOT.TXT^
11825 @end smallexample
11827 @noindent
11828 will not produce any new file and will result in the following warnings:
11830 @smallexample
11831 toto.txt:1:01: warning: empty file, contains no compilation units
11832 no compilation units found
11833 no source files written
11834 @end smallexample
11836 @node Switches for gnatchop
11837 @section Switches for @code{gnatchop}
11839 @noindent
11840 @command{gnatchop} recognizes the following switches:
11842 @table @option
11843 @c !sort!
11845 @item --version
11846 @cindex @option{--version} @command{gnatchop}
11847 Display Copyright and version, then exit disregarding all other options.
11849 @item --help
11850 @cindex @option{--help} @command{gnatchop}
11851 If @option{--version} was not used, display usage, then exit disregarding
11852 all other options.
11854 @item ^-c^/COMPILATION^
11855 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11856 Causes @code{gnatchop} to operate in compilation mode, in which
11857 configuration pragmas are handled according to strict RM rules. See
11858 previous section for a full description of this mode.
11860 @ifclear vms
11861 @item -gnat@var{xxx}
11862 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11863 used to parse the given file. Not all @var{xxx} options make sense,
11864 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11865 process a source file that uses Latin-2 coding for identifiers.
11866 @end ifclear
11868 @item ^-h^/HELP^
11869 Causes @code{gnatchop} to generate a brief help summary to the standard
11870 output file showing usage information.
11872 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11873 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11874 Limit generated file names to the specified number @code{mm}
11875 of characters.
11876 This is useful if the
11877 resulting set of files is required to be interoperable with systems
11878 which limit the length of file names.
11879 @ifset vms
11880 If no value is given, or
11881 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11882 a default of 39, suitable for OpenVMS Alpha
11883 Systems, is assumed
11884 @end ifset
11885 @ifclear vms
11886 No space is allowed between the @option{-k} and the numeric value. The numeric
11887 value may be omitted in which case a default of @option{-k8},
11888 suitable for use
11889 with DOS-like file systems, is used. If no @option{-k} switch
11890 is present then
11891 there is no limit on the length of file names.
11892 @end ifclear
11894 @item ^-p^/PRESERVE^
11895 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11896 Causes the file ^modification^creation^ time stamp of the input file to be
11897 preserved and used for the time stamp of the output file(s). This may be
11898 useful for preserving coherency of time stamps in an environment where
11899 @code{gnatchop} is used as part of a standard build process.
11901 @item ^-q^/QUIET^
11902 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11903 Causes output of informational messages indicating the set of generated
11904 files to be suppressed. Warnings and error messages are unaffected.
11906 @item ^-r^/REFERENCE^
11907 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11908 @findex Source_Reference
11909 Generate @code{Source_Reference} pragmas. Use this switch if the output
11910 files are regarded as temporary and development is to be done in terms
11911 of the original unchopped file. This switch causes
11912 @code{Source_Reference} pragmas to be inserted into each of the
11913 generated files to refers back to the original file name and line number.
11914 The result is that all error messages refer back to the original
11915 unchopped file.
11916 In addition, the debugging information placed into the object file (when
11917 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11918 specified)
11919 also refers back to this original file so that tools like profilers and
11920 debuggers will give information in terms of the original unchopped file.
11922 If the original file to be chopped itself contains
11923 a @code{Source_Reference}
11924 pragma referencing a third file, then gnatchop respects
11925 this pragma, and the generated @code{Source_Reference} pragmas
11926 in the chopped file refer to the original file, with appropriate
11927 line numbers. This is particularly useful when @code{gnatchop}
11928 is used in conjunction with @code{gnatprep} to compile files that
11929 contain preprocessing statements and multiple units.
11931 @item ^-v^/VERBOSE^
11932 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11933 Causes @code{gnatchop} to operate in verbose mode. The version
11934 number and copyright notice are output, as well as exact copies of
11935 the gnat1 commands spawned to obtain the chop control information.
11937 @item ^-w^/OVERWRITE^
11938 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11939 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11940 fatal error if there is already a file with the same name as a
11941 file it would otherwise output, in other words if the files to be
11942 chopped contain duplicated units. This switch bypasses this
11943 check, and causes all but the last instance of such duplicated
11944 units to be skipped.
11946 @ifclear vms
11947 @item --GCC=@var{xxxx}
11948 @cindex @option{--GCC=} (@code{gnatchop})
11949 Specify the path of the GNAT parser to be used. When this switch is used,
11950 no attempt is made to add the prefix to the GNAT parser executable.
11951 @end ifclear
11952 @end table
11954 @node Examples of gnatchop Usage
11955 @section Examples of @code{gnatchop} Usage
11957 @table @code
11958 @ifset vms
11959 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11960 @end ifset
11961 @ifclear vms
11962 @item gnatchop -w hello_s.ada prerelease/files
11963 @end ifclear
11965 Chops the source file @file{hello_s.ada}. The output files will be
11966 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11967 overwriting any
11968 files with matching names in that directory (no files in the current
11969 directory are modified).
11971 @item gnatchop ^archive^ARCHIVE.^
11972 Chops the source file @file{^archive^ARCHIVE.^}
11973 into the current directory. One
11974 useful application of @code{gnatchop} is in sending sets of sources
11975 around, for example in email messages. The required sources are simply
11976 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11977 command), and then
11978 @command{gnatchop} is used at the other end to reconstitute the original
11979 file names.
11981 @item gnatchop file1 file2 file3 direc
11982 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11983 the resulting files in the directory @file{direc}. Note that if any units
11984 occur more than once anywhere within this set of files, an error message
11985 is generated, and no files are written. To override this check, use the
11986 @option{^-w^/OVERWRITE^} switch,
11987 in which case the last occurrence in the last file will
11988 be the one that is output, and earlier duplicate occurrences for a given
11989 unit will be skipped.
11990 @end table
11992 @node Configuration Pragmas
11993 @chapter Configuration Pragmas
11994 @cindex Configuration pragmas
11995 @cindex Pragmas, configuration
11997 @noindent
11998 Configuration pragmas include those pragmas described as
11999 such in the Ada Reference Manual, as well as
12000 implementation-dependent pragmas that are configuration pragmas.
12001 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
12002 for details on these additional GNAT-specific configuration pragmas.
12003 Most notably, the pragma @code{Source_File_Name}, which allows
12004 specifying non-default names for source files, is a configuration
12005 pragma. The following is a complete list of configuration pragmas
12006 recognized by GNAT:
12008 @smallexample
12009    Ada_83
12010    Ada_95
12011    Ada_05
12012    Ada_2005
12013    Ada_12
12014    Ada_2012
12015    Annotate
12016    Assertion_Policy
12017    Assume_No_Invalid_Values
12018    C_Pass_By_Copy
12019    Check_Name
12020    Check_Policy
12021    Compile_Time_Error
12022    Compile_Time_Warning
12023    Compiler_Unit
12024    Component_Alignment
12025    Convention_Identifier
12026    Debug_Policy
12027    Detect_Blocking
12028    Default_Storage_Pool
12029    Discard_Names
12030    Elaboration_Checks
12031    Eliminate
12032    Extend_System
12033    Extensions_Allowed
12034    External_Name_Casing
12035    Fast_Math
12036    Favor_Top_Level
12037    Float_Representation
12038    Implicit_Packing
12039    Initialize_Scalars
12040    Interrupt_State
12041    License
12042    Locking_Policy
12043    Long_Float
12044    No_Run_Time
12045    No_Strict_Aliasing
12046    Normalize_Scalars
12047    Optimize_Alignment
12048    Persistent_BSS
12049    Polling
12050    Priority_Specific_Dispatching
12051    Profile
12052    Profile_Warnings
12053    Propagate_Exceptions
12054    Queuing_Policy
12055    Ravenscar
12056    Restricted_Run_Time
12057    Restrictions
12058    Restrictions_Warnings
12059    Reviewable
12060    Short_Circuit_And_Or
12061    Source_File_Name
12062    Source_File_Name_Project
12063    Style_Checks
12064    Suppress
12065    Suppress_Exception_Locations
12066    Task_Dispatching_Policy
12067    Universal_Data
12068    Unsuppress
12069    Use_VADS_Size
12070    Validity_Checks
12071    Warnings
12072    Wide_Character_Encoding
12074 @end smallexample
12076 @menu
12077 * Handling of Configuration Pragmas::
12078 * The Configuration Pragmas Files::
12079 @end menu
12081 @node Handling of Configuration Pragmas
12082 @section Handling of Configuration Pragmas
12084 Configuration pragmas may either appear at the start of a compilation
12085 unit, or they can appear in a configuration pragma file to apply to
12086 all compilations performed in a given compilation environment.
12088 GNAT also provides the @code{gnatchop} utility to provide an automatic
12089 way to handle configuration pragmas following the semantics for
12090 compilations (that is, files with multiple units), described in the RM.
12091 See @ref{Operating gnatchop in Compilation Mode} for details.
12092 However, for most purposes, it will be more convenient to edit the
12093 @file{gnat.adc} file that contains configuration pragmas directly,
12094 as described in the following section.
12096 In the case of @code{Restrictions} pragmas appearing as configuration
12097 pragmas in individual compilation units, the exact handling depends on
12098 the type of restriction.
12100 Restrictions that require partition-wide consistency (like
12101 @code{No_Tasking}) are
12102 recognized wherever they appear
12103 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12104 unit. This makes sense since the binder will in any case insist on seeing
12105 consistent use, so any unit not conforming to any restrictions that are
12106 anywhere in the partition will be rejected, and you might as well find
12107 that out at compile time rather than at bind time.
12109 For restrictions that do not require partition-wide consistency, e.g.
12110 SPARK or No_Implementation_Attributes, in general the restriction applies
12111 only to the unit in which the pragma appears, and not to any other units.
12113 The exception is No_Elaboration_Code which always applies to the entire
12114 object file from a compilation, i.e. to the body, spec, and all subunits.
12115 This restriction can be specified in a configuration pragma file, or it
12116 can be on the body and/or the spec (in eithe case it applies to all the
12117 relevant units). It can appear on a subunit only if it has previously
12118 appeared in the body of spec.
12120 @node The Configuration Pragmas Files
12121 @section The Configuration Pragmas Files
12122 @cindex @file{gnat.adc}
12124 @noindent
12125 In GNAT a compilation environment is defined by the current
12126 directory at the time that a compile command is given. This current
12127 directory is searched for a file whose name is @file{gnat.adc}. If
12128 this file is present, it is expected to contain one or more
12129 configuration pragmas that will be applied to the current compilation.
12130 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12131 considered.
12133 Configuration pragmas may be entered into the @file{gnat.adc} file
12134 either by running @code{gnatchop} on a source file that consists only of
12135 configuration pragmas, or more conveniently  by
12136 direct editing of the @file{gnat.adc} file, which is a standard format
12137 source file.
12139 In addition to @file{gnat.adc}, additional files containing configuration
12140 pragmas may be applied to the current compilation using the switch
12141 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12142 contains only configuration pragmas. These configuration pragmas are
12143 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12144 is present and switch @option{-gnatA} is not used).
12146 It is allowed to specify several switches @option{-gnatec}, all of which
12147 will be taken into account.
12149 If you are using project file, a separate mechanism is provided using
12150 project attributes, see @ref{Specifying Configuration Pragmas} for more
12151 details.
12153 @ifset vms
12154 Of special interest to GNAT OpenVMS Alpha is the following
12155 configuration pragma:
12157 @smallexample @c ada
12158 @cartouche
12159 pragma Extend_System (Aux_DEC);
12160 @end cartouche
12161 @end smallexample
12163 @noindent
12164 In the presence of this pragma, GNAT adds to the definition of the
12165 predefined package SYSTEM all the additional types and subprograms that are
12166 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12167 @end ifset
12169 @node Handling Arbitrary File Naming Conventions Using gnatname
12170 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
12171 @cindex Arbitrary File Naming Conventions
12173 @menu
12174 * Arbitrary File Naming Conventions::
12175 * Running gnatname::
12176 * Switches for gnatname::
12177 * Examples of gnatname Usage::
12178 @end menu
12180 @node Arbitrary File Naming Conventions
12181 @section Arbitrary File Naming Conventions
12183 @noindent
12184 The GNAT compiler must be able to know the source file name of a compilation
12185 unit.  When using the standard GNAT default file naming conventions
12186 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12187 does not need additional information.
12189 @noindent
12190 When the source file names do not follow the standard GNAT default file naming
12191 conventions, the GNAT compiler must be given additional information through
12192 a configuration pragmas file (@pxref{Configuration Pragmas})
12193 or a project file.
12194 When the non-standard file naming conventions are well-defined,
12195 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12196 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12197 if the file naming conventions are irregular or arbitrary, a number
12198 of pragma @code{Source_File_Name} for individual compilation units
12199 must be defined.
12200 To help maintain the correspondence between compilation unit names and
12201 source file names within the compiler,
12202 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12203 set of files.
12205 @node Running gnatname
12206 @section Running @code{gnatname}
12208 @noindent
12209 The usual form of the @code{gnatname} command is
12211 @smallexample
12212 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12213 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12214 @c Expanding @ovar macro inline (explanation in macro def comments)
12215 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12216       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12217 @end smallexample
12219 @noindent
12220 All of the arguments are optional. If invoked without any argument,
12221 @code{gnatname} will display its usage.
12223 @noindent
12224 When used with at least one naming pattern, @code{gnatname} will attempt to
12225 find all the compilation units in files that follow at least one of the
12226 naming patterns. To find these compilation units,
12227 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12228 regular files.
12230 @noindent
12231 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12232 Each Naming Pattern is enclosed between double quotes (or single
12233 quotes on Windows).
12234 A Naming Pattern is a regular expression similar to the wildcard patterns
12235 used in file names by the Unix shells or the DOS prompt.
12237 @noindent
12238 @code{gnatname} may be called with several sections of directories/patterns.
12239 Sections are separated by switch @code{--and}. In each section, there must be
12240 at least one pattern. If no directory is specified in a section, the current
12241 directory (or the project directory is @code{-P} is used) is implied.
12242 The options other that the directory switches and the patterns apply globally
12243 even if they are in different sections.
12245 @noindent
12246 Examples of Naming Patterns are
12248 @smallexample
12249    "*.[12].ada"
12250    "*.ad[sb]*"
12251    "body_*"    "spec_*"
12252 @end smallexample
12254 @noindent
12255 For a more complete description of the syntax of Naming Patterns,
12256 see the second kind of regular expressions described in @file{g-regexp.ads}
12257 (the ``Glob'' regular expressions).
12259 @noindent
12260 When invoked with no switch @code{-P}, @code{gnatname} will create a
12261 configuration pragmas file @file{gnat.adc} in the current working directory,
12262 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12263 unit.
12265 @node Switches for gnatname
12266 @section Switches for @code{gnatname}
12268 @noindent
12269 Switches for @code{gnatname} must precede any specified Naming Pattern.
12271 @noindent
12272 You may specify any of the following switches to @code{gnatname}:
12274 @table @option
12275 @c !sort!
12277 @item --version
12278 @cindex @option{--version} @command{gnatname}
12279 Display Copyright and version, then exit disregarding all other options.
12281 @item --help
12282 @cindex @option{--help} @command{gnatname}
12283 If @option{--version} was not used, display usage, then exit disregarding
12284 all other options.
12286 @item --and
12287 Start another section of directories/patterns.
12289 @item ^-c^/CONFIG_FILE=^@file{file}
12290 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12291 Create a configuration pragmas file @file{file} (instead of the default
12292 @file{gnat.adc}).
12293 @ifclear vms
12294 There may be zero, one or more space between @option{-c} and
12295 @file{file}.
12296 @end ifclear
12297 @file{file} may include directory information. @file{file} must be
12298 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12299 When a switch @option{^-c^/CONFIG_FILE^} is
12300 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12302 @item ^-d^/SOURCE_DIRS=^@file{dir}
12303 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12304 Look for source files in directory @file{dir}. There may be zero, one or more
12305 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12306 When a switch @option{^-d^/SOURCE_DIRS^}
12307 is specified, the current working directory will not be searched for source
12308 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12309 or @option{^-D^/DIR_FILES^} switch.
12310 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12311 If @file{dir} is a relative path, it is relative to the directory of
12312 the configuration pragmas file specified with switch
12313 @option{^-c^/CONFIG_FILE^},
12314 or to the directory of the project file specified with switch
12315 @option{^-P^/PROJECT_FILE^} or,
12316 if neither switch @option{^-c^/CONFIG_FILE^}
12317 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12318 current working directory. The directory
12319 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12321 @item ^-D^/DIRS_FILE=^@file{file}
12322 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12323 Look for source files in all directories listed in text file @file{file}.
12324 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12325 and @file{file}.
12326 @file{file} must be an existing, readable text file.
12327 Each nonempty line in @file{file} must be a directory.
12328 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12329 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12330 @file{file}.
12332 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12333 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12334 Foreign patterns. Using this switch, it is possible to add sources of languages
12335 other than Ada to the list of sources of a project file.
12336 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12337 For example,
12338 @smallexample
12339 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12340 @end smallexample
12341 @noindent
12342 will look for Ada units in all files with the @file{.ada} extension,
12343 and will add to the list of file for project @file{prj.gpr} the C files
12344 with extension @file{.^c^C^}.
12346 @item ^-h^/HELP^
12347 @cindex @option{^-h^/HELP^} (@code{gnatname})
12348 Output usage (help) information. The output is written to @file{stdout}.
12350 @item ^-P^/PROJECT_FILE=^@file{proj}
12351 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12352 Create or update project file @file{proj}. There may be zero, one or more space
12353 between @option{-P} and @file{proj}. @file{proj} may include directory
12354 information. @file{proj} must be writable.
12355 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12356 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12357 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12359 @item ^-v^/VERBOSE^
12360 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12361 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12362 This includes name of the file written, the name of the directories to search
12363 and, for each file in those directories whose name matches at least one of
12364 the Naming Patterns, an indication of whether the file contains a unit,
12365 and if so the name of the unit.
12367 @item ^-v -v^/VERBOSE /VERBOSE^
12368 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12369 Very Verbose mode. In addition to the output produced in verbose mode,
12370 for each file in the searched directories whose name matches none of
12371 the Naming Patterns, an indication is given that there is no match.
12373 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12374 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12375 Excluded patterns. Using this switch, it is possible to exclude some files
12376 that would match the name patterns. For example,
12377 @smallexample
12378 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12379 @end smallexample
12380 @noindent
12381 will look for Ada units in all files with the @file{.ada} extension,
12382 except those whose names end with @file{_nt.ada}.
12384 @end table
12386 @node Examples of gnatname Usage
12387 @section Examples of @code{gnatname} Usage
12389 @ifset vms
12390 @smallexample
12391 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12392 @end smallexample
12393 @end ifset
12395 @ifclear vms
12396 @smallexample
12397 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12398 @end smallexample
12399 @end ifclear
12401 @noindent
12402 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12403 and be writable. In addition, the directory
12404 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12405 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12407 @ifclear vms
12408 Note the optional spaces after @option{-c} and @option{-d}.
12409 @end ifclear
12411 @smallexample
12412 @ifclear vms
12413 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12414   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12415 @end ifclear
12416 @ifset vms
12417 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12418   /EXCLUDED_PATTERN=*_nt_body.ada
12419   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12420   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12421 @end ifset
12422 @end smallexample
12424 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12425 even in conjunction with one or several switches
12426 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12427 are used in this example.
12429 @c *****************************************
12430 @c * G N A T  P r o j e c t  M a n a g e r *
12431 @c *****************************************
12433 @c ------ macros for projects.texi
12434 @c These macros are needed when building the gprbuild documentation, but
12435 @c should have no effect in the gnat user's guide
12437 @macro CODESAMPLE{TXT}
12438 @smallexample
12439 @group
12440 \TXT\
12441 @end group
12442 @end smallexample
12443 @end macro
12445 @macro PROJECTFILE{TXT}
12446 @CODESAMPLE{\TXT\}
12447 @end macro
12449 @c simulates a newline when in a @CODESAMPLE
12450 @macro NL{}
12451 @end macro
12453 @macro TIP{TXT}
12454 @quotation
12455 @noindent
12456 \TXT\
12457 @end quotation
12458 @end macro
12460 @macro TIPHTML{TXT}
12461 \TXT\
12462 @end macro
12464 @macro IMPORTANT{TXT}
12465 @quotation
12466 @noindent
12467 \TXT\
12468 @end quotation
12470 @end macro
12472 @macro NOTE{TXT}
12473 @quotation
12474 @noindent
12475 \TXT\
12476 @end quotation
12477 @end macro
12479 @include projects.texi
12481 @c *****************************************
12482 @c * Cross-referencing tools
12483 @c *****************************************
12485 @node The Cross-Referencing Tools gnatxref and gnatfind
12486 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12487 @findex gnatxref
12488 @findex gnatfind
12490 @noindent
12491 The compiler generates cross-referencing information (unless
12492 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12493 This information indicates where in the source each entity is declared and
12494 referenced. Note that entities in package Standard are not included, but
12495 entities in all other predefined units are included in the output.
12497 Before using any of these two tools, you need to compile successfully your
12498 application, so that GNAT gets a chance to generate the cross-referencing
12499 information.
12501 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12502 information to provide the user with the capability to easily locate the
12503 declaration and references to an entity. These tools are quite similar,
12504 the difference being that @code{gnatfind} is intended for locating
12505 definitions and/or references to a specified entity or entities, whereas
12506 @code{gnatxref} is oriented to generating a full report of all
12507 cross-references.
12509 To use these tools, you must not compile your application using the
12510 @option{-gnatx} switch on the @command{gnatmake} command line
12511 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12512 information will not be generated.
12514 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12515 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12517 @menu
12518 * Switches for gnatxref::
12519 * Switches for gnatfind::
12520 * Project Files for gnatxref and gnatfind::
12521 * Regular Expressions in gnatfind and gnatxref::
12522 * Examples of gnatxref Usage::
12523 * Examples of gnatfind Usage::
12524 @end menu
12526 @node Switches for gnatxref
12527 @section @code{gnatxref} Switches
12529 @noindent
12530 The command invocation for @code{gnatxref} is:
12531 @smallexample
12532 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12533 @c Expanding @ovar macro inline (explanation in macro def comments)
12534 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12535 @end smallexample
12537 @noindent
12538 where
12540 @table @var
12541 @item sourcefile1
12542 @itemx sourcefile2
12543 identifies the source files for which a report is to be generated. The
12544 ``with''ed units will be processed too. You must provide at least one file.
12546 These file names are considered to be regular expressions, so for instance
12547 specifying @file{source*.adb} is the same as giving every file in the current
12548 directory whose name starts with @file{source} and whose extension is
12549 @file{adb}.
12551 You shouldn't specify any directory name, just base names. @command{gnatxref}
12552 and @command{gnatfind} will be able to locate these files by themselves using
12553 the source path. If you specify directories, no result is produced.
12555 @end table
12557 @noindent
12558 The switches can be:
12559 @table @option
12560 @c !sort!
12561 @item --version
12562 @cindex @option{--version} @command{gnatxref}
12563 Display Copyright and version, then exit disregarding all other options.
12565 @item --help
12566 @cindex @option{--help} @command{gnatxref}
12567 If @option{--version} was not used, display usage, then exit disregarding
12568 all other options.
12570 @item ^-a^/ALL_FILES^
12571 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12572 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12573 the read-only files found in the library search path. Otherwise, these files
12574 will be ignored. This option can be used to protect Gnat sources or your own
12575 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12576 much faster, and their output much smaller. Read-only here refers to access
12577 or permissions status in the file system for the current user.
12579 @item -aIDIR
12580 @cindex @option{-aIDIR} (@command{gnatxref})
12581 When looking for source files also look in directory DIR. The order in which
12582 source file search is undertaken is the same as for @command{gnatmake}.
12584 @item -aODIR
12585 @cindex @option{-aODIR} (@command{gnatxref})
12586 When searching for library and object files, look in directory
12587 DIR. The order in which library files are searched is the same as for
12588 @command{gnatmake}.
12590 @item -nostdinc
12591 @cindex @option{-nostdinc} (@command{gnatxref})
12592 Do not look for sources in the system default directory.
12594 @item -nostdlib
12595 @cindex @option{-nostdlib} (@command{gnatxref})
12596 Do not look for library files in the system default directory.
12598 @item --ext=@var{extension}
12599 @cindex @option{--ext} (@command{gnatxref})
12600 Specify an alternate ali file extension. The default is @code{ali} and other
12601 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12602 switch. Note that if this switch overrides the default, which means that only
12603 the new extension will be considered.
12605 @item --RTS=@var{rts-path}
12606 @cindex @option{--RTS} (@command{gnatxref})
12607 Specifies the default location of the runtime library. Same meaning as the
12608 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12610 @item ^-d^/DERIVED_TYPES^
12611 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12612 If this switch is set @code{gnatxref} will output the parent type
12613 reference for each matching derived types.
12615 @item ^-f^/FULL_PATHNAME^
12616 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12617 If this switch is set, the output file names will be preceded by their
12618 directory (if the file was found in the search path). If this switch is
12619 not set, the directory will not be printed.
12621 @item ^-g^/IGNORE_LOCALS^
12622 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12623 If this switch is set, information is output only for library-level
12624 entities, ignoring local entities. The use of this switch may accelerate
12625 @code{gnatfind} and @code{gnatxref}.
12627 @item -IDIR
12628 @cindex @option{-IDIR} (@command{gnatxref})
12629 Equivalent to @samp{-aODIR -aIDIR}.
12631 @item -pFILE
12632 @cindex @option{-pFILE} (@command{gnatxref})
12633 Specify a project file to use @xref{GNAT Project Manager}.
12634 If you need to use the @file{.gpr}
12635 project files, you should use gnatxref through the GNAT driver
12636 (@command{gnat xref -Pproject}).
12638 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12639 project file in the current directory.
12641 If a project file is either specified or found by the tools, then the content
12642 of the source directory and object directory lines are added as if they
12643 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12644 and @samp{^-aO^OBJECT_SEARCH^}.
12645 @item ^-u^/UNUSED^
12646 Output only unused symbols. This may be really useful if you give your
12647 main compilation unit on the command line, as @code{gnatxref} will then
12648 display every unused entity and 'with'ed package.
12650 @ifclear vms
12651 @item -v
12652 Instead of producing the default output, @code{gnatxref} will generate a
12653 @file{tags} file that can be used by vi. For examples how to use this
12654 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12655 to the standard output, thus you will have to redirect it to a file.
12656 @end ifclear
12658 @end table
12660 @noindent
12661 All these switches may be in any order on the command line, and may even
12662 appear after the file names. They need not be separated by spaces, thus
12663 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12664 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12666 @node Switches for gnatfind
12667 @section @code{gnatfind} Switches
12669 @noindent
12670 The command line for @code{gnatfind} is:
12672 @smallexample
12673 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12674 @c       @r{[}@var{file1} @var{file2} @dots{}]
12675 @c Expanding @ovar macro inline (explanation in macro def comments)
12676 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12677       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12678 @end smallexample
12680 @noindent
12681 where
12683 @table @var
12684 @item pattern
12685 An entity will be output only if it matches the regular expression found
12686 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12688 Omitting the pattern is equivalent to specifying @samp{*}, which
12689 will match any entity. Note that if you do not provide a pattern, you
12690 have to provide both a sourcefile and a line.
12692 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12693 for matching purposes. At the current time there is no support for
12694 8-bit codes other than Latin-1, or for wide characters in identifiers.
12696 @item sourcefile
12697 @code{gnatfind} will look for references, bodies or declarations
12698 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12699 and column @var{column}. See @ref{Examples of gnatfind Usage}
12700 for syntax examples.
12702 @item line
12703 is a decimal integer identifying the line number containing
12704 the reference to the entity (or entities) to be located.
12706 @item column
12707 is a decimal integer identifying the exact location on the
12708 line of the first character of the identifier for the
12709 entity reference. Columns are numbered from 1.
12711 @item file1 file2 @dots{}
12712 The search will be restricted to these source files. If none are given, then
12713 the search will be done for every library file in the search path.
12714 These file must appear only after the pattern or sourcefile.
12716 These file names are considered to be regular expressions, so for instance
12717 specifying @file{source*.adb} is the same as giving every file in the current
12718 directory whose name starts with @file{source} and whose extension is
12719 @file{adb}.
12721 The location of the spec of the entity will always be displayed, even if it
12722 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12723 occurrences of the entity in the separate units of the ones given on the
12724 command line will also be displayed.
12726 Note that if you specify at least one file in this part, @code{gnatfind} may
12727 sometimes not be able to find the body of the subprograms.
12729 @end table
12731 @noindent
12732 At least one of 'sourcefile' or 'pattern' has to be present on
12733 the command line.
12735 The following switches are available:
12736 @table @option
12737 @c !sort!
12739 @cindex @option{--version} @command{gnatfind}
12740 Display Copyright and version, then exit disregarding all other options.
12742 @item --help
12743 @cindex @option{--help} @command{gnatfind}
12744 If @option{--version} was not used, display usage, then exit disregarding
12745 all other options.
12747 @item ^-a^/ALL_FILES^
12748 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12749 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12750 the read-only files found in the library search path. Otherwise, these files
12751 will be ignored. This option can be used to protect Gnat sources or your own
12752 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12753 much faster, and their output much smaller. Read-only here refers to access
12754 or permission status in the file system for the current user.
12756 @item -aIDIR
12757 @cindex @option{-aIDIR} (@command{gnatfind})
12758 When looking for source files also look in directory DIR. The order in which
12759 source file search is undertaken is the same as for @command{gnatmake}.
12761 @item -aODIR
12762 @cindex @option{-aODIR} (@command{gnatfind})
12763 When searching for library and object files, look in directory
12764 DIR. The order in which library files are searched is the same as for
12765 @command{gnatmake}.
12767 @item -nostdinc
12768 @cindex @option{-nostdinc} (@command{gnatfind})
12769 Do not look for sources in the system default directory.
12771 @item -nostdlib
12772 @cindex @option{-nostdlib} (@command{gnatfind})
12773 Do not look for library files in the system default directory.
12775 @item --ext=@var{extension}
12776 @cindex @option{--ext} (@command{gnatfind})
12777 Specify an alternate ali file extension. The default is @code{ali} and other
12778 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12779 switch. Note that if this switch overrides the default, which means that only
12780 the new extension will be considered.
12782 @item --RTS=@var{rts-path}
12783 @cindex @option{--RTS} (@command{gnatfind})
12784 Specifies the default location of the runtime library. Same meaning as the
12785 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12787 @item ^-d^/DERIVED_TYPE_INFORMATION^
12788 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12789 If this switch is set, then @code{gnatfind} will output the parent type
12790 reference for each matching derived types.
12792 @item ^-e^/EXPRESSIONS^
12793 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12794 By default, @code{gnatfind} accept the simple regular expression set for
12795 @samp{pattern}. If this switch is set, then the pattern will be
12796 considered as full Unix-style regular expression.
12798 @item ^-f^/FULL_PATHNAME^
12799 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12800 If this switch is set, the output file names will be preceded by their
12801 directory (if the file was found in the search path). If this switch is
12802 not set, the directory will not be printed.
12804 @item ^-g^/IGNORE_LOCALS^
12805 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12806 If this switch is set, information is output only for library-level
12807 entities, ignoring local entities. The use of this switch may accelerate
12808 @code{gnatfind} and @code{gnatxref}.
12810 @item -IDIR
12811 @cindex @option{-IDIR} (@command{gnatfind})
12812 Equivalent to @samp{-aODIR -aIDIR}.
12814 @item -pFILE
12815 @cindex @option{-pFILE} (@command{gnatfind})
12816 Specify a project file (@pxref{GNAT Project Manager}) to use.
12817 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12818 project file in the current directory.
12820 If a project file is either specified or found by the tools, then the content
12821 of the source directory and object directory lines are added as if they
12822 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12823 @samp{^-aO^/OBJECT_SEARCH^}.
12825 @item ^-r^/REFERENCES^
12826 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12827 By default, @code{gnatfind} will output only the information about the
12828 declaration, body or type completion of the entities. If this switch is
12829 set, the @code{gnatfind} will locate every reference to the entities in
12830 the files specified on the command line (or in every file in the search
12831 path if no file is given on the command line).
12833 @item ^-s^/PRINT_LINES^
12834 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12835 If this switch is set, then @code{gnatfind} will output the content
12836 of the Ada source file lines were the entity was found.
12838 @item ^-t^/TYPE_HIERARCHY^
12839 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12840 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12841 the specified type. It act like -d option but recursively from parent
12842 type to parent type. When this switch is set it is not possible to
12843 specify more than one file.
12845 @end table
12847 @noindent
12848 All these switches may be in any order on the command line, and may even
12849 appear after the file names. They need not be separated by spaces, thus
12850 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12851 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12853 As stated previously, gnatfind will search in every directory in the
12854 search path. You can force it to look only in the current directory if
12855 you specify @code{*} at the end of the command line.
12857 @node Project Files for gnatxref and gnatfind
12858 @section Project Files for @command{gnatxref} and @command{gnatfind}
12860 @noindent
12861 Project files allow a programmer to specify how to compile its
12862 application, where to find sources, etc.  These files are used
12863 @ifclear vms
12864 primarily by GPS, but they can also be used
12865 @end ifclear
12866 by the two tools
12867 @code{gnatxref} and @code{gnatfind}.
12869 A project file name must end with @file{.gpr}. If a single one is
12870 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12871 extract the information from it. If multiple project files are found, none of
12872 them is read, and you have to use the @samp{-p} switch to specify the one
12873 you want to use.
12875 The following lines can be included, even though most of them have default
12876 values which can be used in most cases.
12877 The lines can be entered in any order in the file.
12878 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12879 each line. If you have multiple instances, only the last one is taken into
12880 account.
12882 @table @code
12883 @item src_dir=DIR
12884 [default: @code{"^./^[]^"}]
12885 specifies a directory where to look for source files. Multiple @code{src_dir}
12886 lines can be specified and they will be searched in the order they
12887 are specified.
12889 @item obj_dir=DIR
12890 [default: @code{"^./^[]^"}]
12891 specifies a directory where to look for object and library files. Multiple
12892 @code{obj_dir} lines can be specified, and they will be searched in the order
12893 they are specified
12895 @item comp_opt=SWITCHES
12896 [default: @code{""}]
12897 creates a variable which can be referred to subsequently by using
12898 the @code{$@{comp_opt@}} notation. This is intended to store the default
12899 switches given to @command{gnatmake} and @command{gcc}.
12901 @item bind_opt=SWITCHES
12902 [default: @code{""}]
12903 creates a variable which can be referred to subsequently by using
12904 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12905 switches given to @command{gnatbind}.
12907 @item link_opt=SWITCHES
12908 [default: @code{""}]
12909 creates a variable which can be referred to subsequently by using
12910 the @samp{$@{link_opt@}} notation. This is intended to store the default
12911 switches given to @command{gnatlink}.
12913 @item main=EXECUTABLE
12914 [default: @code{""}]
12915 specifies the name of the executable for the application. This variable can
12916 be referred to in the following lines by using the @samp{$@{main@}} notation.
12918 @ifset vms
12919 @item comp_cmd=COMMAND
12920 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12921 @end ifset
12922 @ifclear vms
12923 @item comp_cmd=COMMAND
12924 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12925 @end ifclear
12926 specifies the command used to compile a single file in the application.
12928 @ifset vms
12929 @item make_cmd=COMMAND
12930 [default: @code{"GNAT MAKE $@{main@}
12931 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12932 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12933 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12934 @end ifset
12935 @ifclear vms
12936 @item make_cmd=COMMAND
12937 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12938 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12939 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12940 @end ifclear
12941 specifies the command used to recompile the whole application.
12943 @item run_cmd=COMMAND
12944 [default: @code{"$@{main@}"}]
12945 specifies the command used to run the application.
12947 @item debug_cmd=COMMAND
12948 [default: @code{"gdb $@{main@}"}]
12949 specifies the command used to debug the application
12951 @end table
12953 @noindent
12954 @command{gnatxref} and @command{gnatfind} only take into account the
12955 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12957 @node Regular Expressions in gnatfind and gnatxref
12958 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12960 @noindent
12961 As specified in the section about @command{gnatfind}, the pattern can be a
12962 regular expression. Actually, there are to set of regular expressions
12963 which are recognized by the program:
12965 @table @code
12966 @item globbing patterns
12967 These are the most usual regular expression. They are the same that you
12968 generally used in a Unix shell command line, or in a DOS session.
12970 Here is a more formal grammar:
12971 @smallexample
12972 @group
12973 @iftex
12974 @leftskip=.5cm
12975 @end iftex
12976 regexp ::= term
12977 term   ::= elmt            -- matches elmt
12978 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12979 term   ::= *               -- any string of 0 or more characters
12980 term   ::= ?               -- matches any character
12981 term   ::= [char @{char@}]   -- matches any character listed
12982 term   ::= [char - char]   -- matches any character in range
12983 @end group
12984 @end smallexample
12986 @item full regular expression
12987 The second set of regular expressions is much more powerful. This is the
12988 type of regular expressions recognized by utilities such a @file{grep}.
12990 The following is the form of a regular expression, expressed in Ada
12991 reference manual style BNF is as follows
12993 @smallexample
12994 @iftex
12995 @leftskip=.5cm
12996 @end iftex
12997 @group
12998 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13000 term ::= item @{item@}       -- concatenation (item then item)
13002 item ::= elmt              -- match elmt
13003 item ::= elmt *            -- zero or more elmt's
13004 item ::= elmt +            -- one or more elmt's
13005 item ::= elmt ?            -- matches elmt or nothing
13006 @end group
13007 @group
13008 elmt ::= nschar            -- matches given character
13009 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13010 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13011 elmt ::= [char - char]     -- matches chars in given range
13012 elmt ::= \ char            -- matches given character
13013 elmt ::= .                 -- matches any single character
13014 elmt ::= ( regexp )        -- parens used for grouping
13016 char ::= any character, including special characters
13017 nschar ::= any character except ()[].*+?^^^
13018 @end group
13019 @end smallexample
13021 Following are a few examples:
13023 @table @samp
13024 @item abcde|fghi
13025 will match any of the two strings @samp{abcde} and @samp{fghi},
13027 @item abc*d
13028 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13029 @samp{abcccd}, and so on,
13031 @item [a-z]+
13032 will match any string which has only lowercase characters in it (and at
13033 least one character.
13035 @end table
13036 @end table
13038 @node Examples of gnatxref Usage
13039 @section Examples of @code{gnatxref} Usage
13041 @subsection General Usage
13043 @noindent
13044 For the following examples, we will consider the following units:
13046 @smallexample @c ada
13047 @group
13048 @cartouche
13049 main.ads:
13050 1: with Bar;
13051 2: package Main is
13052 3:     procedure Foo (B : in Integer);
13053 4:     C : Integer;
13054 5: private
13055 6:     D : Integer;
13056 7: end Main;
13058 main.adb:
13059 1: package body Main is
13060 2:     procedure Foo (B : in Integer) is
13061 3:     begin
13062 4:        C := B;
13063 5:        D := B;
13064 6:        Bar.Print (B);
13065 7:        Bar.Print (C);
13066 8:     end Foo;
13067 9: end Main;
13069 bar.ads:
13070 1: package Bar is
13071 2:     procedure Print (B : Integer);
13072 3: end bar;
13073 @end cartouche
13074 @end group
13075 @end smallexample
13077 @table @code
13079 @noindent
13080 The first thing to do is to recompile your application (for instance, in
13081 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13082 the cross-referencing information.
13083 You can then issue any of the following commands:
13085 @item gnatxref main.adb
13086 @code{gnatxref} generates cross-reference information for main.adb
13087 and every unit 'with'ed by main.adb.
13089 The output would be:
13090 @smallexample
13091 @iftex
13092 @leftskip=0cm
13093 @end iftex
13094 B                                                      Type: Integer
13095   Decl: bar.ads           2:22
13096 B                                                      Type: Integer
13097   Decl: main.ads          3:20
13098   Body: main.adb          2:20
13099   Ref:  main.adb          4:13     5:13     6:19
13100 Bar                                                    Type: Unit
13101   Decl: bar.ads           1:9
13102   Ref:  main.adb          6:8      7:8
13103        main.ads           1:6
13104 C                                                      Type: Integer
13105   Decl: main.ads          4:5
13106   Modi: main.adb          4:8
13107   Ref:  main.adb          7:19
13108 D                                                      Type: Integer
13109   Decl: main.ads          6:5
13110   Modi: main.adb          5:8
13111 Foo                                                    Type: Unit
13112   Decl: main.ads          3:15
13113   Body: main.adb          2:15
13114 Main                                                    Type: Unit
13115   Decl: main.ads          2:9
13116   Body: main.adb          1:14
13117 Print                                                   Type: Unit
13118   Decl: bar.ads           2:15
13119   Ref:  main.adb          6:12     7:12
13120 @end smallexample
13122 @noindent
13123 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13124 its body is in main.adb, line 1, column 14 and is not referenced any where.
13126 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13127 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13129 @item gnatxref package1.adb package2.ads
13130 @code{gnatxref} will generates cross-reference information for
13131 package1.adb, package2.ads and any other package 'with'ed by any
13132 of these.
13134 @end table
13136 @ifclear vms
13137 @subsection Using gnatxref with vi
13139 @code{gnatxref} can generate a tags file output, which can be used
13140 directly from @command{vi}. Note that the standard version of @command{vi}
13141 will not work properly with overloaded symbols. Consider using another
13142 free implementation of @command{vi}, such as @command{vim}.
13144 @smallexample
13145 $ gnatxref -v gnatfind.adb > tags
13146 @end smallexample
13148 @noindent
13149 will generate the tags file for @code{gnatfind} itself (if the sources
13150 are in the search path!).
13152 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13153 (replacing @var{entity} by whatever you are looking for), and vi will
13154 display a new file with the corresponding declaration of entity.
13155 @end ifclear
13157 @node Examples of gnatfind Usage
13158 @section Examples of @code{gnatfind} Usage
13160 @table @code
13162 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13163 Find declarations for all entities xyz referenced at least once in
13164 main.adb. The references are search in every library file in the search
13165 path.
13167 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13168 switch is set)
13170 The output will look like:
13171 @smallexample
13172 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13173 ^directory/^[directory]^main.adb:24:10: xyz <= body
13174 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13175 @end smallexample
13177 @noindent
13178 that is to say, one of the entities xyz found in main.adb is declared at
13179 line 12 of main.ads (and its body is in main.adb), and another one is
13180 declared at line 45 of foo.ads
13182 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13183 This is the same command as the previous one, instead @code{gnatfind} will
13184 display the content of the Ada source file lines.
13186 The output will look like:
13188 @smallexample
13189 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13190    procedure xyz;
13191 ^directory/^[directory]^main.adb:24:10: xyz <= body
13192    procedure xyz is
13193 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13194    xyz : Integer;
13195 @end smallexample
13197 @noindent
13198 This can make it easier to find exactly the location your are looking
13199 for.
13201 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13202 Find references to all entities containing an x that are
13203 referenced on line 123 of main.ads.
13204 The references will be searched only in main.ads and foo.adb.
13206 @item gnatfind main.ads:123
13207 Find declarations and bodies for all entities that are referenced on
13208 line 123 of main.ads.
13210 This is the same as @code{gnatfind "*":main.adb:123}.
13212 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13213 Find the declaration for the entity referenced at column 45 in
13214 line 123 of file main.adb in directory mydir. Note that it
13215 is usual to omit the identifier name when the column is given,
13216 since the column position identifies a unique reference.
13218 The column has to be the beginning of the identifier, and should not
13219 point to any character in the middle of the identifier.
13221 @end table
13223 @c *********************************
13224 @node The GNAT Pretty-Printer gnatpp
13225 @chapter The GNAT Pretty-Printer @command{gnatpp}
13226 @findex gnatpp
13227 @cindex Pretty-Printer
13229 @noindent
13230 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13231 for source reformatting / pretty-printing.
13232 It takes an Ada source file as input and generates a reformatted
13233 version as output.
13234 You can specify various style directives via switches; e.g.,
13235 identifier case conventions, rules of indentation, and comment layout.
13237 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13238 tree for the input source and thus requires the input to be syntactically and
13239 semantically legal.
13240 If this condition is not met, @command{gnatpp} will terminate with an
13241 error message; no output file will be generated.
13243 @command{gnatpp} cannot process sources that contain
13244 preprocessing directives.
13246 If the compilation unit
13247 contained in the input source depends semantically upon units located
13248 outside the current directory, you have to provide the source search path
13249 when invoking @command{gnatpp}, if these units are contained in files with
13250 names that do not follow the GNAT file naming rules, you have to provide
13251 the configuration file describing the corresponding naming scheme;
13252 see the description of the @command{gnatpp}
13253 switches below. Another possibility is to use a project file and to
13254 call @command{gnatpp} through the @command{gnat} driver
13255 (see @ref{The GNAT Driver and Project Files}).
13257 The @command{gnatpp} command has the form
13259 @smallexample
13260 @c $ gnatpp @ovar{switches} @var{filename}
13261 @c Expanding @ovar macro inline (explanation in macro def comments)
13262 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13263 @end smallexample
13265 @noindent
13266 where
13267 @itemize @bullet
13268 @item
13269 @var{switches} is an optional sequence of switches defining such properties as
13270 the formatting rules, the source search path, and the destination for the
13271 output source file
13273 @item
13274 @var{filename} is the name (including the extension) of the source file to
13275 reformat; ``wildcards'' or several file names on the same gnatpp command are
13276 allowed.  The file name may contain path information; it does not have to
13277 follow the GNAT file naming rules
13279 @item
13280 @samp{@var{gcc_switches}} is a list of switches for
13281 @command{gcc}. They will be passed on to all compiler invocations made by
13282 @command{gnatelim} to generate the ASIS trees. Here you can provide
13283 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13284 use the @option{-gnatec} switch to set the configuration file,
13285 use the @option{-gnat05} switch if sources should be compiled in
13286 Ada 2005 mode  etc.
13287 @end itemize
13289 @menu
13290 * Switches for gnatpp::
13291 * Formatting Rules::
13292 @end menu
13294 @node Switches for gnatpp
13295 @section Switches for @command{gnatpp}
13297 @noindent
13298 The following subsections describe the various switches accepted by
13299 @command{gnatpp}, organized by category.
13301 @ifclear vms
13302 You specify a switch by supplying a name and generally also a value.
13303 In many cases the values for a switch with a given name are incompatible with
13304 each other
13305 (for example the switch that controls the casing of a reserved word may have
13306 exactly one value: upper case, lower case, or
13307 mixed case) and thus exactly one such switch can be in effect for an
13308 invocation of @command{gnatpp}.
13309 If more than one is supplied, the last one is used.
13310 However, some values for the same switch are mutually compatible.
13311 You may supply several such switches to @command{gnatpp}, but then
13312 each must be specified in full, with both the name and the value.
13313 Abbreviated forms (the name appearing once, followed by each value) are
13314 not permitted.
13315 For example, to set
13316 the alignment of the assignment delimiter both in declarations and in
13317 assignment statements, you must write @option{-A2A3}
13318 (or @option{-A2 -A3}), but not @option{-A23}.
13319 @end ifclear
13321 @ifset vms
13322 In many cases the set of options for a given qualifier are incompatible with
13323 each other (for example the qualifier that controls the casing of a reserved
13324 word may have exactly one option, which specifies either upper case, lower
13325 case, or mixed case), and thus exactly one such option can be in effect for
13326 an invocation of @command{gnatpp}.
13327 If more than one is supplied, the last one is used.
13328 However, some qualifiers have options that are mutually compatible,
13329 and then you may then supply several such options when invoking
13330 @command{gnatpp}.
13331 @end ifset
13333 In most cases, it is obvious whether or not the
13334 ^values for a switch with a given name^options for a given qualifier^
13335 are compatible with each other.
13336 When the semantics might not be evident, the summaries below explicitly
13337 indicate the effect.
13339 @menu
13340 * Alignment Control::
13341 * Casing Control::
13342 * Construct Layout Control::
13343 * General Text Layout Control::
13344 * Other Formatting Options::
13345 * Setting the Source Search Path::
13346 * Output File Control::
13347 * Other gnatpp Switches::
13348 @end menu
13350 @node Alignment Control
13351 @subsection Alignment Control
13352 @cindex Alignment control in @command{gnatpp}
13354 @noindent
13355 Programs can be easier to read if certain constructs are vertically aligned.
13356 By default all alignments are set ON.
13357 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13358 OFF, and then use one or more of the other
13359 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13360 to activate alignment for specific constructs.
13362 @table @option
13363 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13365 @ifset vms
13366 @item /ALIGN=ON
13367 Set all alignments to ON
13368 @end ifset
13370 @item ^-A0^/ALIGN=OFF^
13371 Set all alignments to OFF
13373 @item ^-A1^/ALIGN=COLONS^
13374 Align @code{:} in declarations
13376 @item ^-A2^/ALIGN=DECLARATIONS^
13377 Align @code{:=} in initializations in declarations
13379 @item ^-A3^/ALIGN=STATEMENTS^
13380 Align @code{:=} in assignment statements
13382 @item ^-A4^/ALIGN=ARROWS^
13383 Align @code{=>} in associations
13385 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13386 Align @code{at} keywords in the component clauses in record
13387 representation clauses
13388 @end table
13390 @noindent
13391 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13392 is allowed.
13394 @node Casing Control
13395 @subsection Casing Control
13396 @cindex Casing control in @command{gnatpp}
13398 @noindent
13399 @command{gnatpp} allows you to specify the casing for reserved words,
13400 pragma names, attribute designators and identifiers.
13401 For identifiers you may define a
13402 general rule for name casing but also override this rule
13403 via a set of dictionary files.
13405 Three types of casing are supported: lower case, upper case, and mixed case.
13406 Lower and upper case are self-explanatory (but since some letters in
13407 Latin1 and other GNAT-supported character sets
13408 exist only in lower-case form, an upper case conversion will have no
13409 effect on them.)
13410 ``Mixed case'' means that the first letter, and also each letter immediately
13411 following an underscore, are converted to their uppercase forms;
13412 all the other letters are converted to their lowercase forms.
13414 @table @option
13415 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13416 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13417 Attribute designators are lower case
13419 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13420 Attribute designators are upper case
13422 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13423 Attribute designators are mixed case (this is the default)
13425 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13426 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13427 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13428 lower case (this is the default)
13430 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13431 Keywords are upper case
13433 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13434 @item ^-nD^/NAME_CASING=AS_DECLARED^
13435 Name casing for defining occurrences are as they appear in the source file
13436 (this is the default)
13438 @item ^-nU^/NAME_CASING=UPPER_CASE^
13439 Names are in upper case
13441 @item ^-nL^/NAME_CASING=LOWER_CASE^
13442 Names are in lower case
13444 @item ^-nM^/NAME_CASING=MIXED_CASE^
13445 Names are in mixed case
13447 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13448 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13449 Enumeration literal casing for defining occurrences are as they appear in the
13450 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13452 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13453 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13454 setting.
13456 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13457 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13458 setting.
13460 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13461 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13462 setting.
13464 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13465 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13466 Names introduced by type and subtype declarations are always
13467 cased as they appear in the declaration in the source file.
13468 Overrides ^-n^/NAME_CASING^ casing setting.
13470 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13471 Names introduced by type and subtype declarations are always in
13472 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13474 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13475 Names introduced by type and subtype declarations are always in
13476 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13478 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13479 Names introduced by type and subtype declarations are always in
13480 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13482 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
13483 Names introduced by number declarations are always in
13484 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13486 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
13487 Names introduced by number declarations are always in
13488 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13490 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
13491 Names introduced by number declarations are always in
13492 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13494 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13495 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13496 Pragma names are lower case
13498 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13499 Pragma names are upper case
13501 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13502 Pragma names are mixed case (this is the default)
13504 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13505 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13506 Use @var{file} as a @emph{dictionary file} that defines
13507 the casing for a set of specified names,
13508 thereby overriding the effect on these names by
13509 any explicit or implicit
13510 ^-n^/NAME_CASING^ switch.
13511 To supply more than one dictionary file,
13512 use ^several @option{-D} switches^a list of files as options^.
13514 @noindent
13515 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13516 to define the casing for the Ada predefined names and
13517 the names declared in the GNAT libraries.
13519 @item ^-D-^/SPECIFIC_CASING^
13520 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13521 Do not use the default dictionary file;
13522 instead, use the casing
13523 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13524 dictionary file(s)
13525 @end table
13527 @noindent
13528 The structure of a dictionary file, and details on the conventions
13529 used in the default dictionary file, are defined in @ref{Name Casing}.
13531 The @option{^-D-^/SPECIFIC_CASING^} and
13532 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13533 compatible.
13535 @node Construct Layout Control
13536 @subsection Construct Layout Control
13537 @cindex Layout control in @command{gnatpp}
13539 @noindent
13540 This group of @command{gnatpp} switches controls the layout of comments and
13541 complex syntactic constructs.  See @ref{Formatting Comments} for details
13542 on their effect.
13544 @table @option
13545 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13546 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13547 All the comments remain unchanged
13549 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13550 GNAT-style comment line indentation (this is the default).
13552 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13553 Reference-manual comment line indentation.
13555 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13556 GNAT-style comment beginning
13558 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13559 Reformat comment blocks
13561 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13562 Keep unchanged special form comments
13564 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13565 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13566 GNAT-style layout (this is the default)
13568 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13569 Compact layout
13571 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13572 Uncompact layout
13574 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13575 @item ^-N^/NOTABS^
13576 All the VT characters are removed from the comment text. All the HT characters
13577 are expanded with the sequences of space characters to get to the next tab
13578 stops.
13580 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13581 @item ^--no-separate-is^/NO_SEPARATE_IS^
13582 Do not place the keyword @code{is} on a separate line in a subprogram body in
13583 case if the spec occupies more than one line.
13585 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13586 @item ^--separate-label^/SEPARATE_LABEL^
13587 Place statement label(s) on a separate line, with the following statement
13588 on the next line.
13590 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13591 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13592 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13593 keyword @code{then} in IF statements on a separate line.
13595 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13596 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13597 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13598 keyword @code{then} in IF statements on a separate line. This option is
13599 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13601 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13602 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13603 Start each USE clause in a context clause from a separate line.
13605 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13606 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13607 Use a separate line for a loop or block statement name, but do not use an extra
13608 indentation level for the statement itself.
13610 @end table
13612 @ifclear vms
13613 @noindent
13614 The @option{-c1} and @option{-c2} switches are incompatible.
13615 The @option{-c3} and @option{-c4} switches are compatible with each other and
13616 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13617 the other comment formatting switches.
13619 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13620 @end ifclear
13622 @ifset vms
13623 @noindent
13624 For the @option{/COMMENTS_LAYOUT} qualifier:
13625 @itemize @bullet
13626 @item
13627 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13628 @item
13629 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13630 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13631 @end itemize
13633 @noindent
13634 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13635 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13636 @end ifset
13638 @node General Text Layout Control
13639 @subsection General Text Layout Control
13641 @noindent
13642 These switches allow control over line length and indentation.
13644 @table @option
13645 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13646 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13647 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13649 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13650 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13651 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13653 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13654 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13655 Indentation level for continuation lines (relative to the line being
13656 continued), @var{nnn} from 1@dots{}9.
13657 The default
13658 value is one less than the (normal) indentation level, unless the
13659 indentation is set to 1 (in which case the default value for continuation
13660 line indentation is also 1)
13661 @end table
13663 @node Other Formatting Options
13664 @subsection Other Formatting Options
13666 @noindent
13667 These switches control the inclusion of missing end/exit labels, and
13668 the indentation level in @b{case} statements.
13670 @table @option
13671 @item ^-e^/NO_MISSED_LABELS^
13672 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13673 Do not insert missing end/exit labels. An end label is the name of
13674 a construct that may optionally be repeated at the end of the
13675 construct's declaration;
13676 e.g., the names of packages, subprograms, and tasks.
13677 An exit label is the name of a loop that may appear as target
13678 of an exit statement within the loop.
13679 By default, @command{gnatpp} inserts these end/exit labels when
13680 they are absent from the original source. This option suppresses such
13681 insertion, so that the formatted source reflects the original.
13683 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13684 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13685 Insert a Form Feed character after a pragma Page.
13687 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13688 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13689 Do not use an additional indentation level for @b{case} alternatives
13690 and variants if there are @var{nnn} or more (the default
13691 value is 10).
13692 If @var{nnn} is 0, an additional indentation level is
13693 used for @b{case} alternatives and variants regardless of their number.
13695 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
13696 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
13697 If the number of parameter associations is greater than @var{nnn} and if at
13698 least one association uses named notation, start each association from
13699 a new line. If @var{nnn} is 0, no check for the number of associations
13700 is made, this is the default.
13702 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
13703 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
13704 If the number of parameter specifications is greater than @var{nnn}
13705 (or equal to @var{nnn} in case of a function), start each specification from
13706 a new line. The default for @var{nnn} is 3.
13707 @end table
13709 @node Setting the Source Search Path
13710 @subsection Setting the Source Search Path
13712 @noindent
13713 To define the search path for the input source file, @command{gnatpp}
13714 uses the same switches as the GNAT compiler, with the same effects.
13716 @table @option
13717 @item ^-I^/SEARCH=^@var{dir}
13718 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13719 The same as the corresponding gcc switch
13721 @item ^-I-^/NOCURRENT_DIRECTORY^
13722 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13723 The same as the corresponding gcc switch
13725 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13726 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13727 The same as the corresponding gcc switch
13729 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13730 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13731 The same as the corresponding gcc switch
13733 @end table
13735 @node Output File Control
13736 @subsection Output File Control
13738 @noindent
13739 By default the output is sent to the file whose name is obtained by appending
13740 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13741 (if the file with this name already exists, it is unconditionally overwritten).
13742 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13743 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13744 as output file.
13745 The output may be redirected by the following switches:
13747 @table @option
13748 @item ^-pipe^/STANDARD_OUTPUT^
13749 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13750 Send the output to @code{Standard_Output}
13752 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13753 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13754 Write the output into @var{output_file}.
13755 If @var{output_file} already exists, @command{gnatpp} terminates without
13756 reading or processing the input file.
13758 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13759 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13760 Write the output into @var{output_file}, overwriting the existing file
13761 (if one is present).
13763 @item ^-r^/REPLACE^
13764 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13765 Replace the input source file with the reformatted output, and copy the
13766 original input source into the file whose name is obtained by appending the
13767 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13768 If a file with this name already exists, @command{gnatpp} terminates without
13769 reading or processing the input file.
13771 @item ^-rf^/OVERRIDING_REPLACE^
13772 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13773 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13774 already exists, it is overwritten.
13776 @item ^-rnb^/REPLACE_NO_BACKUP^
13777 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13778 Replace the input source file with the reformatted output without
13779 creating any backup copy of the input source.
13781 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13782 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13783 Specifies the format of the reformatted output file. The @var{xxx}
13784 ^string specified with the switch^option^ may be either
13785 @itemize @bullet
13786 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13787 @item ``@option{^crlf^CRLF^}''
13788 the same as @option{^crlf^CRLF^}
13789 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13790 @item ``@option{^lf^LF^}''
13791 the same as @option{^unix^UNIX^}
13792 @end itemize
13794 @item ^-W^/RESULT_ENCODING=^@var{e}
13795 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13796 Specify the wide character encoding method used to write the code in the
13797 result file
13798 @var{e} is one of the following:
13800 @itemize @bullet
13802 @item ^h^HEX^
13803 Hex encoding
13805 @item ^u^UPPER^
13806 Upper half encoding
13808 @item ^s^SHIFT_JIS^
13809 Shift/JIS encoding
13811 @item ^e^EUC^
13812 EUC encoding
13814 @item ^8^UTF8^
13815 UTF-8 encoding
13817 @item ^b^BRACKETS^
13818 Brackets encoding (default value)
13819 @end itemize
13821 @end table
13823 @noindent
13824 Options @option{^-pipe^/STANDARD_OUTPUT^},
13825 @option{^-o^/OUTPUT^} and
13826 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13827 contains only one file to reformat.
13828 Option
13829 @option{^--eol^/END_OF_LINE^}
13831 @option{^-W^/RESULT_ENCODING^}
13832 cannot be used together
13833 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13835 @node Other gnatpp Switches
13836 @subsection Other @code{gnatpp} Switches
13838 @noindent
13839 The additional @command{gnatpp} switches are defined in this subsection.
13841 @table @option
13842 @item ^-files @var{filename}^/FILES=@var{filename}^
13843 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13844 Take the argument source files from the specified file. This file should be an
13845 ordinary text file containing file names separated by spaces or
13846 line breaks. You can use this switch more than once in the same call to
13847 @command{gnatpp}. You also can combine this switch with an explicit list of
13848 files.
13850 @item ^-v^/VERBOSE^
13851 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13852 Verbose mode;
13853 @command{gnatpp} generates version information and then
13854 a trace of the actions it takes to produce or obtain the ASIS tree.
13856 @item ^-w^/WARNINGS^
13857 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13858 Warning mode;
13859 @command{gnatpp} generates a warning whenever it cannot provide
13860 a required layout in the result source.
13861 @end table
13863 @node Formatting Rules
13864 @section Formatting Rules
13866 @noindent
13867 The following subsections show how @command{gnatpp} treats ``white space'',
13868 comments, program layout, and name casing.
13869 They provide the detailed descriptions of the switches shown above.
13871 @menu
13872 * White Space and Empty Lines::
13873 * Formatting Comments::
13874 * Construct Layout::
13875 * Name Casing::
13876 @end menu
13878 @node White Space and Empty Lines
13879 @subsection White Space and Empty Lines
13881 @noindent
13882 @command{gnatpp} does not have an option to control space characters.
13883 It will add or remove spaces according to the style illustrated by the
13884 examples in the @cite{Ada Reference Manual}.
13886 The only format effectors
13887 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13888 that will appear in the output file are platform-specific line breaks,
13889 and also format effectors within (but not at the end of) comments.
13890 In particular, each horizontal tab character that is not inside
13891 a comment will be treated as a space and thus will appear in the
13892 output file as zero or more spaces depending on
13893 the reformatting of the line in which it appears.
13894 The only exception is a Form Feed character, which is inserted after a
13895 pragma @code{Page} when @option{-ff} is set.
13897 The output file will contain no lines with trailing ``white space'' (spaces,
13898 format effectors).
13900 Empty lines in the original source are preserved
13901 only if they separate declarations or statements.
13902 In such contexts, a
13903 sequence of two or more empty lines is replaced by exactly one empty line.
13904 Note that a blank line will be removed if it separates two ``comment blocks''
13905 (a comment block is a sequence of whole-line comments).
13906 In order to preserve a visual separation between comment blocks, use an
13907 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13908 Likewise, if for some reason you wish to have a sequence of empty lines,
13909 use a sequence of empty comments instead.
13911 @node Formatting Comments
13912 @subsection Formatting Comments
13914 @noindent
13915 Comments in Ada code are of two kinds:
13916 @itemize @bullet
13917 @item
13918 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13919 ``white space'') on a line
13921 @item
13922 an @emph{end-of-line comment}, which follows some other Ada lexical element
13923 on the same line.
13924 @end itemize
13926 @noindent
13927 The indentation of a whole-line comment is that of either
13928 the preceding or following line in
13929 the formatted source, depending on switch settings as will be described below.
13931 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13932 between the end of the preceding Ada lexical element and the beginning
13933 of the comment as appear in the original source,
13934 unless either the comment has to be split to
13935 satisfy the line length limitation, or else the next line contains a
13936 whole line comment that is considered a continuation of this end-of-line
13937 comment (because it starts at the same position).
13938 In the latter two
13939 cases, the start of the end-of-line comment is moved right to the nearest
13940 multiple of the indentation level.
13941 This may result in a ``line overflow'' (the right-shifted comment extending
13942 beyond the maximum line length), in which case the comment is split as
13943 described below.
13945 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13946 (GNAT-style comment line indentation)
13947 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13948 (reference-manual comment line indentation).
13949 With reference-manual style, a whole-line comment is indented as if it
13950 were a declaration or statement at the same place
13951 (i.e., according to the indentation of the preceding line(s)).
13952 With GNAT style, a whole-line comment that is immediately followed by an
13953 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13954 word @b{begin}, is indented based on the construct that follows it.
13956 For example:
13957 @smallexample @c ada
13958 @cartouche
13959 if A then
13960     null;
13961        -- some comment
13962 else
13963    null;
13964 end if;
13965 @end cartouche
13966 @end smallexample
13968 @noindent
13969 Reference-manual indentation produces:
13971 @smallexample @c ada
13972 @cartouche
13973 if A then
13974    null;
13975    --  some comment
13976 else
13977    null;
13978 end if;
13979 @end cartouche
13980 @end smallexample
13982 @noindent
13983 while GNAT-style indentation produces:
13985 @smallexample @c ada
13986 @cartouche
13987 if A then
13988    null;
13989 --  some comment
13990 else
13991    null;
13992 end if;
13993 @end cartouche
13994 @end smallexample
13996 @noindent
13997 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13998 (GNAT style comment beginning) has the following
13999 effect:
14001 @itemize @bullet
14002 @item
14003 For each whole-line comment that does not end with two hyphens,
14004 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14005 to ensure that there are at least two spaces between these hyphens and the
14006 first non-blank character of the comment.
14007 @end itemize
14009 @noindent
14010 For an end-of-line comment, if in the original source the next line is a
14011 whole-line comment that starts at the same position
14012 as the end-of-line comment,
14013 then the whole-line comment (and all whole-line comments
14014 that follow it and that start at the same position)
14015 will start at this position in the output file.
14017 @noindent
14018 That is, if in the original source we have:
14020 @smallexample @c ada
14021 @cartouche
14022 begin
14023 A := B + C;            --  B must be in the range Low1..High1
14024                        --  C must be in the range Low2..High2
14025              --B+C will be in the range Low1+Low2..High1+High2
14026 X := X + 1;
14027 @end cartouche
14028 @end smallexample
14030 @noindent
14031 Then in the formatted source we get
14033 @smallexample @c ada
14034 @cartouche
14035 begin
14036    A := B + C;            --  B must be in the range Low1..High1
14037                           --  C must be in the range Low2..High2
14038    --  B+C will be in the range Low1+Low2..High1+High2
14039    X := X + 1;
14040 @end cartouche
14041 @end smallexample
14043 @noindent
14044 A comment that exceeds the line length limit will be split.
14045 Unless switch
14046 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14047 the line belongs to a reformattable block, splitting the line generates a
14048 @command{gnatpp} warning.
14049 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14050 comments may be reformatted in typical
14051 word processor style (that is, moving words between lines and putting as
14052 many words in a line as possible).
14054 @noindent
14055 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14056 that has a special format (that is, a character that is neither a letter nor digit
14057 not white space nor line break immediately following the leading @code{--} of
14058 the comment) should be without any change moved from the argument source
14059 into reformatted source. This switch allows to preserve comments that are used
14060 as a special marks in the code (e.g.@: SPARK annotation).
14062 @node Construct Layout
14063 @subsection Construct Layout
14065 @noindent
14066 In several cases the suggested layout in the Ada Reference Manual includes
14067 an extra level of indentation that many programmers prefer to avoid. The
14068 affected cases include:
14070 @itemize @bullet
14072 @item Record type declaration (RM 3.8)
14074 @item Record representation clause (RM 13.5.1)
14076 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14078 @item Block statement in case if a block has a statement identifier (RM 5.6)
14079 @end itemize
14081 @noindent
14082 In compact mode (when GNAT style layout or compact layout is set),
14083 the pretty printer uses one level of indentation instead
14084 of two. This is achieved in the record definition and record representation
14085 clause cases by putting the @code{record} keyword on the same line as the
14086 start of the declaration or representation clause, and in the block and loop
14087 case by putting the block or loop header on the same line as the statement
14088 identifier.
14090 @noindent
14091 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14092 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14093 layout on the one hand, and uncompact layout
14094 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14095 can be illustrated by the following examples:
14097 @iftex
14098 @cartouche
14099 @multitable @columnfractions .5 .5
14100 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14102 @item
14103 @smallexample @c ada
14104 type q is record
14105    a : integer;
14106    b : integer;
14107 end record;
14108 @end smallexample
14109 @tab
14110 @smallexample @c ada
14111 type q is
14112    record
14113       a : integer;
14114       b : integer;
14115    end record;
14116 @end smallexample
14118 @item
14119 @smallexample @c ada
14120 for q use record
14121    a at 0 range  0 .. 31;
14122    b at 4 range  0 .. 31;
14123 end record;
14124 @end smallexample
14125 @tab
14126 @smallexample @c ada
14127 for q use
14128    record
14129       a at 0 range  0 .. 31;
14130       b at 4 range  0 .. 31;
14131    end record;
14132 @end smallexample
14134 @item
14135 @smallexample @c ada
14136 Block : declare
14137    A : Integer := 3;
14138 begin
14139    Proc (A, A);
14140 end Block;
14141 @end smallexample
14142 @tab
14143 @smallexample @c ada
14144 Block :
14145    declare
14146       A : Integer := 3;
14147    begin
14148       Proc (A, A);
14149    end Block;
14150 @end smallexample
14152 @item
14153 @smallexample @c ada
14154 Clear : for J in 1 .. 10 loop
14155    A (J) := 0;
14156 end loop Clear;
14157 @end smallexample
14158 @tab
14159 @smallexample @c ada
14160 Clear :
14161    for J in 1 .. 10 loop
14162       A (J) := 0;
14163    end loop Clear;
14164 @end smallexample
14165 @end multitable
14166 @end cartouche
14167 @end iftex
14169 @ifnottex
14170 @smallexample
14171 @cartouche
14172 GNAT style, compact layout              Uncompact layout
14174 type q is record                        type q is
14175    a : integer;                            record
14176    b : integer;                               a : integer;
14177 end record;                                   b : integer;
14178                                            end record;
14180 for q use record                        for q use
14181    a at 0 range  0 .. 31;                  record
14182    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
14183 end record;                                   b at 4 range  0 .. 31;
14184                                            end record;
14186 Block : declare                         Block :
14187    A : Integer := 3;                       declare
14188 begin                                         A : Integer := 3;
14189    Proc (A, A);                            begin
14190 end Block;                                    Proc (A, A);
14191                                            end Block;
14193 Clear : for J in 1 .. 10 loop           Clear :
14194    A (J) := 0;                             for J in 1 .. 10 loop
14195 end loop Clear;                               A (J) := 0;
14196                                            end loop Clear;
14197 @end cartouche
14198 @end smallexample
14199 @end ifnottex
14201 @noindent
14202 A further difference between GNAT style layout and compact layout is that
14203 GNAT style layout inserts empty lines as separation for
14204 compound statements, return statements and bodies.
14206 Note that the layout specified by
14207 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14208 for named block and loop statements overrides the layout defined by these
14209 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14210 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14211 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14213 @node Name Casing
14214 @subsection Name Casing
14216 @noindent
14217 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14218 the same casing as the corresponding defining identifier.
14220 You control the casing for defining occurrences via the
14221 @option{^-n^/NAME_CASING^} switch.
14222 @ifclear vms
14223 With @option{-nD} (``as declared'', which is the default),
14224 @end ifclear
14225 @ifset vms
14226 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14227 @end ifset
14228 defining occurrences appear exactly as in the source file
14229 where they are declared.
14230 The other ^values for this switch^options for this qualifier^ ---
14231 @option{^-nU^UPPER_CASE^},
14232 @option{^-nL^LOWER_CASE^},
14233 @option{^-nM^MIXED_CASE^} ---
14234 result in
14235 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14236 If @command{gnatpp} changes the casing of a defining
14237 occurrence, it analogously changes the casing of all the
14238 usage occurrences of this name.
14240 If the defining occurrence of a name is not in the source compilation unit
14241 currently being processed by @command{gnatpp}, the casing of each reference to
14242 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14243 switch (subject to the dictionary file mechanism described below).
14244 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14245 had affected the
14246 casing for the defining occurrence of the name.
14248 Some names may need to be spelled with casing conventions that are not
14249 covered by the upper-, lower-, and mixed-case transformations.
14250 You can arrange correct casing by placing such names in a
14251 @emph{dictionary file},
14252 and then supplying a @option{^-D^/DICTIONARY^} switch.
14253 The casing of names from dictionary files overrides
14254 any @option{^-n^/NAME_CASING^} switch.
14256 To handle the casing of Ada predefined names and the names from GNAT libraries,
14257 @command{gnatpp} assumes a default dictionary file.
14258 The name of each predefined entity is spelled with the same casing as is used
14259 for the entity in the @cite{Ada Reference Manual}.
14260 The name of each entity in the GNAT libraries is spelled with the same casing
14261 as is used in the declaration of that entity.
14263 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14264 default dictionary file.
14265 Instead, the casing for predefined and GNAT-defined names will be established
14266 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14267 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14268 will appear as just shown,
14269 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14270 To ensure that even such names are rendered in uppercase,
14271 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14272 (or else, less conveniently, place these names in upper case in a dictionary
14273 file).
14275 A dictionary file is
14276 a plain text file; each line in this file can be either a blank line
14277 (containing only space characters and ASCII.HT characters), an Ada comment
14278 line, or the specification of exactly one @emph{casing schema}.
14280 A casing schema is a string that has the following syntax:
14282 @smallexample
14283 @cartouche
14284   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14286   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14287 @end cartouche
14288 @end smallexample
14290 @noindent
14291 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14292 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14294 The casing schema string can be followed by white space and/or an Ada-style
14295 comment; any amount of white space is allowed before the string.
14297 If a dictionary file is passed as
14298 @ifclear vms
14299 the value of a @option{-D@var{file}} switch
14300 @end ifclear
14301 @ifset vms
14302 an option to the @option{/DICTIONARY} qualifier
14303 @end ifset
14304 then for every
14305 simple name and every identifier, @command{gnatpp} checks if the dictionary
14306 defines the casing for the name or for some of its parts (the term ``subword''
14307 is used below to denote the part of a name which is delimited by ``_'' or by
14308 the beginning or end of the word and which does not contain any ``_'' inside):
14310 @itemize @bullet
14311 @item
14312 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14313 the casing defined by the dictionary; no subwords are checked for this word
14315 @item
14316 for every subword @command{gnatpp} checks if the dictionary contains the
14317 corresponding string of the form @code{*@var{simple_identifier}*},
14318 and if it does, the casing of this @var{simple_identifier} is used
14319 for this subword
14321 @item
14322 if the whole name does not contain any ``_'' inside, and if for this name
14323 the dictionary contains two entries - one of the form @var{identifier},
14324 and another - of the form *@var{simple_identifier}*, then the first one
14325 is applied to define the casing of this name
14327 @item
14328 if more than one dictionary file is passed as @command{gnatpp} switches, each
14329 dictionary adds new casing exceptions and overrides all the existing casing
14330 exceptions set by the previous dictionaries
14332 @item
14333 when @command{gnatpp} checks if the word or subword is in the dictionary,
14334 this check is not case sensitive
14335 @end itemize
14337 @noindent
14338 For example, suppose we have the following source to reformat:
14340 @smallexample @c ada
14341 @cartouche
14342 procedure test is
14343    name1 : integer := 1;
14344    name4_name3_name2 : integer := 2;
14345    name2_name3_name4 : Boolean;
14346    name1_var : Float;
14347 begin
14348    name2_name3_name4 := name4_name3_name2 > name1;
14349 end;
14350 @end cartouche
14351 @end smallexample
14353 @noindent
14354 And suppose we have two dictionaries:
14356 @smallexample
14357 @cartouche
14358 @i{dict1:}
14359    NAME1
14360    *NaMe3*
14361    *Name1*
14362 @end cartouche
14364 @cartouche
14365 @i{dict2:}
14366   *NAME3*
14367 @end cartouche
14368 @end smallexample
14370 @noindent
14371 If @command{gnatpp} is called with the following switches:
14373 @smallexample
14374 @ifclear vms
14375 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14376 @end ifclear
14377 @ifset vms
14378 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14379 @end ifset
14380 @end smallexample
14382 @noindent
14383 then we will get the following name casing in the @command{gnatpp} output:
14385 @smallexample @c ada
14386 @cartouche
14387 procedure Test is
14388    NAME1             : Integer := 1;
14389    Name4_NAME3_Name2 : Integer := 2;
14390    Name2_NAME3_Name4 : Boolean;
14391    Name1_Var         : Float;
14392 begin
14393    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14394 end Test;
14395 @end cartouche
14396 @end smallexample
14398 @c *********************************
14399 @node The GNAT Metric Tool gnatmetric
14400 @chapter The GNAT Metric Tool @command{gnatmetric}
14401 @findex gnatmetric
14402 @cindex Metric tool
14404 @noindent
14405 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14406 for computing various program metrics.
14407 It takes an Ada source file as input and generates a file containing the
14408 metrics data as output. Various switches control which
14409 metrics are computed and output.
14411 @command{gnatmetric} generates and uses the ASIS
14412 tree for the input source and thus requires the input to be syntactically and
14413 semantically legal.
14414 If this condition is not met, @command{gnatmetric} will generate
14415 an error message; no metric information for this file will be
14416 computed and reported.
14418 If the compilation unit contained in the input source depends semantically
14419 upon units in files located outside the current directory, you have to provide
14420 the source search path when invoking @command{gnatmetric}.
14421 If it depends semantically upon units that are contained
14422 in files with names that do not follow the GNAT file naming rules, you have to
14423 provide the configuration file describing the corresponding naming scheme (see
14424 the description of the @command{gnatmetric} switches below.)
14425 Alternatively, you may use a project file and invoke @command{gnatmetric}
14426 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14428 The @command{gnatmetric} command has the form
14430 @smallexample
14431 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14432 @c Expanding @ovar macro inline (explanation in macro def comments)
14433 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14434 @end smallexample
14436 @noindent
14437 where
14438 @itemize @bullet
14439 @item
14440 @var{switches} specify the metrics to compute and define the destination for
14441 the output
14443 @item
14444 Each @var{filename} is the name (including the extension) of a source
14445 file to process. ``Wildcards'' are allowed, and
14446 the file name may contain path information.
14447 If no @var{filename} is supplied, then the @var{switches} list must contain
14448 at least one
14449 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14450 Including both a @option{-files} switch and one or more
14451 @var{filename} arguments is permitted.
14453 @item
14454 @samp{@var{gcc_switches}} is a list of switches for
14455 @command{gcc}. They will be passed on to all compiler invocations made by
14456 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14457 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14458 and use the @option{-gnatec} switch to set the configuration file,
14459 use the @option{-gnat05} switch if sources should be compiled in
14460 Ada 2005 mode etc.
14461 @end itemize
14463 @menu
14464 * Switches for gnatmetric::
14465 @end menu
14467 @node Switches for gnatmetric
14468 @section Switches for @command{gnatmetric}
14470 @noindent
14471 The following subsections describe the various switches accepted by
14472 @command{gnatmetric}, organized by category.
14474 @menu
14475 * Output Files Control::
14476 * Disable Metrics For Local Units::
14477 * Specifying a set of metrics to compute::
14478 * Other gnatmetric Switches::
14479 * Generate project-wide metrics::
14480 @end menu
14482 @node Output Files Control
14483 @subsection Output File Control
14484 @cindex Output file control in @command{gnatmetric}
14486 @noindent
14487 @command{gnatmetric} has two output formats. It can generate a
14488 textual (human-readable) form, and also XML. By default only textual
14489 output is generated.
14491 When generating the output in textual form, @command{gnatmetric} creates
14492 for each Ada source file a corresponding text file
14493 containing the computed metrics, except for the case when the set of metrics
14494 specified by gnatmetric parameters consists only of metrics that are computed
14495 for the whole set of analyzed sources, but not for each Ada source.
14496 By default, this file is placed in the same directory as where the source
14497 file is located, and its name is obtained
14498 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14499 input file.
14501 All the output information generated in XML format is placed in a single
14502 file. By default this file is placed in the current directory and has the
14503 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14505 Some of the computed metrics are summed over the units passed to
14506 @command{gnatmetric}; for example, the total number of lines of code.
14507 By default this information is sent to @file{stdout}, but a file
14508 can be specified with the @option{-og} switch.
14510 The following switches control the @command{gnatmetric} output:
14512 @table @option
14513 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14514 @item ^-x^/XML^
14515 Generate the XML output
14517 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14518 @item ^-xs^/XSD^
14519 Generate the XML output and the XML schema file that describes the structure
14520 of the XML metric report, this schema is assigned to the XML file. The schema
14521 file has the same name as the XML output file with @file{.xml} suffix replaced
14522 with @file{.xsd}
14524 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14525 @item ^-nt^/NO_TEXT^
14526 Do not generate the output in text form (implies @option{^-x^/XML^})
14528 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14529 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14530 Put text files with detailed metrics into @var{output_dir}
14532 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14533 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14534 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14535 in the name of the output file.
14537 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14538 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14539 Put global metrics into @var{file_name}
14541 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14542 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14543 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14545 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14546 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14547 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14548 output includes the name(s) of the Ada source file(s) from which the metrics
14549 are computed.  By default each name includes the absolute path. The
14550 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14551 to exclude all directory information from the file names that are output.)
14553 @end table
14555 @node Disable Metrics For Local Units
14556 @subsection Disable Metrics For Local Units
14557 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14559 @noindent
14560 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14561 one compilation
14562 unit per one source file. It computes line metrics for the whole source
14563 file, and it also computes syntax
14564 and complexity metrics for the file's outermost unit.
14566 By default, @command{gnatmetric} will also compute all metrics for certain
14567 kinds of locally declared program units:
14569 @itemize @bullet
14570 @item
14571 subprogram (and generic subprogram) bodies;
14573 @item
14574 package (and generic package) specs and bodies;
14576 @item
14577 task object and type specifications and bodies;
14579 @item
14580 protected object and type specifications and bodies.
14581 @end itemize
14583 @noindent
14584 These kinds of entities will be referred to as
14585 @emph{eligible local program units}, or simply @emph{eligible local units},
14586 @cindex Eligible local unit (for @command{gnatmetric})
14587 in the discussion below.
14589 Note that a subprogram declaration, generic instantiation,
14590 or renaming declaration only receives metrics
14591 computation when it appear as the outermost entity
14592 in a source file.
14594 Suppression of metrics computation for eligible local units can be
14595 obtained via the following switch:
14597 @table @option
14598 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14599 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14600 Do not compute detailed metrics for eligible local program units
14602 @end table
14604 @node Specifying a set of metrics to compute
14605 @subsection Specifying a set of metrics to compute
14607 @noindent
14608 By default all the metrics are computed and reported. The switches
14609 described in this subsection allow you to control, on an individual
14610 basis, whether metrics are computed and
14611 reported. If at least one positive metric
14612 switch is specified (that is, a switch that defines that a given
14613 metric or set of metrics is to be computed), then only
14614 explicitly specified metrics are reported.
14616 @menu
14617 * Line Metrics Control::
14618 * Syntax Metrics Control::
14619 * Complexity Metrics Control::
14620 * Coupling Metrics Control::
14621 @end menu
14623 @node Line Metrics Control
14624 @subsubsection Line Metrics Control
14625 @cindex Line metrics control in @command{gnatmetric}
14627 @noindent
14628 For any (legal) source file, and for each of its
14629 eligible local program units, @command{gnatmetric} computes the following
14630 metrics:
14632 @itemize @bullet
14633 @item
14634 the total number of lines;
14636 @item
14637 the total number of code lines (i.e., non-blank lines that are not comments)
14639 @item
14640 the number of comment lines
14642 @item
14643 the number of code lines containing end-of-line comments;
14645 @item
14646 the comment percentage: the ratio between the number of lines that contain
14647 comments and the number of all non-blank lines, expressed as a percentage;
14649 @item
14650 the number of empty lines and lines containing only space characters and/or
14651 format effectors (blank lines)
14653 @item
14654 the average number of code lines in subprogram bodies, task bodies, entry
14655 bodies and statement sequences in package bodies (this metric is only computed
14656 across the whole set of the analyzed units)
14658 @end itemize
14660 @noindent
14661 @command{gnatmetric} sums the values of the line metrics for all the
14662 files being processed and then generates the cumulative results. The tool
14663 also computes for all the files being processed the average number of code
14664 lines in bodies.
14666 You can use the following switches to select the specific line metrics
14667 to be computed and reported.
14669 @table @option
14670 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14672 @ifclear vms
14673 @cindex @option{--no-lines@var{x}}
14674 @end ifclear
14676 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14677 Report all the line metrics
14679 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14680 Do not report any of line metrics
14682 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14683 Report the number of all lines
14685 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14686 Do not report the number of all lines
14688 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14689 Report the number of code lines
14691 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14692 Do not report the number of code lines
14694 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14695 Report the number of comment lines
14697 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14698 Do not report the number of comment lines
14700 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14701 Report the number of code lines containing
14702 end-of-line comments
14704 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14705 Do not report the number of code lines containing
14706 end-of-line comments
14708 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14709 Report the comment percentage in the program text
14711 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14712 Do not report the comment percentage in the program text
14714 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14715 Report the number of blank lines
14717 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14718 Do not report the number of blank lines
14720 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14721 Report the average number of code lines in subprogram bodies, task bodies,
14722 entry bodies and statement sequences in package bodies. The metric is computed
14723 and reported for the whole set of processed Ada sources only.
14725 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14726 Do not report the average number of code lines in subprogram bodies,
14727 task bodies, entry bodies and statement sequences in package bodies.
14729 @end table
14731 @node Syntax Metrics Control
14732 @subsubsection Syntax Metrics Control
14733 @cindex Syntax metrics control in @command{gnatmetric}
14735 @noindent
14736 @command{gnatmetric} computes various syntactic metrics for the
14737 outermost unit and for each eligible local unit:
14739 @table @emph
14740 @item LSLOC (``Logical Source Lines Of Code'')
14741 The total number of declarations and the total number of statements. Note
14742 that the definition of declarations is the one given in the reference
14743 manual:
14745 @noindent
14746 ``Each of the following is defined to be a declaration: any basic_declaration;
14747 an enumeration_literal_specification; a discriminant_specification;
14748 a component_declaration; a loop_parameter_specification; a
14749 parameter_specification; a subprogram_body; an entry_declaration;
14750 an entry_index_specification; a choice_parameter_specification;
14751 a generic_formal_parameter_declaration.''
14753 This means for example that each enumeration literal adds one to the count,
14754 as well as each subprogram parameter.
14756 Thus the results from this metric will be significantly greater than might
14757 be expected from a naive view of counting semicolons.
14759 @item Maximal static nesting level of inner program units
14760 According to
14761 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14762 package, a task unit, a protected unit, a
14763 protected entry, a generic unit, or an explicitly declared subprogram other
14764 than an enumeration literal.''
14766 @item Maximal nesting level of composite syntactic constructs
14767 This corresponds to the notion of the
14768 maximum nesting level in the GNAT built-in style checks
14769 (@pxref{Style Checking})
14770 @end table
14772 @noindent
14773 For the outermost unit in the file, @command{gnatmetric} additionally computes
14774 the following metrics:
14776 @table @emph
14777 @item Public subprograms
14778 This metric is computed for package specs. It is the
14779 number of subprograms and generic subprograms declared in the visible
14780 part (including the visible part of nested packages, protected objects, and
14781 protected types).
14783 @item All subprograms
14784 This metric is computed for bodies and subunits. The
14785 metric is equal to a total number of subprogram bodies in the compilation
14786 unit.
14787 Neither generic instantiations nor renamings-as-a-body nor body stubs
14788 are counted. Any subprogram body is counted, independently of its nesting
14789 level and enclosing constructs. Generic bodies and bodies of protected
14790 subprograms are counted in the same way as ``usual'' subprogram bodies.
14792 @item Public types
14793 This metric is computed for package specs and
14794 generic package declarations. It is the total number of types
14795 that can be referenced from outside this compilation unit, plus the
14796 number of types from all the visible parts of all the visible generic
14797 packages. Generic formal types are not counted.  Only types, not subtypes,
14798 are included.
14800 @noindent
14801 Along with the total number of public types, the following
14802 types are counted and reported separately:
14804 @itemize @bullet
14805 @item
14806 Abstract types
14808 @item
14809 Root tagged types (abstract, non-abstract, private, non-private). Type
14810 extensions are @emph{not} counted
14812 @item
14813 Private types (including private extensions)
14815 @item
14816 Task types
14818 @item
14819 Protected types
14821 @end itemize
14823 @item All types
14824 This metric is computed for any compilation unit. It is equal to the total
14825 number of the declarations of different types given in the compilation unit.
14826 The private and the corresponding full type declaration are counted as one
14827 type declaration. Incomplete type declarations and generic formal types
14828 are not counted.
14829 No distinction is made among different kinds of types (abstract,
14830 private etc.); the total number of types is computed and reported.
14832 @end table
14834 @noindent
14835 By default, all the syntax metrics are computed and reported. You can use the
14836 following switches to select specific syntax metrics.
14838 @table @option
14840 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14842 @ifclear vms
14843 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14844 @end ifclear
14846 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14847 Report all the syntax metrics
14849 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14850 Do not report any of syntax metrics
14852 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14853 Report the total number of declarations
14855 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14856 Do not report the total number of declarations
14858 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14859 Report the total number of statements
14861 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14862 Do not report the total number of statements
14864 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14865 Report the number of public subprograms in a compilation unit
14867 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14868 Do not report the number of public subprograms in a compilation unit
14870 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14871 Report the number of all the subprograms in a compilation unit
14873 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14874 Do not report the number of all the subprograms in a compilation unit
14876 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14877 Report the number of public types in a compilation unit
14879 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14880 Do not report the number of public types in a compilation unit
14882 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14883 Report the number of all the types in a compilation unit
14885 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14886 Do not report the number of all the types in a compilation unit
14888 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14889 Report the maximal program unit nesting level
14891 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14892 Do not report the maximal program unit nesting level
14894 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14895 Report the maximal construct nesting level
14897 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14898 Do not report the maximal construct nesting level
14900 @end table
14902 @node Complexity Metrics Control
14903 @subsubsection Complexity Metrics Control
14904 @cindex Complexity metrics control in @command{gnatmetric}
14906 @noindent
14907 For a program unit that is an executable body (a subprogram body (including
14908 generic bodies), task body, entry body or a package body containing
14909 its own statement sequence) @command{gnatmetric} computes the following
14910 complexity metrics:
14912 @itemize @bullet
14913 @item
14914 McCabe cyclomatic complexity;
14916 @item
14917 McCabe essential complexity;
14919 @item
14920 maximal loop nesting level;
14922 @item
14923 extra exit points (for subprograms);
14924 @end itemize
14926 @noindent
14927 The McCabe cyclomatic complexity metric is defined
14928 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14930 According to McCabe, both control statements and short-circuit control forms
14931 should be taken into account when computing cyclomatic complexity.
14932 For Ada 2012 we have also take into account conditional expressions
14933 and quantified expressions. For each body, we compute three metric values:
14935 @itemize @bullet
14936 @item
14937 the complexity introduced by control
14938 statements only, without taking into account short-circuit forms,
14940 @item
14941 the complexity introduced by short-circuit control forms only, and
14943 @item
14944 the total
14945 cyclomatic complexity, which is the sum of these two values.
14946 @end itemize
14948 @noindent
14950 The cyclomatic complexity is also computed for Ada 2012 expression functions.
14951 An expression function cannot have statements as its components, so only one
14952 metric value is computed as a cyclomatic complexity of an expression function.
14954 The origin of cyclomatic complexity metric is the need to estimate the number
14955 of independent paths in the control flow graph that in turn gives the number
14956 of tests needed to satisfy paths coverage testing completeness criterion.
14957 Considered from the testing point of view, a static Ada @code{loop} (that is,
14958 the @code{loop} statement having static subtype in loop parameter
14959 specification) does not add to cyclomatic complexity. By providing
14960 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14961 may specify that such loops should not be counted when computing the
14962 cyclomatic complexity metric
14964 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14965 counted for the code that is reduced by excluding all the pure structural Ada
14966 control statements. An compound statement is considered as a non-structural
14967 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14968 or if it contains a @code{goto} statement that transfers the control outside
14969 the operator. A selective accept statement with @code{terminate} alternative
14970 is considered as non-structural statement. When computing this metric,
14971 @code{exit} statements are treated in the same way as @code{goto}
14972 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14974 The Ada essential complexity metric defined here is intended to quantify
14975 the extent to which the software is unstructured. It is adapted from
14976 the McCabe essential complexity metric defined in
14977 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
14978 suitable for typical Ada usage. For example, short circuit forms
14979 are not penalized as unstructured in the Ada essential complexity metric.
14981 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14982 the code in the exception handlers and in all the nested program units. The
14983 code of assertions and predicates (that is, subprogram preconditions and
14984 postconditions, subtype predicates and type invariants) is also skipped.
14986 By default, all the complexity metrics are computed and reported.
14987 For more fine-grained control you can use
14988 the following switches:
14990 @table @option
14991 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14993 @ifclear vms
14994 @cindex @option{--no-complexity@var{x}}
14995 @end ifclear
14997 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14998 Report all the complexity metrics
15000 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
15001 Do not report any of complexity metrics
15003 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
15004 Report the McCabe Cyclomatic Complexity
15006 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
15007 Do not report the McCabe Cyclomatic Complexity
15009 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
15010 Report the Essential Complexity
15012 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
15013 Do not report the Essential Complexity
15015 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
15016 Report maximal loop nesting level
15018 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
15019 Do not report maximal loop nesting level
15021 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
15022 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15023 task bodies, entry bodies and statement sequences in package bodies.
15024 The metric is computed and reported for whole set of processed Ada sources
15025 only.
15027 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
15028 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15029 bodies, task bodies, entry bodies and statement sequences in package bodies
15031 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
15032 @item ^-ne^/NO_EXITS_AS_GOTOS^
15033 Do not consider @code{exit} statements as @code{goto}s when
15034 computing Essential Complexity
15036 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
15037 @item ^--no-static-loop^/NO_STATIC_LOOP^
15038 Do not consider static loops when computing cyclomatic complexity
15040 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
15041 Report the extra exit points for subprogram bodies. As an exit point, this
15042 metric counts @code{return} statements and raise statements in case when the
15043 raised exception is not handled in the same body. In case of a function this
15044 metric subtracts 1 from the number of exit points, because a function body
15045 must contain at least one @code{return} statement.
15047 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
15048 Do not report the extra exit points for subprogram bodies
15049 @end table
15052 @node Coupling Metrics Control
15053 @subsubsection Coupling Metrics Control
15054 @cindex Coupling metrics control in @command{gnatmetric}
15056 @noindent
15057 @cindex Coupling metrics (in in @command{gnatmetric})
15058 Coupling metrics measure the dependencies between a given entity and other
15059 entities the program consists of. The goal of these metrics is to estimate the
15060 stability of the whole program considered as the collection of entities
15061 (modules, classes etc.).
15063 Gnatmetric computes the following coupling metrics:
15065 @itemize @bullet
15067 @item
15068 @emph{object-oriented coupling} - for classes in traditional object-oriented
15069 sense;
15071 @item
15072 @emph{unit coupling} - for all the program units making up a program;
15074 @item
15075 @emph{control coupling} - this metric counts dependencies between a unit and
15076 only those units that define subprograms;
15077 @end itemize
15079 @noindent
15080 Two kinds of coupling metrics are computed:
15082 @table @asis
15083 @item fan-out coupling (efferent coupling)
15084 @cindex fan-out coupling
15085 @cindex efferent coupling
15086 the number of entities the given entity depends upon. It
15087 estimates in what extent the given entity depends on the changes in
15088 ``external world''
15090 @item fan-in coupling (afferent coupling)
15091 @cindex fan-in coupling
15092 @cindex afferent coupling
15093 the number of entities that depend on a given entity.
15094 It estimates in what extent the ``external world'' depends on the changes in a
15095 given entity
15096 @end table
15098 @noindent
15100 Object-oriented coupling metrics are metrics that measure the dependencies
15101 between a given class (or a group of classes) and the other classes in the
15102 program. In this subsection the term ``class'' is used in its traditional
15103 object-oriented programming sense (an instantiable module that contains data
15104 and/or method members). A @emph{category} (of classes) is a group of closely
15105 related classes that are reused and/or modified together.
15107 A class @code{K}'s fan-out coupling is the number of classes
15108 that @code{K} depends upon.
15109 A category's fan-out coupling is the number of classes outside the
15110 category that the classes inside the category depend upon.
15112 A class @code{K}'s fan-in coupling is the number of classes
15113 that depend upon @code{K}.
15114 A category's fan-in coupling is the number of classes outside the
15115 category that depend on classes belonging to the category.
15117 Ada's implementation of the object-oriented paradigm does not use the
15118 traditional class notion, so the definition of the coupling
15119 metrics for Ada maps the class and class category notions
15120 onto Ada constructs.
15122 For the coupling metrics, several kinds of modules -- a library package,
15123 a library generic package, and a library generic package instantiation --
15124 that define a tagged type or an interface type are
15125 considered to be a class. A category consists of a library package (or
15126 a library generic package) that defines a tagged or an interface type,
15127 together with all its descendant (generic) packages that define tagged
15128 or interface types. That is a
15129 category is an Ada hierarchy of library-level program units. So class coupling
15130 in case of Ada is called as tagged coupling, and category coupling - as
15131 hierarchy coupling.
15133 For any package counted as a class, its body and subunits (if any) are
15134 considered together with its spec when counting the dependencies, and coupling
15135 metrics are reported for spec units only. For dependencies between classes,
15136 the Ada semantic dependencies are considered. For object-oriented coupling
15137 metrics, only dependencies on units that are considered as classes, are
15138 considered.
15140 For unit and control coupling also not compilation units but program units are
15141 counted. That is, for a package, its spec, its body and its subunits (if any)
15142 are considered as making up one unit, and the dependencies that are counted
15143 are the dependencies of all these compilation units collected together as
15144 the dependencies as a (whole) unit. And metrics are reported for spec
15145 compilation units only (or for a subprogram body unit in case if there is no
15146 separate spec for the given subprogram).
15148 For unit coupling, dependencies between all kinds of program units are
15149 considered. For control coupling, for each unit the dependencies of this unit
15150 upon units that define subprograms are counted, so control fan-out coupling
15151 is reported for all units, but control fan-in coupling - only for the units
15152 that define subprograms.
15154 The following simple example illustrates the difference between unit coupling
15155 and control coupling metrics:
15157 @smallexample @c ada
15158 package Lib_1 is
15159     function F_1 (I : Integer) return Integer;
15160 end Lib_1;
15162 package Lib_2 is
15163     type T_2 is new Integer;
15164 end Lib_2;
15166 package body Lib_1 is
15167     function F_1 (I : Integer) return Integer is
15168     begin
15169        return I + 1;
15170     end F_1;
15171 end Lib_1;
15173 with Lib_2; use Lib_2;
15174 package Pack is
15175     Var : T_2;
15176     function Fun (I : Integer) return Integer;
15177 end Pack;
15179 with Lib_1; use Lib_1;
15180 package body Pack is
15181     function Fun (I : Integer) return Integer is
15182     begin
15183        return F_1 (I);
15184     end Fun;
15185 end Pack;
15186 @end smallexample
15188 @noindent
15189 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
15190 units, the result will be:
15192 @smallexample
15193 Coupling metrics:
15194 =================
15195     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15196        control fan-out coupling  : 0
15197        control fan-in coupling   : 1
15198        unit fan-out coupling     : 0
15199        unit fan-in coupling      : 1
15201     Unit Pack (C:\customers\662\L406-007\pack.ads)
15202        control fan-out coupling  : 1
15203        control fan-in coupling   : 0
15204        unit fan-out coupling     : 2
15205        unit fan-in coupling      : 0
15207     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15208        control fan-out coupling  : 0
15209        unit fan-out coupling     : 0
15210        unit fan-in coupling      : 1
15211 @end smallexample
15213 @noindent
15214 The result does not contain values for object-oriented
15215 coupling because none of the argument unit contains a tagged type and
15216 therefore none of these units can be treated as a class.
15218 @code{Pack} (considered as a program unit, that is spec+body) depends on two
15219 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
15220 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
15221 well as control fan-in coupling. Only one of the units @code{Pack} depends
15222 upon defines a subprogram, so its control fan-out coupling is 1.
15224 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
15225 not define a subprogram, so control fan-in metric cannot be applied to it,
15226 and there is one unit that depends on it (@code{Pack}), so it has
15227 unit fan-in coupling equals to 1.
15229 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15230 So it has control fan-in coupling equals to 1 (because there is a unit
15231 depending on it).
15233 When computing coupling metrics, @command{gnatmetric} counts only
15234 dependencies between units that are arguments of the @command{gnatmetric}
15235 call. Coupling metrics are program-wide (or project-wide) metrics, so to
15236 get a valid result, you should call @command{gnatmetric} for
15237 the whole set of sources that make up your program. It can be done
15238 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
15239 option (see @ref{The GNAT Driver and Project Files} for details).
15241 By default, all the coupling metrics are disabled. You can use the following
15242 switches to specify the coupling metrics to be computed and reported:
15244 @table @option
15246 @ifclear vms
15247 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15248 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15249 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15250 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15251 @end ifclear
15253 @ifset vms
15254 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
15255 @end ifset
15257 @item ^--coupling-all^/COUPLING_METRICS=ALL^
15258 Report all the coupling metrics
15260 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
15261 Report tagged (class) fan-out coupling
15263 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
15264 Report tagged (class) fan-in coupling
15266 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
15267 Report hierarchy (category) fan-out coupling
15269 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
15270 Report hierarchy (category) fan-in coupling
15272 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
15273 Report unit fan-out coupling
15275 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
15276 Report unit fan-in coupling
15278 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
15279 Report control fan-out coupling
15281 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
15282 Report control fan-in coupling
15283 @end table
15285 @node Other gnatmetric Switches
15286 @subsection Other @code{gnatmetric} Switches
15288 @noindent
15289 Additional @command{gnatmetric} switches are as follows:
15291 @table @option
15292 @item ^-files @var{filename}^/FILES=@var{filename}^
15293 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15294 Take the argument source files from the specified file. This file should be an
15295 ordinary text file containing file names separated by spaces or
15296 line breaks. You can use this switch more than once in the same call to
15297 @command{gnatmetric}. You also can combine this switch with
15298 an explicit list of files.
15300 @item ^-v^/VERBOSE^
15301 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15302 Verbose mode;
15303 @command{gnatmetric} generates version information and then
15304 a trace of sources being processed.
15306 @item ^-q^/QUIET^
15307 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15308 Quiet mode.
15309 @end table
15311 @node Generate project-wide metrics
15312 @subsection Generate project-wide metrics
15314 In order to compute metrics on all units of a given project, you can use
15315 the @command{gnat} driver along with the @option{-P} option:
15316 @smallexample
15317    gnat metric -Pproj
15318 @end smallexample
15320 @noindent
15321 If the project @code{proj} depends upon other projects, you can compute
15322 the metrics on the project closure using the @option{-U} option:
15323 @smallexample
15324    gnat metric -Pproj -U
15325 @end smallexample
15327 @noindent
15328 Finally, if not all the units are relevant to a particular main
15329 program in the project closure, you can generate metrics for the set
15330 of units needed to create a given main program (unit closure) using
15331 the @option{-U} option followed by the name of the main unit:
15332 @smallexample
15333    gnat metric -Pproj -U main
15334 @end smallexample
15337 @c ***********************************
15338 @node File Name Krunching Using gnatkr
15339 @chapter File Name Krunching Using @code{gnatkr}
15340 @findex gnatkr
15342 @noindent
15343 This chapter discusses the method used by the compiler to shorten
15344 the default file names chosen for Ada units so that they do not
15345 exceed the maximum length permitted. It also describes the
15346 @code{gnatkr} utility that can be used to determine the result of
15347 applying this shortening.
15348 @menu
15349 * About gnatkr::
15350 * Using gnatkr::
15351 * Krunching Method::
15352 * Examples of gnatkr Usage::
15353 @end menu
15355 @node About gnatkr
15356 @section About @code{gnatkr}
15358 @noindent
15359 The default file naming rule in GNAT
15360 is that the file name must be derived from
15361 the unit name. The exact default rule is as follows:
15362 @itemize @bullet
15363 @item
15364 Take the unit name and replace all dots by hyphens.
15365 @item
15366 If such a replacement occurs in the
15367 second character position of a name, and the first character is
15368 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15369 then replace the dot by the character
15370 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15371 instead of a minus.
15372 @end itemize
15373 The reason for this exception is to avoid clashes
15374 with the standard names for children of System, Ada, Interfaces,
15375 and GNAT, which use the prefixes
15376 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15377 respectively.
15379 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15380 switch of the compiler activates a ``krunching''
15381 circuit that limits file names to nn characters (where nn is a decimal
15382 integer). For example, using OpenVMS,
15383 where the maximum file name length is
15384 39, the value of nn is usually set to 39, but if you want to generate
15385 a set of files that would be usable if ported to a system with some
15386 different maximum file length, then a different value can be specified.
15387 The default value of 39 for OpenVMS need not be specified.
15389 The @code{gnatkr} utility can be used to determine the krunched name for
15390 a given file, when krunched to a specified maximum length.
15392 @node Using gnatkr
15393 @section Using @code{gnatkr}
15395 @noindent
15396 The @code{gnatkr} command has the form
15398 @ifclear vms
15399 @smallexample
15400 @c $ gnatkr @var{name} @ovar{length}
15401 @c Expanding @ovar macro inline (explanation in macro def comments)
15402 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15403 @end smallexample
15404 @end ifclear
15406 @ifset vms
15407 @smallexample
15408 $ gnatkr @var{name} /COUNT=nn
15409 @end smallexample
15410 @end ifset
15412 @noindent
15413 @var{name} is the uncrunched file name, derived from the name of the unit
15414 in the standard manner described in the previous section (i.e., in particular
15415 all dots are replaced by hyphens). The file name may or may not have an
15416 extension (defined as a suffix of the form period followed by arbitrary
15417 characters other than period). If an extension is present then it will
15418 be preserved in the output. For example, when krunching @file{hellofile.ads}
15419 to eight characters, the result will be hellofil.ads.
15421 Note: for compatibility with previous versions of @code{gnatkr} dots may
15422 appear in the name instead of hyphens, but the last dot will always be
15423 taken as the start of an extension. So if @code{gnatkr} is given an argument
15424 such as @file{Hello.World.adb} it will be treated exactly as if the first
15425 period had been a hyphen, and for example krunching to eight characters
15426 gives the result @file{hellworl.adb}.
15428 Note that the result is always all lower case (except on OpenVMS where it is
15429 all upper case). Characters of the other case are folded as required.
15431 @var{length} represents the length of the krunched name. The default
15432 when no argument is given is ^8^39^ characters. A length of zero stands for
15433 unlimited, in other words do not chop except for system files where the
15434 implied crunching length is always eight characters.
15436 @noindent
15437 The output is the krunched name. The output has an extension only if the
15438 original argument was a file name with an extension.
15440 @node Krunching Method
15441 @section Krunching Method
15443 @noindent
15444 The initial file name is determined by the name of the unit that the file
15445 contains. The name is formed by taking the full expanded name of the
15446 unit and replacing the separating dots with hyphens and
15447 using ^lowercase^uppercase^
15448 for all letters, except that a hyphen in the second character position is
15449 replaced by a ^tilde^dollar sign^ if the first character is
15450 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15451 The extension is @code{.ads} for a
15452 spec and @code{.adb} for a body.
15453 Krunching does not affect the extension, but the file name is shortened to
15454 the specified length by following these rules:
15456 @itemize @bullet
15457 @item
15458 The name is divided into segments separated by hyphens, tildes or
15459 underscores and all hyphens, tildes, and underscores are
15460 eliminated. If this leaves the name short enough, we are done.
15462 @item
15463 If the name is too long, the longest segment is located (left-most
15464 if there are two of equal length), and shortened by dropping
15465 its last character. This is repeated until the name is short enough.
15467 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15468 to fit the name into 8 characters as required by some operating systems.
15470 @smallexample
15471 our-strings-wide_fixed 22
15472 our strings wide fixed 19
15473 our string  wide fixed 18
15474 our strin   wide fixed 17
15475 our stri    wide fixed 16
15476 our stri    wide fixe  15
15477 our str     wide fixe  14
15478 our str     wid  fixe  13
15479 our str     wid  fix   12
15480 ou  str     wid  fix   11
15481 ou  st      wid  fix   10
15482 ou  st      wi   fix   9
15483 ou  st      wi   fi    8
15484 Final file name: oustwifi.adb
15485 @end smallexample
15487 @item
15488 The file names for all predefined units are always krunched to eight
15489 characters. The krunching of these predefined units uses the following
15490 special prefix replacements:
15492 @table @file
15493 @item ada-
15494 replaced by @file{^a^A^-}
15496 @item gnat-
15497 replaced by @file{^g^G^-}
15499 @item interfaces-
15500 replaced by @file{^i^I^-}
15502 @item system-
15503 replaced by @file{^s^S^-}
15504 @end table
15506 These system files have a hyphen in the second character position. That
15507 is why normal user files replace such a character with a
15508 ^tilde^dollar sign^, to
15509 avoid confusion with system file names.
15511 As an example of this special rule, consider
15512 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15514 @smallexample
15515 ada-strings-wide_fixed 22
15516 a-  strings wide fixed 18
15517 a-  string  wide fixed 17
15518 a-  strin   wide fixed 16
15519 a-  stri    wide fixed 15
15520 a-  stri    wide fixe  14
15521 a-  str     wide fixe  13
15522 a-  str     wid  fixe  12
15523 a-  str     wid  fix   11
15524 a-  st      wid  fix   10
15525 a-  st      wi   fix   9
15526 a-  st      wi   fi    8
15527 Final file name: a-stwifi.adb
15528 @end smallexample
15529 @end itemize
15531 Of course no file shortening algorithm can guarantee uniqueness over all
15532 possible unit names, and if file name krunching is used then it is your
15533 responsibility to ensure that no name clashes occur. The utility
15534 program @code{gnatkr} is supplied for conveniently determining the
15535 krunched name of a file.
15537 @node Examples of gnatkr Usage
15538 @section Examples of @code{gnatkr} Usage
15540 @smallexample
15541 @iftex
15542 @leftskip=0cm
15543 @end iftex
15544 @ifclear vms
15545 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15546 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15547 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15548 $ gnatkr grandparent-parent-child     --> grparchi
15549 @end ifclear
15550 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15551 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15552 @end smallexample
15554 @node Preprocessing Using gnatprep
15555 @chapter Preprocessing Using @code{gnatprep}
15556 @findex gnatprep
15558 @noindent
15559 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15560 preprocessing.
15561 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15562 special GNAT features.
15563 For further discussion of conditional compilation in general, see
15564 @ref{Conditional Compilation}.
15566 @menu
15567 * Preprocessing Symbols::
15568 * Using gnatprep::
15569 * Switches for gnatprep::
15570 * Form of Definitions File::
15571 * Form of Input Text for gnatprep::
15572 @end menu
15574 @node Preprocessing Symbols
15575 @section Preprocessing Symbols
15577 @noindent
15578 Preprocessing symbols are defined in definition files and referred to in
15579 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15580 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15581 all characters need to be in the ASCII set (no accented letters).
15583 @node Using gnatprep
15584 @section Using @code{gnatprep}
15586 @noindent
15587 To call @code{gnatprep} use
15589 @smallexample
15590 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15591 @c Expanding @ovar macro inline (explanation in macro def comments)
15592 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15593 @end smallexample
15595 @noindent
15596 where
15597 @table @var
15598 @item switches
15599 is an optional sequence of switches as described in the next section.
15601 @item infile
15602 is the full name of the input file, which is an Ada source
15603 file containing preprocessor directives.
15605 @item outfile
15606 is the full name of the output file, which is an Ada source
15607 in standard Ada form. When used with GNAT, this file name will
15608 normally have an ads or adb suffix.
15610 @item deffile
15611 is the full name of a text file containing definitions of
15612 preprocessing symbols to be referenced by the preprocessor. This argument is
15613 optional, and can be replaced by the use of the @option{-D} switch.
15615 @end table
15617 @node Switches for gnatprep
15618 @section Switches for @code{gnatprep}
15620 @table @option
15621 @c !sort!
15623 @item ^-b^/BLANK_LINES^
15624 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15625 Causes both preprocessor lines and the lines deleted by
15626 preprocessing to be replaced by blank lines in the output source file,
15627 preserving line numbers in the output file.
15629 @item ^-c^/COMMENTS^
15630 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15631 Causes both preprocessor lines and the lines deleted
15632 by preprocessing to be retained in the output source as comments marked
15633 with the special string @code{"--! "}. This option will result in line numbers
15634 being preserved in the output file.
15636 @item ^-C^/REPLACE_IN_COMMENTS^
15637 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15638 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15639 If this option is specified, then comments are scanned and any $symbol
15640 substitutions performed as in program text. This is particularly useful
15641 when structured comments are used (e.g., when writing programs in the
15642 SPARK dialect of Ada). Note that this switch is not available when
15643 doing integrated preprocessing (it would be useless in this context
15644 since comments are ignored by the compiler in any case).
15646 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15647 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15648 Defines a new preprocessing symbol, associated with value. If no value is given
15649 on the command line, then symbol is considered to be @code{True}. This switch
15650 can be used in place of a definition file.
15652 @ifset vms
15653 @item /REMOVE
15654 @cindex @option{/REMOVE} (@command{gnatprep})
15655 This is the default setting which causes lines deleted by preprocessing
15656 to be entirely removed from the output file.
15657 @end ifset
15659 @item ^-r^/REFERENCE^
15660 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15661 Causes a @code{Source_Reference} pragma to be generated that
15662 references the original input file, so that error messages will use
15663 the file name of this original file. The use of this switch implies
15664 that preprocessor lines are not to be removed from the file, so its
15665 use will force @option{^-b^/BLANK_LINES^} mode if
15666 @option{^-c^/COMMENTS^}
15667 has not been specified explicitly.
15669 Note that if the file to be preprocessed contains multiple units, then
15670 it will be necessary to @code{gnatchop} the output file from
15671 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15672 in the preprocessed file, it will be respected by
15673 @code{gnatchop ^-r^/REFERENCE^}
15674 so that the final chopped files will correctly refer to the original
15675 input source file for @code{gnatprep}.
15677 @item ^-s^/SYMBOLS^
15678 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15679 Causes a sorted list of symbol names and values to be
15680 listed on the standard output file.
15682 @item ^-u^/UNDEFINED^
15683 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15684 Causes undefined symbols to be treated as having the value FALSE in the context
15685 of a preprocessor test. In the absence of this option, an undefined symbol in
15686 a @code{#if} or @code{#elsif} test will be treated as an error.
15688 @end table
15690 @ifclear vms
15691 @noindent
15692 Note: if neither @option{-b} nor @option{-c} is present,
15693 then preprocessor lines and
15694 deleted lines are completely removed from the output, unless -r is
15695 specified, in which case -b is assumed.
15696 @end ifclear
15698 @node Form of Definitions File
15699 @section Form of Definitions File
15701 @noindent
15702 The definitions file contains lines of the form
15704 @smallexample
15705 symbol := value
15706 @end smallexample
15708 @noindent
15709 where symbol is a preprocessing symbol, and value is one of the following:
15711 @itemize @bullet
15712 @item
15713 Empty, corresponding to a null substitution
15714 @item
15715 A string literal using normal Ada syntax
15716 @item
15717 Any sequence of characters from the set
15718 (letters, digits, period, underline).
15719 @end itemize
15721 @noindent
15722 Comment lines may also appear in the definitions file, starting with
15723 the usual @code{--},
15724 and comments may be added to the definitions lines.
15726 @node Form of Input Text for gnatprep
15727 @section Form of Input Text for @code{gnatprep}
15729 @noindent
15730 The input text may contain preprocessor conditional inclusion lines,
15731 as well as general symbol substitution sequences.
15733 The preprocessor conditional inclusion commands have the form
15735 @smallexample
15736 @group
15737 @cartouche
15738 #if @i{expression} @r{[}then@r{]}
15739    lines
15740 #elsif @i{expression} @r{[}then@r{]}
15741    lines
15742 #elsif @i{expression} @r{[}then@r{]}
15743    lines
15744 @dots{}
15745 #else
15746    lines
15747 #end if;
15748 @end cartouche
15749 @end group
15750 @end smallexample
15752 @noindent
15753 In this example, @i{expression} is defined by the following grammar:
15754 @smallexample
15755 @i{expression} ::=  <symbol>
15756 @i{expression} ::=  <symbol> = "<value>"
15757 @i{expression} ::=  <symbol> = <symbol>
15758 @i{expression} ::=  <symbol> 'Defined
15759 @i{expression} ::=  not @i{expression}
15760 @i{expression} ::=  @i{expression} and @i{expression}
15761 @i{expression} ::=  @i{expression} or @i{expression}
15762 @i{expression} ::=  @i{expression} and then @i{expression}
15763 @i{expression} ::=  @i{expression} or else @i{expression}
15764 @i{expression} ::=  ( @i{expression} )
15765 @end smallexample
15767 The following restriction exists: it is not allowed to have "and" or "or"
15768 following "not" in the same expression without parentheses. For example, this
15769 is not allowed:
15771 @smallexample
15772    not X or Y
15773 @end smallexample
15775 This should be one of the following:
15777 @smallexample
15778    (not X) or Y
15779    not (X or Y)
15780 @end smallexample
15782 @noindent
15783 For the first test (@i{expression} ::= <symbol>) the symbol must have
15784 either the value true or false, that is to say the right-hand of the
15785 symbol definition must be one of the (case-insensitive) literals
15786 @code{True} or @code{False}. If the value is true, then the
15787 corresponding lines are included, and if the value is false, they are
15788 excluded.
15790 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15791 the symbol has been defined in the definition file or by a @option{-D}
15792 switch on the command line. Otherwise, the test is false.
15794 The equality tests are case insensitive, as are all the preprocessor lines.
15796 If the symbol referenced is not defined in the symbol definitions file,
15797 then the effect depends on whether or not switch @option{-u}
15798 is specified. If so, then the symbol is treated as if it had the value
15799 false and the test fails. If this switch is not specified, then
15800 it is an error to reference an undefined symbol. It is also an error to
15801 reference a symbol that is defined with a value other than @code{True}
15802 or @code{False}.
15804 The use of the @code{not} operator inverts the sense of this logical test.
15805 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15806 operators, without parentheses. For example, "if not X or Y then" is not
15807 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15809 The @code{then} keyword is optional as shown
15811 The @code{#} must be the first non-blank character on a line, but
15812 otherwise the format is free form. Spaces or tabs may appear between
15813 the @code{#} and the keyword. The keywords and the symbols are case
15814 insensitive as in normal Ada code. Comments may be used on a
15815 preprocessor line, but other than that, no other tokens may appear on a
15816 preprocessor line. Any number of @code{elsif} clauses can be present,
15817 including none at all. The @code{else} is optional, as in Ada.
15819 The @code{#} marking the start of a preprocessor line must be the first
15820 non-blank character on the line, i.e., it must be preceded only by
15821 spaces or horizontal tabs.
15823 Symbol substitution outside of preprocessor lines is obtained by using
15824 the sequence
15826 @smallexample
15827 $symbol
15828 @end smallexample
15830 @noindent
15831 anywhere within a source line, except in a comment or within a
15832 string literal. The identifier
15833 following the @code{$} must match one of the symbols defined in the symbol
15834 definition file, and the result is to substitute the value of the
15835 symbol in place of @code{$symbol} in the output file.
15837 Note that although the substitution of strings within a string literal
15838 is not possible, it is possible to have a symbol whose defined value is
15839 a string literal. So instead of setting XYZ to @code{hello} and writing:
15841 @smallexample
15842 Header : String := "$XYZ";
15843 @end smallexample
15845 @noindent
15846 you should set XYZ to @code{"hello"} and write:
15848 @smallexample
15849 Header : String := $XYZ;
15850 @end smallexample
15852 @noindent
15853 and then the substitution will occur as desired.
15855 @node The GNAT Library Browser gnatls
15856 @chapter The GNAT Library Browser @code{gnatls}
15857 @findex gnatls
15858 @cindex Library browser
15860 @noindent
15861 @code{gnatls} is a tool that outputs information about compiled
15862 units. It gives the relationship between objects, unit names and source
15863 files. It can also be used to check the source dependencies of a unit
15864 as well as various characteristics.
15866 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15867 driver (see @ref{The GNAT Driver and Project Files}).
15869 @menu
15870 * Running gnatls::
15871 * Switches for gnatls::
15872 * Examples of gnatls Usage::
15873 @end menu
15875 @node Running gnatls
15876 @section Running @code{gnatls}
15878 @noindent
15879 The @code{gnatls} command has the form
15881 @smallexample
15882 $ gnatls switches @var{object_or_ali_file}
15883 @end smallexample
15885 @noindent
15886 The main argument is the list of object or @file{ali} files
15887 (@pxref{The Ada Library Information Files})
15888 for which information is requested.
15890 In normal mode, without additional option, @code{gnatls} produces a
15891 four-column listing. Each line represents information for a specific
15892 object. The first column gives the full path of the object, the second
15893 column gives the name of the principal unit in this object, the third
15894 column gives the status of the source and the fourth column gives the
15895 full path of the source representing this unit.
15896 Here is a simple example of use:
15898 @smallexample
15899 $ gnatls *.o
15900 ^./^[]^demo1.o            demo1            DIF demo1.adb
15901 ^./^[]^demo2.o            demo2             OK demo2.adb
15902 ^./^[]^hello.o            h1                OK hello.adb
15903 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15904 ^./^[]^instr.o            instr             OK instr.adb
15905 ^./^[]^tef.o              tef              DIF tef.adb
15906 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15907 ^./^[]^tgef.o             tgef             DIF tgef.adb
15908 @end smallexample
15910 @noindent
15911 The first line can be interpreted as follows: the main unit which is
15912 contained in
15913 object file @file{demo1.o} is demo1, whose main source is in
15914 @file{demo1.adb}. Furthermore, the version of the source used for the
15915 compilation of demo1 has been modified (DIF). Each source file has a status
15916 qualifier which can be:
15918 @table @code
15919 @item OK (unchanged)
15920 The version of the source file used for the compilation of the
15921 specified unit corresponds exactly to the actual source file.
15923 @item MOK (slightly modified)
15924 The version of the source file used for the compilation of the
15925 specified unit differs from the actual source file but not enough to
15926 require recompilation. If you use gnatmake with the qualifier
15927 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15928 MOK will not be recompiled.
15930 @item DIF (modified)
15931 No version of the source found on the path corresponds to the source
15932 used to build this object.
15934 @item ??? (file not found)
15935 No source file was found for this unit.
15937 @item HID (hidden,  unchanged version not first on PATH)
15938 The version of the source that corresponds exactly to the source used
15939 for compilation has been found on the path but it is hidden by another
15940 version of the same source that has been modified.
15942 @end table
15944 @node Switches for gnatls
15945 @section Switches for @code{gnatls}
15947 @noindent
15948 @code{gnatls} recognizes the following switches:
15950 @table @option
15951 @c !sort!
15952 @cindex @option{--version} @command{gnatls}
15953 Display Copyright and version, then exit disregarding all other options.
15955 @item --help
15956 @cindex @option{--help} @command{gnatls}
15957 If @option{--version} was not used, display usage, then exit disregarding
15958 all other options.
15960 @item ^-a^/ALL_UNITS^
15961 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15962 Consider all units, including those of the predefined Ada library.
15963 Especially useful with @option{^-d^/DEPENDENCIES^}.
15965 @item ^-d^/DEPENDENCIES^
15966 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15967 List sources from which specified units depend on.
15969 @item ^-h^/OUTPUT=OPTIONS^
15970 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15971 Output the list of options.
15973 @item ^-o^/OUTPUT=OBJECTS^
15974 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15975 Only output information about object files.
15977 @item ^-s^/OUTPUT=SOURCES^
15978 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15979 Only output information about source files.
15981 @item ^-u^/OUTPUT=UNITS^
15982 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15983 Only output information about compilation units.
15985 @item ^-files^/FILES^=@var{file}
15986 @cindex @option{^-files^/FILES^} (@code{gnatls})
15987 Take as arguments the files listed in text file @var{file}.
15988 Text file @var{file} may contain empty lines that are ignored.
15989 Each nonempty line should contain the name of an existing file.
15990 Several such switches may be specified simultaneously.
15992 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15993 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15994 @itemx ^-I^/SEARCH=^@var{dir}
15995 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15996 @itemx -nostdinc
15997 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15998 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15999 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16000 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16001 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16002 flags (@pxref{Switches for gnatmake}).
16004 @item --RTS=@var{rts-path}
16005 @cindex @option{--RTS} (@code{gnatls})
16006 Specifies the default location of the runtime library. Same meaning as the
16007 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16009 @item ^-v^/OUTPUT=VERBOSE^
16010 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16011 Verbose mode. Output the complete source, object and project paths. Do not use
16012 the default column layout but instead use long format giving as much as
16013 information possible on each requested units, including special
16014 characteristics such as:
16016 @table @code
16017 @item  Preelaborable
16018 The unit is preelaborable in the Ada sense.
16020 @item No_Elab_Code
16021 No elaboration code has been produced by the compiler for this unit.
16023 @item Pure
16024 The unit is pure in the Ada sense.
16026 @item Elaborate_Body
16027 The unit contains a pragma Elaborate_Body.
16029 @item Remote_Types
16030 The unit contains a pragma Remote_Types.
16032 @item Shared_Passive
16033 The unit contains a pragma Shared_Passive.
16035 @item Predefined
16036 This unit is part of the predefined environment and cannot be modified
16037 by the user.
16039 @item Remote_Call_Interface
16040 The unit contains a pragma Remote_Call_Interface.
16042 @end table
16044 @end table
16046 @node Examples of gnatls Usage
16047 @section Example of @code{gnatls} Usage
16048 @ifclear vms
16050 @noindent
16051 Example of using the verbose switch. Note how the source and
16052 object paths are affected by the -I switch.
16054 @smallexample
16055 $ gnatls -v -I.. demo1.o
16057 GNATLS 5.03w (20041123-34)
16058 Copyright 1997-2004 Free Software Foundation, Inc.
16060 Source Search Path:
16061    <Current_Directory>
16062    ../
16063    /home/comar/local/adainclude/
16065 Object Search Path:
16066    <Current_Directory>
16067    ../
16068    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16070 Project Search Path:
16071    <Current_Directory>
16072    /home/comar/local/lib/gnat/
16074 ./demo1.o
16075    Unit =>
16076      Name   => demo1
16077      Kind   => subprogram body
16078      Flags  => No_Elab_Code
16079      Source => demo1.adb    modified
16080 @end smallexample
16082 @noindent
16083 The following is an example of use of the dependency list.
16084 Note the use of the -s switch
16085 which gives a straight list of source files. This can be useful for
16086 building specialized scripts.
16088 @smallexample
16089 $ gnatls -d demo2.o
16090 ./demo2.o   demo2        OK demo2.adb
16091                          OK gen_list.ads
16092                          OK gen_list.adb
16093                          OK instr.ads
16094                          OK instr-child.ads
16096 $ gnatls -d -s -a demo1.o
16097 demo1.adb
16098 /home/comar/local/adainclude/ada.ads
16099 /home/comar/local/adainclude/a-finali.ads
16100 /home/comar/local/adainclude/a-filico.ads
16101 /home/comar/local/adainclude/a-stream.ads
16102 /home/comar/local/adainclude/a-tags.ads
16103 gen_list.ads
16104 gen_list.adb
16105 /home/comar/local/adainclude/gnat.ads
16106 /home/comar/local/adainclude/g-io.ads
16107 instr.ads
16108 /home/comar/local/adainclude/system.ads
16109 /home/comar/local/adainclude/s-exctab.ads
16110 /home/comar/local/adainclude/s-finimp.ads
16111 /home/comar/local/adainclude/s-finroo.ads
16112 /home/comar/local/adainclude/s-secsta.ads
16113 /home/comar/local/adainclude/s-stalib.ads
16114 /home/comar/local/adainclude/s-stoele.ads
16115 /home/comar/local/adainclude/s-stratt.ads
16116 /home/comar/local/adainclude/s-tasoli.ads
16117 /home/comar/local/adainclude/s-unstyp.ads
16118 /home/comar/local/adainclude/unchconv.ads
16119 @end smallexample
16120 @end ifclear
16122 @ifset vms
16123 @smallexample
16124 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16126 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16127 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16128 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16129 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16130 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16131 demo1.adb
16132 gen_list.ads
16133 gen_list.adb
16134 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16135 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16136 instr.ads
16137 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16138 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16139 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16140 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16141 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16142 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16143 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16144 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16145 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16146 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16147 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16148 @end smallexample
16149 @end ifset
16151 @node Cleaning Up Using gnatclean
16152 @chapter Cleaning Up Using @code{gnatclean}
16153 @findex gnatclean
16154 @cindex Cleaning tool
16156 @noindent
16157 @code{gnatclean} is a tool that allows the deletion of files produced by the
16158 compiler, binder and linker, including ALI files, object files, tree files,
16159 expanded source files, library files, interface copy source files, binder
16160 generated files and executable files.
16162 @menu
16163 * Running gnatclean::
16164 * Switches for gnatclean::
16165 @c * Examples of gnatclean Usage::
16166 @end menu
16168 @node Running gnatclean
16169 @section Running @code{gnatclean}
16171 @noindent
16172 The @code{gnatclean} command has the form:
16174 @smallexample
16175 $ gnatclean switches @var{names}
16176 @end smallexample
16178 @noindent
16179 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16180 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16181 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16183 @noindent
16184 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16185 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16186 the linker. In informative-only mode, specified by switch
16187 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16188 normal mode is listed, but no file is actually deleted.
16190 @node Switches for gnatclean
16191 @section Switches for @code{gnatclean}
16193 @noindent
16194 @code{gnatclean} recognizes the following switches:
16196 @table @option
16197 @c !sort!
16198 @cindex @option{--version} @command{gnatclean}
16199 Display Copyright and version, then exit disregarding all other options.
16201 @item --help
16202 @cindex @option{--help} @command{gnatclean}
16203 If @option{--version} was not used, display usage, then exit disregarding
16204 all other options.
16206 @item ^--subdirs^/SUBDIRS^=subdir
16207 Actual object directory of each project file is the subdirectory subdir of the
16208 object directory specified or defaulted in the project file.
16210 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
16211 By default, shared library projects are not allowed to import static library
16212 projects. When this switch is used on the command line, this restriction is
16213 relaxed.
16215 @item ^-c^/COMPILER_FILES_ONLY^
16216 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16217 Only attempt to delete the files produced by the compiler, not those produced
16218 by the binder or the linker. The files that are not to be deleted are library
16219 files, interface copy files, binder generated files and executable files.
16221 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16222 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16223 Indicate that ALI and object files should normally be found in directory
16224 @var{dir}.
16226 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16227 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16228 When using project files, if some errors or warnings are detected during
16229 parsing and verbose mode is not in effect (no use of switch
16230 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16231 file, rather than its simple file name.
16233 @item ^-h^/HELP^
16234 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16235 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16237 @item ^-n^/NODELETE^
16238 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16239 Informative-only mode. Do not delete any files. Output the list of the files
16240 that would have been deleted if this switch was not specified.
16242 @item ^-P^/PROJECT_FILE=^@var{project}
16243 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16244 Use project file @var{project}. Only one such switch can be used.
16245 When cleaning a project file, the files produced by the compilation of the
16246 immediate sources or inherited sources of the project files are to be
16247 deleted. This is not depending on the presence or not of executable names
16248 on the command line.
16250 @item ^-q^/QUIET^
16251 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16252 Quiet output. If there are no errors, do not output anything, except in
16253 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16254 (switch ^-n^/NODELETE^).
16256 @item ^-r^/RECURSIVE^
16257 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16258 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16259 clean all imported and extended project files, recursively. If this switch
16260 is not specified, only the files related to the main project file are to be
16261 deleted. This switch has no effect if no project file is specified.
16263 @item ^-v^/VERBOSE^
16264 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16265 Verbose mode.
16267 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16268 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16269 Indicates the verbosity of the parsing of GNAT project files.
16270 @xref{Switches Related to Project Files}.
16272 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16273 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16274 Indicates that external variable @var{name} has the value @var{value}.
16275 The Project Manager will use this value for occurrences of
16276 @code{external(name)} when parsing the project file.
16277 @xref{Switches Related to Project Files}.
16279 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16280 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16281 When searching for ALI and object files, look in directory
16282 @var{dir}.
16284 @item ^-I^/SEARCH=^@var{dir}
16285 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16286 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16288 @item ^-I-^/NOCURRENT_DIRECTORY^
16289 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16290 @cindex Source files, suppressing search
16291 Do not look for ALI or object files in the directory
16292 where @code{gnatclean} was invoked.
16294 @end table
16296 @c @node Examples of gnatclean Usage
16297 @c @section Examples of @code{gnatclean} Usage
16299 @ifclear vms
16300 @node GNAT and Libraries
16301 @chapter GNAT and Libraries
16302 @cindex Library, building, installing, using
16304 @noindent
16305 This chapter describes how to build and use libraries with GNAT, and also shows
16306 how to recompile the GNAT run-time library. You should be familiar with the
16307 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16308 chapter.
16310 @menu
16311 * Introduction to Libraries in GNAT::
16312 * General Ada Libraries::
16313 * Stand-alone Ada Libraries::
16314 * Rebuilding the GNAT Run-Time Library::
16315 @end menu
16317 @node Introduction to Libraries in GNAT
16318 @section Introduction to Libraries in GNAT
16320 @noindent
16321 A library is, conceptually, a collection of objects which does not have its
16322 own main thread of execution, but rather provides certain services to the
16323 applications that use it. A library can be either statically linked with the
16324 application, in which case its code is directly included in the application,
16325 or, on platforms that support it, be dynamically linked, in which case
16326 its code is shared by all applications making use of this library.
16328 GNAT supports both types of libraries.
16329 In the static case, the compiled code can be provided in different ways. The
16330 simplest approach is to provide directly the set of objects resulting from
16331 compilation of the library source files. Alternatively, you can group the
16332 objects into an archive using whatever commands are provided by the operating
16333 system. For the latter case, the objects are grouped into a shared library.
16335 In the GNAT environment, a library has three types of components:
16336 @itemize @bullet
16337 @item
16338 Source files.
16339 @item
16340 @file{ALI} files.
16341 @xref{The Ada Library Information Files}.
16342 @item
16343 Object files, an archive or a shared library.
16344 @end itemize
16346 @noindent
16347 A GNAT library may expose all its source files, which is useful for
16348 documentation purposes. Alternatively, it may expose only the units needed by
16349 an external user to make use of the library. That is to say, the specs
16350 reflecting the library services along with all the units needed to compile
16351 those specs, which can include generic bodies or any body implementing an
16352 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16353 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16355 All compilation units comprising an application, including those in a library,
16356 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16357 computes the elaboration order from the @file{ALI} files and this is why they
16358 constitute a mandatory part of GNAT libraries.
16359 @emph{Stand-alone libraries} are the exception to this rule because a specific
16360 library elaboration routine is produced independently of the application(s)
16361 using the library.
16363 @node General Ada Libraries
16364 @section General Ada Libraries
16366 @menu
16367 * Building a library::
16368 * Installing a library::
16369 * Using a library::
16370 @end menu
16372 @node Building a library
16373 @subsection Building a library
16375 @noindent
16376 The easiest way to build a library is to use the Project Manager,
16377 which supports a special type of project called a @emph{Library Project}
16378 (@pxref{Library Projects}).
16380 A project is considered a library project, when two project-level attributes
16381 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16382 control different aspects of library configuration, additional optional
16383 project-level attributes can be specified:
16384 @table @code
16385 @item Library_Kind
16386 This attribute controls whether the library is to be static or dynamic
16388 @item Library_Version
16389 This attribute specifies the library version; this value is used
16390 during dynamic linking of shared libraries to determine if the currently
16391 installed versions of the binaries are compatible.
16393 @item Library_Options
16394 @item Library_GCC
16395 These attributes specify additional low-level options to be used during
16396 library generation, and redefine the actual application used to generate
16397 library.
16398 @end table
16400 @noindent
16401 The GNAT Project Manager takes full care of the library maintenance task,
16402 including recompilation of the source files for which objects do not exist
16403 or are not up to date, assembly of the library archive, and installation of
16404 the library (i.e., copying associated source, object and @file{ALI} files
16405 to the specified location).
16407 Here is a simple library project file:
16408 @smallexample @c ada
16409 project My_Lib is
16410    for Source_Dirs use ("src1", "src2");
16411    for Object_Dir use "obj";
16412    for Library_Name use "mylib";
16413    for Library_Dir use "lib";
16414    for Library_Kind use "dynamic";
16415 end My_lib;
16416 @end smallexample
16418 @noindent
16419 and the compilation command to build and install the library:
16421 @smallexample @c ada
16422   $ gnatmake -Pmy_lib
16423 @end smallexample
16425 @noindent
16426 It is not entirely trivial to perform manually all the steps required to
16427 produce a library. We recommend that you use the GNAT Project Manager
16428 for this task. In special cases where this is not desired, the necessary
16429 steps are discussed below.
16431 There are various possibilities for compiling the units that make up the
16432 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16433 with a conventional script. For simple libraries, it is also possible to create
16434 a dummy main program which depends upon all the packages that comprise the
16435 interface of the library. This dummy main program can then be given to
16436 @command{gnatmake}, which will ensure that all necessary objects are built.
16438 After this task is accomplished, you should follow the standard procedure
16439 of the underlying operating system to produce the static or shared library.
16441 Here is an example of such a dummy program:
16442 @smallexample @c ada
16443 @group
16444 with My_Lib.Service1;
16445 with My_Lib.Service2;
16446 with My_Lib.Service3;
16447 procedure My_Lib_Dummy is
16448 begin
16449    null;
16450 end;
16451 @end group
16452 @end smallexample
16454 @noindent
16455 Here are the generic commands that will build an archive or a shared library.
16457 @smallexample
16458 # compiling the library
16459 $ gnatmake -c my_lib_dummy.adb
16461 # we don't need the dummy object itself
16462 $ rm my_lib_dummy.o my_lib_dummy.ali
16464 # create an archive with the remaining objects
16465 $ ar rc libmy_lib.a *.o
16466 # some systems may require "ranlib" to be run as well
16468 # or create a shared library
16469 $ gcc -shared -o libmy_lib.so *.o
16470 # some systems may require the code to have been compiled with -fPIC
16472 # remove the object files that are now in the library
16473 $ rm *.o
16475 # Make the ALI files read-only so that gnatmake will not try to
16476 # regenerate the objects that are in the library
16477 $ chmod -w *.ali
16478 @end smallexample
16480 @noindent
16481 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16482 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16483 be accessed by the directive @option{-l@var{xxx}} at link time.
16485 @node Installing a library
16486 @subsection Installing a library
16487 @cindex @code{ADA_PROJECT_PATH}
16488 @cindex @code{GPR_PROJECT_PATH}
16490 @noindent
16491 If you use project files, library installation is part of the library build
16492 process (@pxref{Installing a library with project files}).
16494 When project files are not an option, it is also possible, but not recommended,
16495 to install the library so that the sources needed to use the library are on the
16496 Ada source path and the ALI files & libraries be on the Ada Object path (see
16497 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16498 administrator can place general-purpose libraries in the default compiler
16499 paths, by specifying the libraries' location in the configuration files
16500 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16501 must be located in the GNAT installation tree at the same place as the gcc spec
16502 file. The location of the gcc spec file can be determined as follows:
16503 @smallexample
16504 $ gcc -v
16505 @end smallexample
16507 @noindent
16508 The configuration files mentioned above have a simple format: each line
16509 must contain one unique directory name.
16510 Those names are added to the corresponding path
16511 in their order of appearance in the file. The names can be either absolute
16512 or relative; in the latter case, they are relative to where theses files
16513 are located.
16515 The files @file{ada_source_path} and @file{ada_object_path} might not be
16516 present in a
16517 GNAT installation, in which case, GNAT will look for its run-time library in
16518 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16519 objects and @file{ALI} files). When the files exist, the compiler does not
16520 look in @file{adainclude} and @file{adalib}, and thus the
16521 @file{ada_source_path} file
16522 must contain the location for the GNAT run-time sources (which can simply
16523 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16524 contain the location for the GNAT run-time objects (which can simply
16525 be @file{adalib}).
16527 You can also specify a new default path to the run-time library at compilation
16528 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16529 the run-time library you want your program to be compiled with. This switch is
16530 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16531 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16533 It is possible to install a library before or after the standard GNAT
16534 library, by reordering the lines in the configuration files. In general, a
16535 library must be installed before the GNAT library if it redefines
16536 any part of it.
16538 @node Using a library
16539 @subsection Using a library
16541 @noindent Once again, the project facility greatly simplifies the use of
16542 libraries. In this context, using a library is just a matter of adding a
16543 @code{with} clause in the user project. For instance, to make use of the
16544 library @code{My_Lib} shown in examples in earlier sections, you can
16545 write:
16547 @smallexample @c projectfile
16548 with "my_lib";
16549 project My_Proj is
16550   @dots{}
16551 end My_Proj;
16552 @end smallexample
16554 Even if you have a third-party, non-Ada library, you can still use GNAT's
16555 Project Manager facility to provide a wrapper for it. For example, the
16556 following project, when @code{with}ed by your main project, will link with the
16557 third-party library @file{liba.a}:
16559 @smallexample @c projectfile
16560 @group
16561 project Liba is
16562    for Externally_Built use "true";
16563    for Source_Files use ();
16564    for Library_Dir use "lib";
16565    for Library_Name use "a";
16566    for Library_Kind use "static";
16567 end Liba;
16568 @end group
16569 @end smallexample
16570 This is an alternative to the use of @code{pragma Linker_Options}. It is
16571 especially interesting in the context of systems with several interdependent
16572 static libraries where finding a proper linker order is not easy and best be
16573 left to the tools having visibility over project dependence information.
16575 @noindent
16576 In order to use an Ada library manually, you need to make sure that this
16577 library is on both your source and object path
16578 (see @ref{Search Paths and the Run-Time Library (RTL)}
16579 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16580 in an archive or a shared library, you need to specify the desired
16581 library at link time.
16583 For example, you can use the library @file{mylib} installed in
16584 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16586 @smallexample
16587 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16588   -largs -lmy_lib
16589 @end smallexample
16591 @noindent
16592 This can be expressed more simply:
16593 @smallexample
16594 $ gnatmake my_appl
16595 @end smallexample
16596 @noindent
16597 when the following conditions are met:
16598 @itemize @bullet
16599 @item
16600 @file{/dir/my_lib_src} has been added by the user to the environment
16601 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16602 @file{ada_source_path}
16603 @item
16604 @file{/dir/my_lib_obj} has been added by the user to the environment
16605 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16606 @file{ada_object_path}
16607 @item
16608 a pragma @code{Linker_Options} has been added to one of the sources.
16609 For example:
16611 @smallexample @c ada
16612 pragma Linker_Options ("-lmy_lib");
16613 @end smallexample
16614 @end itemize
16616 @node Stand-alone Ada Libraries
16617 @section Stand-alone Ada Libraries
16618 @cindex Stand-alone library, building, using
16620 @menu
16621 * Introduction to Stand-alone Libraries::
16622 * Building a Stand-alone Library::
16623 * Creating a Stand-alone Library to be used in a non-Ada context::
16624 * Restrictions in Stand-alone Libraries::
16625 @end menu
16627 @node Introduction to Stand-alone Libraries
16628 @subsection Introduction to Stand-alone Libraries
16630 @noindent
16631 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16632 necessary code to
16633 elaborate the Ada units that are included in the library. In contrast with
16634 an ordinary library, which consists of all sources, objects and @file{ALI}
16635 files of the
16636 library, a SAL may specify a restricted subset of compilation units
16637 to serve as a library interface. In this case, the fully
16638 self-sufficient set of files will normally consist of an objects
16639 archive, the sources of interface units' specs, and the @file{ALI}
16640 files of interface units.
16641 If an interface spec contains a generic unit or an inlined subprogram,
16642 the body's
16643 source must also be provided; if the units that must be provided in the source
16644 form depend on other units, the source and @file{ALI} files of those must
16645 also be provided.
16647 The main purpose of a SAL is to minimize the recompilation overhead of client
16648 applications when a new version of the library is installed. Specifically,
16649 if the interface sources have not changed, client applications do not need to
16650 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16651 version, controlled by @code{Library_Version} attribute, is not changed,
16652 then the clients do not need to be relinked.
16654 SALs also allow the library providers to minimize the amount of library source
16655 text exposed to the clients.  Such ``information hiding'' might be useful or
16656 necessary for various reasons.
16658 Stand-alone libraries are also well suited to be used in an executable whose
16659 main routine is not written in Ada.
16661 @node Building a Stand-alone Library
16662 @subsection Building a Stand-alone Library
16664 @noindent
16665 GNAT's Project facility provides a simple way of building and installing
16666 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16667 To be a Stand-alone Library Project, in addition to the two attributes
16668 that make a project a Library Project (@code{Library_Name} and
16669 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16670 @code{Library_Interface} must be defined.  For example:
16672 @smallexample @c projectfile
16673 @group
16674    for Library_Dir use "lib_dir";
16675    for Library_Name use "dummy";
16676    for Library_Interface use ("int1", "int1.child");
16677 @end group
16678 @end smallexample
16680 @noindent
16681 Attribute @code{Library_Interface} has a non-empty string list value,
16682 each string in the list designating a unit contained in an immediate source
16683 of the project file.
16685 When a Stand-alone Library is built, first the binder is invoked to build
16686 a package whose name depends on the library name
16687 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16688 This binder-generated package includes initialization and
16689 finalization procedures whose
16690 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16691 in the example
16692 above). The object corresponding to this package is included in the library.
16694 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16695 calling of these procedures if a static SAL is built, or if a shared SAL
16696 is built
16697 with the project-level attribute @code{Library_Auto_Init} set to
16698 @code{"false"}.
16700 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16701 (those that are listed in attribute @code{Library_Interface}) are copied to
16702 the Library Directory. As a consequence, only the Interface Units may be
16703 imported from Ada units outside of the library. If other units are imported,
16704 the binding phase will fail.
16706 @noindent
16707 It is also possible to build an encapsulated library where not only
16708 the code to elaborate and finalize the library is embedded but also
16709 ensuring that the library is linked only against static
16710 libraries. So an encapsulated library only depends on system
16711 libraries, all other code, including the GNAT runtime, is embedded. To
16712 build an encapsulated library the attribute
16713 @code{Library_Standalone} must be set to @code{encapsulated}:
16715 @smallexample @c projectfile
16716 @group
16717    for Library_Dir use "lib_dir";
16718    for Library_Name use "dummy";
16719    for Library_Interface use ("int1", "int1.child");
16720    for Library_Standalone use "encapsulated";
16721 @end group
16722 @end smallexample
16724 @noindent
16725 The default value for this attribute is @code{standard} in which case
16726 a stand-alone library is built.
16728 The attribute @code{Library_Src_Dir} may be specified for a
16729 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16730 single string value. Its value must be the path (absolute or relative to the
16731 project directory) of an existing directory. This directory cannot be the
16732 object directory or one of the source directories, but it can be the same as
16733 the library directory. The sources of the Interface
16734 Units of the library that are needed by an Ada client of the library will be
16735 copied to the designated directory, called the Interface Copy directory.
16736 These sources include the specs of the Interface Units, but they may also
16737 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16738 are used, or when there is a generic unit in the spec. Before the sources
16739 are copied to the Interface Copy directory, an attempt is made to delete all
16740 files in the Interface Copy directory.
16742 Building stand-alone libraries by hand is somewhat tedious, but for those
16743 occasions when it is necessary here are the steps that you need to perform:
16744 @itemize @bullet
16745 @item
16746 Compile all library sources.
16748 @item
16749 Invoke the binder with the switch @option{-n} (No Ada main program),
16750 with all the @file{ALI} files of the interfaces, and
16751 with the switch @option{-L} to give specific names to the @code{init}
16752 and @code{final} procedures.  For example:
16753 @smallexample
16754   gnatbind -n int1.ali int2.ali -Lsal1
16755 @end smallexample
16757 @item
16758 Compile the binder generated file:
16759 @smallexample
16760   gcc -c b~int2.adb
16761 @end smallexample
16763 @item
16764 Link the dynamic library with all the necessary object files,
16765 indicating to the linker the names of the @code{init} (and possibly
16766 @code{final}) procedures for automatic initialization (and finalization).
16767 The built library should be placed in a directory different from
16768 the object directory.
16770 @item
16771 Copy the @code{ALI} files of the interface to the library directory,
16772 add in this copy an indication that it is an interface to a SAL
16773 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16774 with letter ``P'') and make the modified copy of the @file{ALI} file
16775 read-only.
16776 @end itemize
16778 @noindent
16779 Using SALs is not different from using other libraries
16780 (see @ref{Using a library}).
16782 @node Creating a Stand-alone Library to be used in a non-Ada context
16783 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16785 @noindent
16786 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16787 a non-Ada context.
16789 The only extra step required is to ensure that library interface subprograms
16790 are compatible with the main program, by means of @code{pragma Export}
16791 or @code{pragma Convention}.
16793 Here is an example of simple library interface for use with C main program:
16795 @smallexample @c ada
16796 package My_Package is
16798    procedure Do_Something;
16799    pragma Export (C, Do_Something, "do_something");
16801    procedure Do_Something_Else;
16802    pragma Export (C, Do_Something_Else, "do_something_else");
16804 end My_Package;
16805 @end smallexample
16807 @noindent
16808 On the foreign language side, you must provide a ``foreign'' view of the
16809 library interface; remember that it should contain elaboration routines in
16810 addition to interface subprograms.
16812 The example below shows the content of @code{mylib_interface.h} (note
16813 that there is no rule for the naming of this file, any name can be used)
16814 @smallexample
16815 /* the library elaboration procedure */
16816 extern void mylibinit (void);
16818 /* the library finalization procedure */
16819 extern void mylibfinal (void);
16821 /* the interface exported by the library */
16822 extern void do_something (void);
16823 extern void do_something_else (void);
16824 @end smallexample
16826 @noindent
16827 Libraries built as explained above can be used from any program, provided
16828 that the elaboration procedures (named @code{mylibinit} in the previous
16829 example) are called before the library services are used. Any number of
16830 libraries can be used simultaneously, as long as the elaboration
16831 procedure of each library is called.
16833 Below is an example of a C program that uses the @code{mylib} library.
16835 @smallexample
16836 #include "mylib_interface.h"
16839 main (void)
16841    /* First, elaborate the library before using it */
16842    mylibinit ();
16844    /* Main program, using the library exported entities */
16845    do_something ();
16846    do_something_else ();
16848    /* Library finalization at the end of the program */
16849    mylibfinal ();
16850    return 0;
16852 @end smallexample
16854 @noindent
16855 Note that invoking any library finalization procedure generated by
16856 @code{gnatbind} shuts down the Ada run-time environment.
16857 Consequently, the
16858 finalization of all Ada libraries must be performed at the end of the program.
16859 No call to these libraries or to the Ada run-time library should be made
16860 after the finalization phase.
16862 @node Restrictions in Stand-alone Libraries
16863 @subsection Restrictions in Stand-alone Libraries
16865 @noindent
16866 The pragmas listed below should be used with caution inside libraries,
16867 as they can create incompatibilities with other Ada libraries:
16868 @itemize @bullet
16869 @item pragma @code{Locking_Policy}
16870 @item pragma @code{Queuing_Policy}
16871 @item pragma @code{Task_Dispatching_Policy}
16872 @item pragma @code{Unreserve_All_Interrupts}
16873 @end itemize
16875 @noindent
16876 When using a library that contains such pragmas, the user must make sure
16877 that all libraries use the same pragmas with the same values. Otherwise,
16878 @code{Program_Error} will
16879 be raised during the elaboration of the conflicting
16880 libraries. The usage of these pragmas and its consequences for the user
16881 should therefore be well documented.
16883 Similarly, the traceback in the exception occurrence mechanism should be
16884 enabled or disabled in a consistent manner across all libraries.
16885 Otherwise, Program_Error will be raised during the elaboration of the
16886 conflicting libraries.
16888 If the @code{Version} or @code{Body_Version}
16889 attributes are used inside a library, then you need to
16890 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16891 libraries, so that version identifiers can be properly computed.
16892 In practice these attributes are rarely used, so this is unlikely
16893 to be a consideration.
16895 @node  Rebuilding the GNAT Run-Time Library
16896 @section Rebuilding the GNAT Run-Time Library
16897 @cindex GNAT Run-Time Library, rebuilding
16898 @cindex Building the GNAT Run-Time Library
16899 @cindex Rebuilding the GNAT Run-Time Library
16900 @cindex Run-Time Library, rebuilding
16902 @noindent
16903 It may be useful to recompile the GNAT library in various contexts, the
16904 most important one being the use of partition-wide configuration pragmas
16905 such as @code{Normalize_Scalars}. A special Makefile called
16906 @code{Makefile.adalib} is provided to that effect and can be found in
16907 the directory containing the GNAT library. The location of this
16908 directory depends on the way the GNAT environment has been installed and can
16909 be determined by means of the command:
16911 @smallexample
16912 $ gnatls -v
16913 @end smallexample
16915 @noindent
16916 The last entry in the object search path usually contains the
16917 gnat library. This Makefile contains its own documentation and in
16918 particular the set of instructions needed to rebuild a new library and
16919 to use it.
16921 @node Using the GNU make Utility
16922 @chapter Using the GNU @code{make} Utility
16923 @findex make
16925 @noindent
16926 This chapter offers some examples of makefiles that solve specific
16927 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16928 make, make, GNU @code{make}}), nor does it try to replace the
16929 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16931 All the examples in this section are specific to the GNU version of
16932 make. Although @command{make} is a standard utility, and the basic language
16933 is the same, these examples use some advanced features found only in
16934 @code{GNU make}.
16936 @menu
16937 * Using gnatmake in a Makefile::
16938 * Automatically Creating a List of Directories::
16939 * Generating the Command Line Switches::
16940 * Overcoming Command Line Length Limits::
16941 @end menu
16943 @node Using gnatmake in a Makefile
16944 @section Using gnatmake in a Makefile
16945 @findex makefile
16946 @cindex GNU make
16948 @noindent
16949 Complex project organizations can be handled in a very powerful way by
16950 using GNU make combined with gnatmake. For instance, here is a Makefile
16951 which allows you to build each subsystem of a big project into a separate
16952 shared library. Such a makefile allows you to significantly reduce the link
16953 time of very big applications while maintaining full coherence at
16954 each step of the build process.
16956 The list of dependencies are handled automatically by
16957 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16958 the appropriate directories.
16960 Note that you should also read the example on how to automatically
16961 create the list of directories
16962 (@pxref{Automatically Creating a List of Directories})
16963 which might help you in case your project has a lot of subdirectories.
16965 @smallexample
16966 @iftex
16967 @leftskip=0cm
16968 @font@heightrm=cmr8
16969 @heightrm
16970 @end iftex
16971 ## This Makefile is intended to be used with the following directory
16972 ## configuration:
16973 ##  - The sources are split into a series of csc (computer software components)
16974 ##    Each of these csc is put in its own directory.
16975 ##    Their name are referenced by the directory names.
16976 ##    They will be compiled into shared library (although this would also work
16977 ##    with static libraries
16978 ##  - The main program (and possibly other packages that do not belong to any
16979 ##    csc is put in the top level directory (where the Makefile is).
16980 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16981 ##                    \_ second_csc (sources) __ lib (will contain the library)
16982 ##                    \_ @dots{}
16983 ## Although this Makefile is build for shared library, it is easy to modify
16984 ## to build partial link objects instead (modify the lines with -shared and
16985 ## gnatlink below)
16987 ## With this makefile, you can change any file in the system or add any new
16988 ## file, and everything will be recompiled correctly (only the relevant shared
16989 ## objects will be recompiled, and the main program will be re-linked).
16991 # The list of computer software component for your project. This might be
16992 # generated automatically.
16993 CSC_LIST=aa bb cc
16995 # Name of the main program (no extension)
16996 MAIN=main
16998 # If we need to build objects with -fPIC, uncomment the following line
16999 #NEED_FPIC=-fPIC
17001 # The following variable should give the directory containing libgnat.so
17002 # You can get this directory through 'gnatls -v'. This is usually the last
17003 # directory in the Object_Path.
17004 GLIB=@dots{}
17006 # The directories for the libraries
17007 # (This macro expands the list of CSC to the list of shared libraries, you
17008 # could simply use the expanded form:
17009 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17010 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17012 $@{MAIN@}: objects $@{LIB_DIR@}
17013     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17014     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17016 objects::
17017     # recompile the sources
17018     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17020 # Note: In a future version of GNAT, the following commands will be simplified
17021 # by a new tool, gnatmlib
17022 $@{LIB_DIR@}:
17023     mkdir -p $@{dir $@@ @}
17024     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17025     cd $@{dir $@@ @} && cp -f ../*.ali .
17027 # The dependencies for the modules
17028 # Note that we have to force the expansion of *.o, since in some cases
17029 # make won't be able to do it itself.
17030 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17031 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17032 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17034 # Make sure all of the shared libraries are in the path before starting the
17035 # program
17036 run::
17037     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17039 clean::
17040     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17041     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17042     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17043     $@{RM@} *.o *.ali $@{MAIN@}
17044 @end smallexample
17046 @node Automatically Creating a List of Directories
17047 @section Automatically Creating a List of Directories
17049 @noindent
17050 In most makefiles, you will have to specify a list of directories, and
17051 store it in a variable. For small projects, it is often easier to
17052 specify each of them by hand, since you then have full control over what
17053 is the proper order for these directories, which ones should be
17054 included.
17056 However, in larger projects, which might involve hundreds of
17057 subdirectories, it might be more convenient to generate this list
17058 automatically.
17060 The example below presents two methods. The first one, although less
17061 general, gives you more control over the list. It involves wildcard
17062 characters, that are automatically expanded by @command{make}. Its
17063 shortcoming is that you need to explicitly specify some of the
17064 organization of your project, such as for instance the directory tree
17065 depth, whether some directories are found in a separate tree, @enddots{}
17067 The second method is the most general one. It requires an external
17068 program, called @command{find}, which is standard on all Unix systems. All
17069 the directories found under a given root directory will be added to the
17070 list.
17072 @smallexample
17073 @iftex
17074 @leftskip=0cm
17075 @font@heightrm=cmr8
17076 @heightrm
17077 @end iftex
17078 # The examples below are based on the following directory hierarchy:
17079 # All the directories can contain any number of files
17080 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17081 #                       ->  ab
17082 #                       ->  ac
17083 #                ->  b  ->  ba  ->  baa
17084 #                       ->  bb
17085 #                       ->  bc
17086 # This Makefile creates a variable called DIRS, that can be reused any time
17087 # you need this list (see the other examples in this section)
17089 # The root of your project's directory hierarchy
17090 ROOT_DIRECTORY=.
17092 ####
17093 # First method: specify explicitly the list of directories
17094 # This allows you to specify any subset of all the directories you need.
17095 ####
17097 DIRS := a/aa/ a/ab/ b/ba/
17099 ####
17100 # Second method: use wildcards
17101 # Note that the argument(s) to wildcard below should end with a '/'.
17102 # Since wildcards also return file names, we have to filter them out
17103 # to avoid duplicate directory names.
17104 # We thus use make's @code{dir} and @code{sort} functions.
17105 # It sets DIRs to the following value (note that the directories aaa and baa
17106 # are not given, unless you change the arguments to wildcard).
17107 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17108 ####
17110 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17111                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17113 ####
17114 # Third method: use an external program
17115 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17116 # This is the most complete command: it sets DIRs to the following value:
17117 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17118 ####
17120 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17122 @end smallexample
17124 @node Generating the Command Line Switches
17125 @section Generating the Command Line Switches
17127 @noindent
17128 Once you have created the list of directories as explained in the
17129 previous section (@pxref{Automatically Creating a List of Directories}),
17130 you can easily generate the command line arguments to pass to gnatmake.
17132 For the sake of completeness, this example assumes that the source path
17133 is not the same as the object path, and that you have two separate lists
17134 of directories.
17136 @smallexample
17137 # see "Automatically creating a list of directories" to create
17138 # these variables
17139 SOURCE_DIRS=
17140 OBJECT_DIRS=
17142 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17143 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17145 all:
17146         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17147 @end smallexample
17149 @node Overcoming Command Line Length Limits
17150 @section Overcoming Command Line Length Limits
17152 @noindent
17153 One problem that might be encountered on big projects is that many
17154 operating systems limit the length of the command line. It is thus hard to give
17155 gnatmake the list of source and object directories.
17157 This example shows how you can set up environment variables, which will
17158 make @command{gnatmake} behave exactly as if the directories had been
17159 specified on the command line, but have a much higher length limit (or
17160 even none on most systems).
17162 It assumes that you have created a list of directories in your Makefile,
17163 using one of the methods presented in
17164 @ref{Automatically Creating a List of Directories}.
17165 For the sake of completeness, we assume that the object
17166 path (where the ALI files are found) is different from the sources patch.
17168 Note a small trick in the Makefile below: for efficiency reasons, we
17169 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17170 expanded immediately by @code{make}. This way we overcome the standard
17171 make behavior which is to expand the variables only when they are
17172 actually used.
17174 On Windows, if you are using the standard Windows command shell, you must
17175 replace colons with semicolons in the assignments to these variables.
17177 @smallexample
17178 @iftex
17179 @leftskip=0cm
17180 @font@heightrm=cmr8
17181 @heightrm
17182 @end iftex
17183 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17184 # This is the same thing as putting the -I arguments on the command line.
17185 # (the equivalent of using -aI on the command line would be to define
17186 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17187 # You can of course have different values for these variables.
17189 # Note also that we need to keep the previous values of these variables, since
17190 # they might have been set before running 'make' to specify where the GNAT
17191 # library is installed.
17193 # see "Automatically creating a list of directories" to create these
17194 # variables
17195 SOURCE_DIRS=
17196 OBJECT_DIRS=
17198 empty:=
17199 space:=$@{empty@} $@{empty@}
17200 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17201 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17202 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17203 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17204 export ADA_INCLUDE_PATH
17205 export ADA_OBJECTS_PATH
17207 all:
17208         gnatmake main_unit
17209 @end smallexample
17210 @end ifclear
17212 @node Memory Management Issues
17213 @chapter Memory Management Issues
17215 @noindent
17216 This chapter describes some useful memory pools provided in the GNAT library
17217 and in particular the GNAT Debug Pool facility, which can be used to detect
17218 incorrect uses of access values (including ``dangling references'').
17219 @ifclear vms
17220 It also describes the @command{gnatmem} tool, which can be used to track down
17221 ``memory leaks''.
17222 @end ifclear
17224 @menu
17225 * Some Useful Memory Pools::
17226 * The GNAT Debug Pool Facility::
17227 @ifclear vms
17228 * The gnatmem Tool::
17229 @end ifclear
17230 @end menu
17232 @node Some Useful Memory Pools
17233 @section Some Useful Memory Pools
17234 @findex Memory Pool
17235 @cindex storage, pool
17237 @noindent
17238 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17239 storage pool. Allocations use the standard system call @code{malloc} while
17240 deallocations use the standard system call @code{free}. No reclamation is
17241 performed when the pool goes out of scope. For performance reasons, the
17242 standard default Ada allocators/deallocators do not use any explicit storage
17243 pools but if they did, they could use this storage pool without any change in
17244 behavior. That is why this storage pool is used  when the user
17245 manages to make the default implicit allocator explicit as in this example:
17246 @smallexample @c ada
17247    type T1 is access Something;
17248     -- no Storage pool is defined for T2
17249    type T2 is access Something_Else;
17250    for T2'Storage_Pool use T1'Storage_Pool;
17251    -- the above is equivalent to
17252    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17253 @end smallexample
17255 @noindent
17256 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17257 pool. The allocation strategy is similar to @code{Pool_Local}'s
17258 except that the all
17259 storage allocated with this pool is reclaimed when the pool object goes out of
17260 scope. This pool provides a explicit mechanism similar to the implicit one
17261 provided by several Ada 83 compilers for allocations performed through a local
17262 access type and whose purpose was to reclaim memory when exiting the
17263 scope of a given local access. As an example, the following program does not
17264 leak memory even though it does not perform explicit deallocation:
17266 @smallexample @c ada
17267 with System.Pool_Local;
17268 procedure Pooloc1 is
17269    procedure Internal is
17270       type A is access Integer;
17271       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17272       for A'Storage_Pool use X;
17273       v : A;
17274    begin
17275       for I in  1 .. 50 loop
17276          v := new Integer;
17277       end loop;
17278    end Internal;
17279 begin
17280    for I in  1 .. 100 loop
17281       Internal;
17282    end loop;
17283 end Pooloc1;
17284 @end smallexample
17286 @noindent
17287 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17288 @code{Storage_Size} is specified for an access type.
17289 The whole storage for the pool is
17290 allocated at once, usually on the stack at the point where the access type is
17291 elaborated. It is automatically reclaimed when exiting the scope where the
17292 access type is defined. This package is not intended to be used directly by the
17293 user and it is implicitly used for each such declaration:
17295 @smallexample @c ada
17296    type T1 is access Something;
17297    for T1'Storage_Size use 10_000;
17298 @end smallexample
17300 @node The GNAT Debug Pool Facility
17301 @section The GNAT Debug Pool Facility
17302 @findex Debug Pool
17303 @cindex storage, pool, memory corruption
17305 @noindent
17306 The use of unchecked deallocation and unchecked conversion can easily
17307 lead to incorrect memory references. The problems generated by such
17308 references are usually difficult to tackle because the symptoms can be
17309 very remote from the origin of the problem. In such cases, it is
17310 very helpful to detect the problem as early as possible. This is the
17311 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17313 In order to use the GNAT specific debugging pool, the user must
17314 associate a debug pool object with each of the access types that may be
17315 related to suspected memory problems. See Ada Reference Manual 13.11.
17316 @smallexample @c ada
17317 type Ptr is access Some_Type;
17318 Pool : GNAT.Debug_Pools.Debug_Pool;
17319 for Ptr'Storage_Pool use Pool;
17320 @end smallexample
17322 @noindent
17323 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17324 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17325 allow the user to redefine allocation and deallocation strategies. They
17326 also provide a checkpoint for each dereference, through the use of
17327 the primitive operation @code{Dereference} which is implicitly called at
17328 each dereference of an access value.
17330 Once an access type has been associated with a debug pool, operations on
17331 values of the type may raise four distinct exceptions,
17332 which correspond to four potential kinds of memory corruption:
17333 @itemize @bullet
17334 @item
17335 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17336 @item
17337 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17338 @item
17339 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17340 @item
17341 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17342 @end itemize
17344 @noindent
17345 For types associated with a Debug_Pool, dynamic allocation is performed using
17346 the standard GNAT allocation routine. References to all allocated chunks of
17347 memory are kept in an internal dictionary. Several deallocation strategies are
17348 provided, whereupon the user can choose to release the memory to the system,
17349 keep it allocated for further invalid access checks, or fill it with an easily
17350 recognizable pattern for debug sessions. The memory pattern is the old IBM
17351 hexadecimal convention: @code{16#DEADBEEF#}.
17353 See the documentation in the file g-debpoo.ads for more information on the
17354 various strategies.
17356 Upon each dereference, a check is made that the access value denotes a
17357 properly allocated memory location. Here is a complete example of use of
17358 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17359 @smallexample @c ada
17360 @iftex
17361 @leftskip=0cm
17362 @end iftex
17363 with Gnat.Io; use Gnat.Io;
17364 with Unchecked_Deallocation;
17365 with Unchecked_Conversion;
17366 with GNAT.Debug_Pools;
17367 with System.Storage_Elements;
17368 with Ada.Exceptions; use Ada.Exceptions;
17369 procedure Debug_Pool_Test is
17371    type T is access Integer;
17372    type U is access all T;
17374    P : GNAT.Debug_Pools.Debug_Pool;
17375    for T'Storage_Pool use P;
17377    procedure Free is new Unchecked_Deallocation (Integer, T);
17378    function UC is new Unchecked_Conversion (U, T);
17379    A, B : aliased T;
17381    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17383 begin
17384    Info (P);
17385    A := new Integer;
17386    B := new Integer;
17387    B := A;
17388    Info (P);
17389    Free (A);
17390    begin
17391       Put_Line (Integer'Image(B.all));
17392    exception
17393       when E : others => Put_Line ("raised: " & Exception_Name (E));
17394    end;
17395    begin
17396       Free (B);
17397    exception
17398       when E : others => Put_Line ("raised: " & Exception_Name (E));
17399    end;
17400    B := UC(A'Access);
17401    begin
17402       Put_Line (Integer'Image(B.all));
17403    exception
17404       when E : others => Put_Line ("raised: " & Exception_Name (E));
17405    end;
17406    begin
17407       Free (B);
17408    exception
17409       when E : others => Put_Line ("raised: " & Exception_Name (E));
17410    end;
17411    Info (P);
17412 end Debug_Pool_Test;
17413 @end smallexample
17415 @noindent
17416 The debug pool mechanism provides the following precise diagnostics on the
17417 execution of this erroneous program:
17418 @smallexample
17419 Debug Pool info:
17420   Total allocated bytes :  0
17421   Total deallocated bytes :  0
17422   Current Water Mark:  0
17423   High Water Mark:  0
17425 Debug Pool info:
17426   Total allocated bytes :  8
17427   Total deallocated bytes :  0
17428   Current Water Mark:  8
17429   High Water Mark:  8
17431 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17432 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17433 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17434 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17435 Debug Pool info:
17436   Total allocated bytes :  8
17437   Total deallocated bytes :  4
17438   Current Water Mark:  4
17439   High Water Mark:  8
17440 @end smallexample
17442 @ifclear vms
17443 @node The gnatmem Tool
17444 @section The @command{gnatmem} Tool
17445 @findex gnatmem
17447 @noindent
17448 The @code{gnatmem} utility monitors dynamic allocation and
17449 deallocation activity in a program, and displays information about
17450 incorrect deallocations and possible sources of memory leaks.
17451 It is designed to work in association with a static runtime library
17452 only and in this context provides three types of information:
17453 @itemize @bullet
17454 @item
17455 General information concerning memory management, such as the total
17456 number of allocations and deallocations, the amount of allocated
17457 memory and the high water mark, i.e.@: the largest amount of allocated
17458 memory in the course of program execution.
17460 @item
17461 Backtraces for all incorrect deallocations, that is to say deallocations
17462 which do not correspond to a valid allocation.
17464 @item
17465 Information on each allocation that is potentially the origin of a memory
17466 leak.
17467 @end itemize
17469 @menu
17470 * Running gnatmem::
17471 * Switches for gnatmem::
17472 * Example of gnatmem Usage::
17473 @end menu
17475 @node Running gnatmem
17476 @subsection Running @code{gnatmem}
17478 @noindent
17479 @code{gnatmem} makes use of the output created by the special version of
17480 allocation and deallocation routines that record call information. This
17481 allows to obtain accurate dynamic memory usage history at a minimal cost to
17482 the execution speed. Note however, that @code{gnatmem} is not supported on
17483 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17484 Solaris and Windows NT/2000/XP (x86).
17486 @noindent
17487 The @code{gnatmem} command has the form
17489 @smallexample
17490 @c    $ gnatmem @ovar{switches} user_program
17491 @c Expanding @ovar macro inline (explanation in macro def comments)
17492       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17493 @end smallexample
17495 @noindent
17496 The program must have been linked with the instrumented version of the
17497 allocation and deallocation routines. This is done by linking with the
17498 @file{libgmem.a} library. For correct symbolic backtrace information,
17499 the user program should be compiled with debugging options
17500 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17502 @smallexample
17503 $ gnatmake -g my_program -largs -lgmem
17504 @end smallexample
17506 @noindent
17507 As library @file{libgmem.a} contains an alternate body for package
17508 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17509 when an executable is linked with library @file{libgmem.a}. It is then not
17510 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17512 @noindent
17513 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17514 This file contains information about all allocations and deallocations
17515 performed by the program. It is produced by the instrumented allocations and
17516 deallocations routines and will be used by @code{gnatmem}.
17518 In order to produce symbolic backtrace information for allocations and
17519 deallocations performed by the GNAT run-time library, you need to use a
17520 version of that library that has been compiled with the @option{-g} switch
17521 (see @ref{Rebuilding the GNAT Run-Time Library}).
17523 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17524 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17525 @option{-i} switch, gnatmem will assume that this file can be found in the
17526 current directory. For example, after you have executed @file{my_program},
17527 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17529 @smallexample
17530 $ gnatmem my_program
17531 @end smallexample
17533 @noindent
17534 This will produce the output with the following format:
17536 *************** debut cc
17537 @smallexample
17538 $ gnatmem my_program
17540 Global information
17541 ------------------
17542    Total number of allocations        :  45
17543    Total number of deallocations      :   6
17544    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17545    High Water Mark                    :  11.40 Kilobytes
17550 Allocation Root # 2
17551 -------------------
17552  Number of non freed allocations    :  11
17553  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17554  High Water Mark                    :   1.27 Kilobytes
17555  Backtrace                          :
17556    my_program.adb:23 my_program.alloc
17560 @end smallexample
17562 The first block of output gives general information. In this case, the
17563 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17564 Unchecked_Deallocation routine occurred.
17566 @noindent
17567 Subsequent paragraphs display  information on all allocation roots.
17568 An allocation root is a specific point in the execution of the program
17569 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17570 construct. This root is represented by an execution backtrace (or subprogram
17571 call stack). By default the backtrace depth for allocations roots is 1, so
17572 that a root corresponds exactly to a source location. The backtrace can
17573 be made deeper, to make the root more specific.
17575 @node Switches for gnatmem
17576 @subsection Switches for @code{gnatmem}
17578 @noindent
17579 @code{gnatmem} recognizes the following switches:
17581 @table @option
17583 @item -q
17584 @cindex @option{-q} (@code{gnatmem})
17585 Quiet. Gives the minimum output needed to identify the origin of the
17586 memory leaks. Omits statistical information.
17588 @item @var{N}
17589 @cindex @var{N} (@code{gnatmem})
17590 N is an integer literal (usually between 1 and 10) which controls the
17591 depth of the backtraces defining allocation root. The default value for
17592 N is 1. The deeper the backtrace, the more precise the localization of
17593 the root. Note that the total number of roots can depend on this
17594 parameter. This parameter must be specified @emph{before} the name of the
17595 executable to be analyzed, to avoid ambiguity.
17597 @item -b n
17598 @cindex @option{-b} (@code{gnatmem})
17599 This switch has the same effect as just depth parameter.
17601 @item -i @var{file}
17602 @cindex @option{-i} (@code{gnatmem})
17603 Do the @code{gnatmem} processing starting from @file{file}, rather than
17604 @file{gmem.out} in the current directory.
17606 @item -m n
17607 @cindex @option{-m} (@code{gnatmem})
17608 This switch causes @code{gnatmem} to mask the allocation roots that have less
17609 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17610 examine even the roots that didn't result in leaks.
17612 @item -s order
17613 @cindex @option{-s} (@code{gnatmem})
17614 This switch causes @code{gnatmem} to sort the allocation roots according to the
17615 specified order of sort criteria, each identified by a single letter. The
17616 currently supported criteria are @code{n, h, w} standing respectively for
17617 number of unfreed allocations, high watermark, and final watermark
17618 corresponding to a specific root. The default order is @code{nwh}.
17620 @end table
17622 @node Example of gnatmem Usage
17623 @subsection Example of @code{gnatmem} Usage
17625 @noindent
17626 The following example shows the use of @code{gnatmem}
17627 on a simple memory-leaking program.
17628 Suppose that we have the following Ada program:
17630 @smallexample @c ada
17631 @group
17632 @cartouche
17633 with Unchecked_Deallocation;
17634 procedure Test_Gm is
17636    type T is array (1..1000) of Integer;
17637    type Ptr is access T;
17638    procedure Free is new Unchecked_Deallocation (T, Ptr);
17639    A : Ptr;
17641    procedure My_Alloc is
17642    begin
17643       A := new T;
17644    end My_Alloc;
17646    procedure My_DeAlloc is
17647       B : Ptr := A;
17648    begin
17649       Free (B);
17650    end My_DeAlloc;
17652 begin
17653    My_Alloc;
17654    for I in 1 .. 5 loop
17655       for J in I .. 5 loop
17656          My_Alloc;
17657       end loop;
17658       My_Dealloc;
17659    end loop;
17660 end;
17661 @end cartouche
17662 @end group
17663 @end smallexample
17665 @noindent
17666 The program needs to be compiled with debugging option and linked with
17667 @code{gmem} library:
17669 @smallexample
17670 $ gnatmake -g test_gm -largs -lgmem
17671 @end smallexample
17673 @noindent
17674 Then we execute the program as usual:
17676 @smallexample
17677 $ test_gm
17678 @end smallexample
17680 @noindent
17681 Then @code{gnatmem} is invoked simply with
17682 @smallexample
17683 $ gnatmem test_gm
17684 @end smallexample
17686 @noindent
17687 which produces the following output (result may vary on different platforms):
17689 @smallexample
17690 Global information
17691 ------------------
17692    Total number of allocations        :  18
17693    Total number of deallocations      :   5
17694    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17695    High Water Mark                    :  56.90 Kilobytes
17697 Allocation Root # 1
17698 -------------------
17699  Number of non freed allocations    :  11
17700  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17701  High Water Mark                    :  46.88 Kilobytes
17702  Backtrace                          :
17703    test_gm.adb:11 test_gm.my_alloc
17705 Allocation Root # 2
17706 -------------------
17707  Number of non freed allocations    :   1
17708  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17709  High Water Mark                    :  10.02 Kilobytes
17710  Backtrace                          :
17711    s-secsta.adb:81 system.secondary_stack.ss_init
17713 Allocation Root # 3
17714 -------------------
17715  Number of non freed allocations    :   1
17716  Final Water Mark (non freed mem)   :  12 Bytes
17717  High Water Mark                    :  12 Bytes
17718  Backtrace                          :
17719    s-secsta.adb:181 system.secondary_stack.ss_init
17720 @end smallexample
17722 @noindent
17723 Note that the GNAT run time contains itself a certain number of
17724 allocations that have no  corresponding deallocation,
17725 as shown here for root #2 and root
17726 #3. This is a normal behavior when the number of non-freed allocations
17727 is one, it allocates dynamic data structures that the run time needs for
17728 the complete lifetime of the program. Note also that there is only one
17729 allocation root in the user program with a single line back trace:
17730 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17731 program shows that 'My_Alloc' is called at 2 different points in the
17732 source (line 21 and line 24). If those two allocation roots need to be
17733 distinguished, the backtrace depth parameter can be used:
17735 @smallexample
17736 $ gnatmem 3 test_gm
17737 @end smallexample
17739 @noindent
17740 which will give the following output:
17742 @smallexample
17743 Global information
17744 ------------------
17745    Total number of allocations        :  18
17746    Total number of deallocations      :   5
17747    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17748    High Water Mark                    :  56.90 Kilobytes
17750 Allocation Root # 1
17751 -------------------
17752  Number of non freed allocations    :  10
17753  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17754  High Water Mark                    :  42.97 Kilobytes
17755  Backtrace                          :
17756    test_gm.adb:11 test_gm.my_alloc
17757    test_gm.adb:24 test_gm
17758    b_test_gm.c:52 main
17760 Allocation Root # 2
17761 -------------------
17762  Number of non freed allocations    :   1
17763  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17764  High Water Mark                    :  10.02 Kilobytes
17765  Backtrace                          :
17766    s-secsta.adb:81  system.secondary_stack.ss_init
17767    s-secsta.adb:283 <system__secondary_stack___elabb>
17768    b_test_gm.c:33   adainit
17770 Allocation Root # 3
17771 -------------------
17772  Number of non freed allocations    :   1
17773  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17774  High Water Mark                    :   3.91 Kilobytes
17775  Backtrace                          :
17776    test_gm.adb:11 test_gm.my_alloc
17777    test_gm.adb:21 test_gm
17778    b_test_gm.c:52 main
17780 Allocation Root # 4
17781 -------------------
17782  Number of non freed allocations    :   1
17783  Final Water Mark (non freed mem)   :  12 Bytes
17784  High Water Mark                    :  12 Bytes
17785  Backtrace                          :
17786    s-secsta.adb:181 system.secondary_stack.ss_init
17787    s-secsta.adb:283 <system__secondary_stack___elabb>
17788    b_test_gm.c:33   adainit
17789 @end smallexample
17791 @noindent
17792 The allocation root #1 of the first example has been split in 2 roots #1
17793 and #3 thanks to the more precise associated backtrace.
17795 @end ifclear
17797 @node Stack Related Facilities
17798 @chapter Stack Related Facilities
17800 @noindent
17801 This chapter describes some useful tools associated with stack
17802 checking and analysis. In
17803 particular, it deals with dynamic and static stack usage measurements.
17805 @menu
17806 * Stack Overflow Checking::
17807 * Static Stack Usage Analysis::
17808 * Dynamic Stack Usage Analysis::
17809 @end menu
17811 @node Stack Overflow Checking
17812 @section Stack Overflow Checking
17813 @cindex Stack Overflow Checking
17814 @cindex -fstack-check
17816 @noindent
17817 For most operating systems, @command{gcc} does not perform stack overflow
17818 checking by default. This means that if the main environment task or
17819 some other task exceeds the available stack space, then unpredictable
17820 behavior will occur. Most native systems offer some level of protection by
17821 adding a guard page at the end of each task stack. This mechanism is usually
17822 not enough for dealing properly with stack overflow situations because
17823 a large local variable could ``jump'' above the guard page.
17824 Furthermore, when the
17825 guard page is hit, there may not be any space left on the stack for executing
17826 the exception propagation code. Enabling stack checking avoids
17827 such situations.
17829 To activate stack checking, compile all units with the gcc option
17830 @option{-fstack-check}. For example:
17832 @smallexample
17833 gcc -c -fstack-check package1.adb
17834 @end smallexample
17836 @noindent
17837 Units compiled with this option will generate extra instructions to check
17838 that any use of the stack (for procedure calls or for declaring local
17839 variables in declare blocks) does not exceed the available stack space.
17840 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17842 For declared tasks, the stack size is controlled by the size
17843 given in an applicable @code{Storage_Size} pragma or by the value specified
17844 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17845 the default size as defined in the GNAT runtime otherwise.
17847 For the environment task, the stack size depends on
17848 system defaults and is unknown to the compiler. Stack checking
17849 may still work correctly if a fixed
17850 size stack is allocated, but this cannot be guaranteed.
17851 @ifclear vms
17852 To ensure that a clean exception is signalled for stack
17853 overflow, set the environment variable
17854 @env{GNAT_STACK_LIMIT} to indicate the maximum
17855 stack area that can be used, as in:
17856 @cindex GNAT_STACK_LIMIT
17858 @smallexample
17859 SET GNAT_STACK_LIMIT 1600
17860 @end smallexample
17862 @noindent
17863 The limit is given in kilobytes, so the above declaration would
17864 set the stack limit of the environment task to 1.6 megabytes.
17865 Note that the only purpose of this usage is to limit the amount
17866 of stack used by the environment task. If it is necessary to
17867 increase the amount of stack for the environment task, then this
17868 is an operating systems issue, and must be addressed with the
17869 appropriate operating systems commands.
17870 @end ifclear
17871 @ifset vms
17872 To have a fixed size stack in the environment task, the stack must be put
17873 in the P0 address space and its size specified.  Use these switches to
17874 create a p0 image:
17876 @smallexample
17877 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17878 @end smallexample
17880 @noindent
17881 The quotes are required to keep case.  The number after @samp{STACK=} is the
17882 size of the environmental task stack in pagelets (512 bytes).  In this example
17883 the stack size is about 2 megabytes.
17885 @noindent
17886 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17887 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17888 more details about the @option{/p0image} qualifier and the @option{stack}
17889 option.
17891 @noindent
17892 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17893 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17894 stack in kilobytes.  For example:
17896 @smallexample
17897 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17898 @end smallexample
17899 @end ifset
17901 @node Static Stack Usage Analysis
17902 @section Static Stack Usage Analysis
17903 @cindex Static Stack Usage Analysis
17904 @cindex -fstack-usage
17906 @noindent
17907 A unit compiled with @option{-fstack-usage} will generate an extra file
17908 that specifies
17909 the maximum amount of stack used, on a per-function basis.
17910 The file has the same
17911 basename as the target object file with a @file{.su} extension.
17912 Each line of this file is made up of three fields:
17914 @itemize
17915 @item
17916 The name of the function.
17917 @item
17918 A number of bytes.
17919 @item
17920 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17921 @end itemize
17923 The second field corresponds to the size of the known part of the function
17924 frame.
17926 The qualifier @code{static} means that the function frame size
17927 is purely static.
17928 It usually means that all local variables have a static size.
17929 In this case, the second field is a reliable measure of the function stack
17930 utilization.
17932 The qualifier @code{dynamic} means that the function frame size is not static.
17933 It happens mainly when some local variables have a dynamic size. When this
17934 qualifier appears alone, the second field is not a reliable measure
17935 of the function stack analysis. When it is qualified with  @code{bounded}, it
17936 means that the second field is a reliable maximum of the function stack
17937 utilization.
17939 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17940 subprogram whose stack usage might be larger than the specified amount of
17941 bytes.  The wording is in keeping with the qualifier documented above.
17943 @node Dynamic Stack Usage Analysis
17944 @section Dynamic Stack Usage Analysis
17946 @noindent
17947 It is possible to measure the maximum amount of stack used by a task, by
17948 adding a switch to @command{gnatbind}, as:
17950 @smallexample
17951 $ gnatbind -u0 file
17952 @end smallexample
17954 @noindent
17955 With this option, at each task termination, its stack usage is  output on
17956 @file{stderr}.
17957 It is not always convenient to output the stack usage when the program
17958 is still running. Hence, it is possible to delay this output until program
17959 termination. for a given number of tasks specified as the argument of the
17960 @option{-u} option. For instance:
17962 @smallexample
17963 $ gnatbind -u100 file
17964 @end smallexample
17966 @noindent
17967 will buffer the stack usage information of the first 100 tasks to terminate and
17968 output this info at program termination. Results are displayed in four
17969 columns:
17971 @noindent
17972 Index | Task Name | Stack Size | Stack Usage
17974 @noindent
17975 where:
17977 @table @emph
17978 @item Index
17979 is a number associated with each task.
17981 @item Task Name
17982 is the name of the task analyzed.
17984 @item Stack Size
17985 is the maximum size for the stack.
17987 @item Stack Usage
17988 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17989 is not entirely analyzed, and it's not possible to know exactly how
17990 much has actually been used.
17992 @end table
17994 @noindent
17995 The environment task stack, e.g., the stack that contains the main unit, is
17996 only processed when the environment variable GNAT_STACK_LIMIT is set.
17998 @noindent
17999 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18000 stack usage reports at run-time. See its body for the details.
18002 @c *********************************
18003 @c *            GNATCHECK          *
18004 @c *********************************
18005 @node Verifying Properties Using gnatcheck
18006 @chapter Verifying Properties Using @command{gnatcheck}
18007 @findex gnatcheck
18008 @cindex @command{gnatcheck}
18010 @noindent
18011 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18012 of Ada source files according to a given set of semantic rules.
18013 @cindex ASIS
18015 In order to check compliance with a given rule, @command{gnatcheck} has to
18016 semantically analyze the Ada sources.
18017 Therefore, checks can only be performed on
18018 legal Ada units. Moreover, when a unit depends semantically upon units located
18019 outside the current directory, the source search path has to be provided when
18020 calling @command{gnatcheck}, either through a specified project file or
18021 through @command{gnatcheck} switches.
18023 For full details, refer to @cite{GNATcheck Reference Manual} document.
18026 @c *********************************
18027 @node Creating Sample Bodies Using gnatstub
18028 @chapter Creating Sample Bodies Using @command{gnatstub}
18029 @findex gnatstub
18031 @noindent
18032 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18033 for library unit declarations.
18035 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
18036 driver (see @ref{The GNAT Driver and Project Files}).
18038 To create a body stub, @command{gnatstub} has to compile the library
18039 unit declaration. Therefore, bodies can be created only for legal
18040 library units. Moreover, if a library unit depends semantically upon
18041 units located outside the current directory, you have to provide
18042 the source search path when calling @command{gnatstub}, see the description
18043 of @command{gnatstub} switches below.
18045 By default, all the program unit body stubs generated by @code{gnatstub}
18046 raise the predefined @code{Program_Error} exception, which will catch
18047 accidental calls of generated stubs. This behavior can be changed with
18048 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
18050 @menu
18051 * Running gnatstub::
18052 * Switches for gnatstub::
18053 @end menu
18055 @node Running gnatstub
18056 @section Running @command{gnatstub}
18058 @noindent
18059 @command{gnatstub} has a command-line interface of the form:
18061 @smallexample
18062 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
18063 @c Expanding @ovar macro inline (explanation in macro def comments)
18064 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18065 @end smallexample
18067 @noindent
18068 where
18069 @table @var
18070 @item filename
18071 is the name of the source file that contains a library unit declaration
18072 for which a body must be created. The file name may contain the path
18073 information.
18074 The file name does not have to follow the GNAT file name conventions. If the
18075 name
18076 does not follow GNAT file naming conventions, the name of the body file must
18077 be provided
18078 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18079 If the file name follows the GNAT file naming
18080 conventions and the name of the body file is not provided,
18081 @command{gnatstub}
18082 creates the name
18083 of the body file from the argument file name by replacing the @file{.ads}
18084 suffix
18085 with the @file{.adb} suffix.
18087 @item directory
18088 indicates the directory in which the body stub is to be placed (the default
18089 is the
18090 current directory)
18092 @item @samp{@var{gcc_switches}} is a list of switches for
18093 @command{gcc}. They will be passed on to all compiler invocations made by
18094 @command{gnatstub} to generate the ASIS trees. Here you can provide
18095 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18096 use the @option{-gnatec} switch to set the configuration file,
18097 use the @option{-gnat05} switch if sources should be compiled in
18098 Ada 2005 mode etc.
18100 @item switches
18101 is an optional sequence of switches as described in the next section
18102 @end table
18104 @node Switches for gnatstub
18105 @section Switches for @command{gnatstub}
18107 @table @option
18108 @c !sort!
18110 @item ^-f^/FULL^
18111 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18112 If the destination directory already contains a file with the name of the
18113 body file
18114 for the argument spec file, replace it with the generated body stub.
18116 @item ^-hs^/HEADER=SPEC^
18117 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18118 Put the comment header (i.e., all the comments preceding the
18119 compilation unit) from the source of the library unit declaration
18120 into the body stub.
18122 @item ^-hg^/HEADER=GENERAL^
18123 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18124 Put a sample comment header into the body stub.
18126 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
18127 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
18128 Use the content of the file as the comment header for a generated body stub.
18130 @ifclear vms
18131 @item -IDIR
18132 @cindex @option{-IDIR} (@command{gnatstub})
18133 @itemx -I-
18134 @cindex @option{-I-} (@command{gnatstub})
18135 @end ifclear
18136 @ifset vms
18137 @item /NOCURRENT_DIRECTORY
18138 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18139 @end ifset
18140 ^These switches have ^This switch has^ the same meaning as in calls to
18141 @command{gcc}.
18142 ^They define ^It defines ^ the source search path in the call to
18143 @command{gcc} issued
18144 by @command{gnatstub} to compile an argument source file.
18146 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18147 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18148 This switch has the same meaning as in calls to @command{gcc}.
18149 It defines the additional configuration file to be passed to the call to
18150 @command{gcc} issued
18151 by @command{gnatstub} to compile an argument source file.
18153 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18154 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18155 (@var{n} is a non-negative integer). Set the maximum line length in the
18156 body stub to @var{n}; the default is 79. The maximum value that can be
18157 specified is 32767. Note that in the special case of configuration
18158 pragma files, the maximum is always 32767 regardless of whether or
18159 not this switch appears.
18161 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18162 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18163 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18164 the generated body sample to @var{n}.
18165 The default indentation is 3.
18167 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18168 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18169 Order local bodies alphabetically. (By default local bodies are ordered
18170 in the same way as the corresponding local specs in the argument spec file.)
18172 @item ^-i^/INDENTATION=^@var{n}
18173 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18174 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18176 @item ^-k^/TREE_FILE=SAVE^
18177 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18178 Do not remove the tree file (i.e., the snapshot of the compiler internal
18179 structures used by @command{gnatstub}) after creating the body stub.
18181 @item ^-l^/LINE_LENGTH=^@var{n}
18182 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18183 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18185 @item ^--no-exception^/NO_EXCEPTION^
18186 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
18187 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18188 This is not always possible for function stubs.
18190 @item ^--no-local-header^/NO_LOCAL_HEADER^
18191 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
18192 Do not place local comment header with unit name before body stub for a
18193 unit.
18195 @item ^-o ^/BODY=^@var{body-name}
18196 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18197 Body file name.  This should be set if the argument file name does not
18198 follow
18199 the GNAT file naming
18200 conventions. If this switch is omitted the default name for the body will be
18201 obtained
18202 from the argument file name according to the GNAT file naming conventions.
18204 @item ^-q^/QUIET^
18205 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18206 Quiet mode: do not generate a confirmation when a body is
18207 successfully created, and do not generate a message when a body is not
18208 required for an
18209 argument unit.
18211 @item ^-r^/TREE_FILE=REUSE^
18212 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18213 Reuse the tree file (if it exists) instead of creating it.  Instead of
18214 creating the tree file for the library unit declaration, @command{gnatstub}
18215 tries to find it in the current directory and use it for creating
18216 a body. If the tree file is not found, no body is created. This option
18217 also implies @option{^-k^/SAVE^}, whether or not
18218 the latter is set explicitly.
18220 @item ^-t^/TREE_FILE=OVERWRITE^
18221 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18222 Overwrite the existing tree file.  If the current directory already
18223 contains the file which, according to the GNAT file naming rules should
18224 be considered as a tree file for the argument source file,
18225 @command{gnatstub}
18226 will refuse to create the tree file needed to create a sample body
18227 unless this option is set.
18229 @item ^-v^/VERBOSE^
18230 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18231 Verbose mode: generate version information.
18233 @end table
18235 @c *********************************
18236 @node Creating Unit Tests Using gnattest
18237 @chapter Creating Unit Tests Using @command{gnattest}
18238 @findex gnattest
18240 @noindent
18241 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18242 as well as a test driver infrastructure (harness). @command{gnattest} creates
18243 a skeleton for each visible subprogram in the packages under consideration when
18244 they do not exist already.
18246 In order to process source files from a project, @command{gnattest} has to
18247 semantically analyze the sources. Therefore, test skeletons can only be
18248 generated for legal Ada units. If a unit is dependent on other units,
18249 those units should be among the source files of the project or of other projects
18250 imported by this one.
18252 Generated skeletons and harnesses are based on the AUnit testing framework.
18253 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18254 for Java or CppUnit for C++. While it is advised that gnattest users read
18255 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18256 For correct operation of @command{gnattest}, AUnit should be installed and
18257 aunit.gpr must be on the project path. This happens automatically when Aunit
18258 is installed at its default location.
18259 @menu
18260 * Running gnattest::
18261 * Switches for gnattest::
18262 * Project Attributes for gnattest::
18263 * Simple Example::
18264 * Setting Up and Tearing Down the Testing Environment::
18265 * Regenerating Tests::
18266 * Default Test Behavior::
18267 * Testing Primitive Operations of Tagged Types::
18268 * Testing Inheritance::
18269 * Tagged Types Substitutability Testing::
18270 * Testing with Contracts::
18271 * Additional Tests::
18272 @ifclear vms
18273 * Support for other platforms/run-times::
18274 @end ifclear
18275 * Current Limitations::
18276 @end menu
18278 @node Running gnattest
18279 @section Running @command{gnattest}
18281 @noindent
18282 @command{gnattest} has a command-line interface of the form
18284 @smallexample
18285 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
18286 @c Expanding @ovar macro inline (explanation in macro def comments)
18287 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18288 @end smallexample
18290 @noindent
18291 where
18292 @table @var
18294 @item -Pprojname
18295 specifies the project defining the location of source files. When no
18296 file names are provided on the command line, all sources in the project
18297 are used as input. This switch is required.
18299 @item filename
18300 is the name of the source file containing the library unit package declaration
18301 for which a test package will be created. The file name may be given with a
18302 path.
18304 @item @samp{@var{gcc_switches}}
18305 is a list of switches for
18306 @command{gcc}. These switches will be passed on to all compiler invocations
18307 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
18308 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18309 use the @option{-gnatec} switch to set the configuration file,
18310 use the @option{-gnat05} switch if sources should be compiled in
18311 Ada 2005 mode, etc.
18313 @item switches
18314 is an optional sequence of switches as described in the next section.
18316 @end table
18318 @command{gnattest} results can be found in two different places.
18320 @itemize @bullet
18321 @item automatic harness:
18322 the harness code, which is located by default in "gnattest/harness" directory
18323 that is created in the object directory of corresponding project file. All of
18324 this code is generated completely automatically and can be destroyed and
18325 regenerated at will. It is not recommended to modify this code manually, since
18326 it could easily be overridden by mistake. The entry point in the harness code is
18327 the project file named @command{test_driver.gpr}. Tests can be compiled and run
18328 using a command such as:
18330 @smallexample
18331 gnatmake -P<harness-dir>/test_driver
18332 test_runner
18333 @end smallexample
18335 Note that you might need to specify the necessary values of scenario variables
18336 when you are not using the AUnit defaults.
18338 @item actual unit test skeletons:
18339 a test skeleton for each visible subprogram is created in a separate file, if it
18340 doesn't exist already. By default, those separate test files are located in a
18341 "gnattest/tests" directory that is created in the object directory of
18342 corresponding project file. For example, if a source file my_unit.ads in
18343 directory src contains a visible subprogram Proc, then the corresponding unit
18344 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
18345 <code> is a signature encoding used to differentiate test names in case of
18346 overloading.
18348 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
18349 this will cause a name conflict with the generated test package.
18350 @end itemize
18352 @node Switches for gnattest
18353 @section Switches for @command{gnattest}
18355 @table @option
18356 @c !sort!
18358 @item --harness-only
18359 @cindex @option{--harness-only} (@command{gnattest})
18360 When this option is given, @command{gnattest} creates a harness for all
18361 sources, treating them as test packages.
18363 @item --additional-tests=@var{projname}
18364 @cindex @option{--additional-tests} (@command{gnattest})
18365 Sources described in @var{projname} are considered potential additional
18366 manual tests to be added to the test suite.
18368 @item -r
18369 @cindex @option{-r} (@command{gnattest})
18370 Recursively consider all sources from all projects.
18372 @item -X@var{name=value}
18373 @cindex @option{-X} (@command{gnattest})
18374 Indicate that external variable @var{name} has the value @var{value}.
18376 @item -q
18377 @cindex @option{-q} (@command{gnattest})
18378 Suppresses noncritical output messages.
18380 @item -v
18381 @cindex @option{-v} (@command{gnattest})
18382 Verbose mode: generates version information.
18384 @item --validate-type-extensions
18385 @cindex @option{--validate-type-extensions} (@command{gnattest})
18386 Enables substitution check: run all tests from all parents in order
18387 to check substitutability.
18389 @item --skeleton-default=@var{val}
18390 @cindex @option{--skeleton-default} (@command{gnattest})
18391 Specifies the default behavior of generated skeletons. @var{val} can be either
18392 "fail" or "pass", "fail" being the default.
18394 @item --tests-root=@var{dirname}
18395 @cindex @option{--tests-root} (@command{gnattest})
18396 The directory hierarchy of tested sources is recreated in the @var{dirname}
18397 directory, and test packages are placed in corresponding directories.
18398 If the @var{dirname} is a relative path, it is considered relative to the object
18399 directory of the project file. When all sources from all projects are taken
18400 recursively from all projects, directory hierarchies of tested sources are
18401 recreated for each project in their object directories and test packages are
18402 placed accordingly.
18404 @item --subdir=@var{dirname}
18405 @cindex @option{--subdir} (@command{gnattest})
18406 Test packages are placed in subdirectories.
18408 @item --tests-dir=@var{dirname}
18409 @cindex @option{--tests-dir} (@command{gnattest})
18410 All test packages are placed in the @var{dirname} directory.
18411 If the @var{dirname} is a relative path, it is considered relative to the object
18412 directory of the project file. When all sources from all projects are taken
18413 recursively from all projects, @var{dirname} directories are created for each
18414 project in their object directories and test packages are placed accordingly.
18416 @item --harness-dir=@var{dirname}
18417 @cindex @option{--harness-dir} (@command{gnattest})
18418 specifies the directory that will hold the harness packages and project file
18419 for the test driver. If the @var{dirname} is a relative path, it is considered
18420 relative to the object directory of the project file.
18422 @item --separates
18423 @cindex @option{--separates} (@command{gnattest})
18424 Bodies of all test routines are generated as separates. Note that this mode is
18425 kept for compatibility reasons only and it is not advised to use it due to
18426 possible problems with hash in names of test skeletons when using an
18427 inconsistent casing. Separate test skeletons can be incorporated to monolith
18428 test package with improved hash being used by using @option{--transition}
18429 switch.
18432 @item --transition
18433 @cindex @option{--transition} (@command{gnattest})
18434 This allows transition from separate test routines to monolith test packages.
18435 All matching test routines are overwritten with contents of corresponding
18436 separates. Note that if separate test routines had any manually added with
18437 clauses they will be moved to the test package body as is and have to be moved
18438 by hand.
18440 @end table
18442 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
18443 mutually exclusive.
18445 @node Project Attributes for gnattest
18446 @section Project Attributes for @command{gnattest}
18448 @noindent
18450 Most of the command-line options can also be passed to the tool by adding
18451 special attributes to the project file. Those attributes should be put in
18452 package gnattest. Here is the list of attributes:
18454 @itemize @bullet
18456 @item Tests_Root
18457 is used to select the same output mode as with the --tests-root option.
18458 This attribute cannot be used together with Subdir or Tests_Dir.
18460 @item Subdir
18461 is used to select the same output mode as with the --subdir option.
18462 This attribute cannot be used together with Tests_Root or Tests_Dir.
18464 @item Tests_Dir
18465 is used to select the same output mode as with the --tests-dir option.
18466 This attribute cannot be used together with Subdir or Tests_Root.
18468 @item Harness_Dir
18469 is used to specify the directory in which to place harness packages and project
18470 file for the test driver, otherwise specified by --harness-dir.
18472 @item Additional_Tests
18473 is used to specify the project file, otherwise given by
18474 --additional-tests switch.
18476 @item Skeletons_Default
18477 is used to specify the default behaviour of test skeletons, otherwise
18478 specified by --skeleton-default option. The value of this attribute
18479 should be either "pass" or "fail".
18481 @end itemize
18483 Each of those attributes can be overridden from the command line if needed.
18484 Other @command{gnattest} switches can also be passed via the project
18485 file as an attribute list called GNATtest_Switches.
18487 @node Simple Example
18488 @section Simple Example
18490 @noindent
18492 Let's take a very simple example using the first @command{gnattest} example
18493 located in:
18495 @smallexample
18496 <install_prefix>/share/examples/gnattest/simple
18497 @end smallexample
18499 This project contains a simple package containing one subprogram. By running gnattest:
18501 @smallexample
18502 $ gnattest --harness-dir=driver -Psimple.gpr
18503 @end smallexample
18505 a test driver is created in directory "driver". It can be compiled and run:
18507 @smallexample
18508 $ cd driver
18509 $ gprbuild -Ptest_driver
18510 $ test_runner
18511 @end smallexample
18513 One failed test with diagnosis "test not implemented" is reported.
18514 Since no special output option was specified, the test package Simple.Tests
18515 is located in:
18517 @smallexample
18518 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
18519 @end smallexample
18521 For each package containing visible subprograms, a child test package is
18522 generated. It contains one test routine per tested subprogram. Each
18523 declaration of a test subprogram has a comment specifying which tested
18524 subprogram it corresponds to. Bodies of test routines are placed in test package
18525 bodies and are surrounded by special comment sections. Those comment sections
18526 should not be removed or modified in order for gnattest to be able to regenerate
18527 test packages and keep already written tests in place.
18528 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
18529 a single statement: a call to procedure Assert. It has two arguments:
18530 the Boolean expression we want to check and the diagnosis message to display if
18531 the condition is false.
18533 That is where actual testing code should be written after a proper setup.
18534 An actual check can be performed by replacing the Assert call with:
18536 @smallexample @c ada
18537 Assert (Inc (1) = 2, "wrong incrementation");
18538 @end smallexample
18540 After recompiling and running the test driver, one successfully passed test
18541 is reported.
18543 @node Setting Up and Tearing Down the Testing Environment
18544 @section Setting Up and Tearing Down the Testing Environment
18546 @noindent
18548 Besides test routines themselves, each test package has a parent package
18549 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
18550 overwritten by the tool. Set_Up is called before each test routine of the
18551 package and Tear_Down is called after each test routine. Those two procedures
18552 can be used to perform necessary initialization and finalization,
18553 memory allocation, etc. Test type declared in Test_Data package is parent type
18554 for the test type of test package and can have user-defined components whose
18555 values can be set by Set_Up routine and used in test routines afterwards.
18557 @node Regenerating Tests
18558 @section Regenerating Tests
18560 @noindent
18562 Bodies of test routines and test_data packages are never overridden after they
18563 have been created once. As long as the name of the subprogram, full expanded Ada
18564 names, and the order of its parameters is the same, and comment sections are
18565 intact the old test routine will fit in its place and no test skeleton will be
18566 generated for the subprogram.
18568 This can be demonstrated with the previous example. By uncommenting declaration
18569 and body of function Dec in simple.ads and simple.adb, running
18570 @command{gnattest} on the project, and then running the test driver:
18572 @smallexample
18573 gnattest --harness-dir=driver -Psimple.gpr
18574 cd driver
18575 gprbuild -Ptest_driver
18576 test_runner
18577 @end smallexample
18579 the old test is not replaced with a stub, nor is it lost, but a new test
18580 skeleton is created for function Dec.
18582 The only way of regenerating tests skeletons is to remove the previously created
18583 tests together with corresponding comment sections.
18585 @node Default Test Behavior
18586 @section Default Test Behavior
18588 @noindent
18590 The generated test driver can treat unimplemented tests in two ways:
18591 either count them all as failed (this is useful to see which tests are still
18592 left to implement) or as passed (to sort out unimplemented ones from those
18593 actually failing).
18595 The test driver accepts a switch to specify this behavior:
18596 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
18597 @command{gnattest}).
18599 The default behavior of the test driver is set with the same switch
18600 as passed to gnattest when generating the test driver.
18602 Passing it to the driver generated on the first example:
18604 @smallexample
18605 test_runner --skeleton-default=pass
18606 @end smallexample
18608 makes both tests pass, even the unimplemented one.
18610 @node Testing Primitive Operations of Tagged Types
18611 @section Testing Primitive Operations of Tagged Types
18613 @noindent
18615 Creation of test skeletons for primitive operations of tagged types entails
18616 a number of features. Test routines for all primitives of a given tagged type
18617 are placed in a separate child package named according to the tagged type. For
18618 example, if you have tagged type T in package P, all tests for primitives
18619 of T will be in P.T_Test_Data.T_Tests.
18621 Consider running gnattest on the second example (note: actual tests for this
18622 example already exist, so there's no need to worry if the tool reports that
18623 no new stubs were generated):
18625 @smallexample
18626 cd <install_prefix>/share/examples/gnattest/tagged_rec
18627 gnattest --harness-dir=driver -Ptagged_rec.gpr
18628 @end smallexample
18630 Taking a closer look at the test type declared in the test package
18631 Speed1.Controller_Test_Data is necessary. It is declared in:
18633 @smallexample
18634 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
18635 @end smallexample
18637 Test types are direct or indirect descendants of
18638 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18639 subprograms, the user doesn't need to be concerned with them. However,
18640 when generating test packages for primitive operations, there are some things
18641 the user needs to know.
18643 Type Test_Controller has components that allow assignment of various
18644 derivations of type Controller. And if you look at the specification of
18645 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18646 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18647 Thus, test types mirror the hierarchy of tested types.
18649 The Set_Up procedure of Test_Data package corresponding to a test package
18650 of primitive operations of type T assigns to Fixture a reference to an
18651 object of that exact type T. Notice, however, that if the tagged type has
18652 discriminants, the Set_Up only has a commented template for setting
18653 up the fixture, since filling the discriminant with actual value is up
18654 to the user.
18656 The knowledge of the structure of test types allows additional testing
18657 without additional effort. Those possibilities are described below.
18659 @node Testing Inheritance
18660 @section Testing Inheritance
18662 @noindent
18664 Since the test type hierarchy mimics the hierarchy of tested types, the
18665 inheritance of tests takes place. An example of such inheritance can be
18666 seen by running the test driver generated for the second example. As previously
18667 mentioned, actual tests are already written for this example.
18669 @smallexample
18670 cd driver
18671 gprbuild -Ptest_driver
18672 test_runner
18673 @end smallexample
18675 There are 6 passed tests while there are only 5 testable subprograms. The test
18676 routine for function Speed has been inherited and run against objects of the
18677 derived type.
18679 @node Tagged Types Substitutability Testing
18680 @section Tagged Types Substitutability Testing
18682 @noindent
18684 Tagged Types Substitutability Testing is a way of verifying the global type
18685 consistency by testing. Global type consistency is a principle stating that if
18686 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18687 then objects of type T may be replaced with objects of type S (that is,
18688 objects of type S may be substituted for objects of type T), without
18689 altering any of the desirable properties of the program. When the properties
18690 of the program are expressed in the form of subprogram preconditions and
18691 postconditions (let's call them pre and post), the principle is formulated as
18692 relations between the pre and post of primitive operations and the pre and post
18693 of their derived operations. The pre of a derived operation should not be
18694 stronger than the original pre, and the post of the derived operation should
18695 not be weaker than the original post. Those relations ensure that verifying if
18696 a dispatching call is safe can be done just by using the pre and post of the
18697 root operation.
18699 Verifying global type consistency by testing consists of running all the unit
18700 tests associated with the primitives of a given tagged type with objects of its
18701 derived types.
18703 In the example used in the previous section, there was clearly a violation of
18704 type consistency. The overriding primitive Adjust_Speed in package Speed2
18705 removes the functionality of the overridden primitive and thus doesn't respect
18706 the consistency principle.
18707 Gnattest has a special option to run overridden parent tests against objects
18708 of the type which have overriding primitives:
18710 @smallexample
18711 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
18712 cd driver
18713 gprbuild -Ptest_driver
18714 test_runner
18715 @end smallexample
18717 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18718 against objects of the derived type.
18720 Non-overridden tests are already inherited for derived test types, so the
18721 --validate-type-extensions enables the application of overriden tests to objects
18722 of derived types.
18724 @node Testing with Contracts
18725 @section Testing with Contracts
18727 @noindent
18729 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
18730 as well as corresponding aspects.
18731 Test routines are generated, one per each Test_Case associated with a tested
18732 subprogram. Those test routines have special wrappers for tested functions
18733 that have composition of pre- and postcondition of the subprogram with
18734 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18735 either count for Nominal mode or do not count for Robustness mode).
18737 The third example demonstrates how this works:
18739 @smallexample
18740 cd <install_prefix>/share/examples/gnattest/contracts
18741 gnattest --harness-dir=driver -Pcontracts.gpr
18742 @end smallexample
18744 Putting actual checks within the range of the contract does not cause any
18745 error reports. For example, for the test routine which corresponds to
18746 test case 1:
18748 @smallexample @c ada
18749 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18750 @end smallexample
18752 and for the test routine corresponding to test case 2:
18754 @smallexample @c ada
18755 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18756 @end smallexample
18758 are acceptable:
18760 @smallexample
18761 cd driver
18762 gprbuild -Ptest_driver
18763 test_runner
18764 @end smallexample
18766 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18767 a precondition violation for test case one. Also, by using any otherwise
18768 correct but positive pair of numbers in the second test routine, you can also
18769 get a precondition violation. Postconditions are checked and reported
18770 the same way.
18772 @node Additional Tests
18773 @section Additional Tests
18775 @noindent
18776 @command{gnattest} can add user-written tests to the main suite of the test
18777 driver. @command{gnattest} traverses the given packages and searches for test
18778 routines. All procedures with a single in out parameter of a type which is
18779 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18780 specifications are added to the suites and are then executed by the test driver.
18781 (Set_Up and Tear_Down are filtered out.)
18783 An example illustrates two ways of creating test harnesses for user-written
18784 tests. Directory additional_tests contains an AUnit-based test driver written
18785 by hand.
18787 @smallexample
18788 <install_prefix>/share/examples/gnattest/additional_tests/
18789 @end smallexample
18791 To create a test driver for already-written tests, use the --harness-only
18792 option:
18794 @smallexample
18795 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18796   --harness-only
18797 gnatmake -Pharness_only/test_driver.gpr
18798 harness_only/test_runner
18799 @end smallexample
18801 Additional tests can also be executed together with generated tests:
18803 @smallexample
18804 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18805   --harness-dir=mixing
18806 gnatmake -Pmixing/test_driver.gpr
18807 mixing/test_runner
18808 @end smallexample
18810 @ifclear vms
18811 @node Support for other platforms/run-times
18812 @section Support for other platforms/run-times
18814 @noindent
18815 @command{gnattest} can be used to generate the test harness for platforms
18816 and run-time libraries others than the default native target with the
18817 default full run-time. For example, when using a limited run-time library
18818 such as Zero FootPrint (ZFP), a simplified harness is generated.
18820 Two variables are used to tell the underlying AUnit framework how to generate
18821 the test harness: @code{PLATFORM}, which identifies the target, and
18822 @code{RUNTIME}, used to determine the run-time library for which the harness
18823 is generated. Corresponding prefix should also be used when calling
18824 @command{gnattest} for non-native targets. For example, the following options
18825 are used to generate the AUnit test harness for a PowerPC ELF target using
18826 the ZFP run-time library:
18828 @smallexample
18829 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
18830 @end smallexample
18831 @end ifclear
18833 @node Current Limitations
18834 @section Current Limitations
18836 @noindent
18838 The tool currently does not support following features:
18840 @itemize @bullet
18841 @item generic tests for generic packages and package instantiations
18842 @item tests for protected subprograms and entries
18844 @end itemize
18846 @c *********************************
18847 @node Performing Dimensionality Analysis in GNAT
18848 @chapter Performing Dimensionality Analysis in GNAT
18849 @noindent
18850 The GNAT compiler now supports dimensionality checking. The user can
18851 specify physical units for objects, and the compiler will verify that uses
18852 of these objects are compatible with their dimensions, in a fashion that is
18853 familiar to engineering practice. The dimensions of algebraic expressions
18854 (including powers with static exponents) are computed from their consistuents.
18856 This feature depends on Ada 2012 aspect specifications, and is available from
18857 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
18858 the user to define a system of units; the aspect Dimension then allows the user
18859 to declare dimensioned quantities within a given system.
18861 The major advantage of this model is that it does not require the declaration of
18862 multiple operators for all possible combinations of types: it is only necessary
18863 to use the proper subtypes in object declarations.
18865 The simplest way to impose dimensionality checking on a computation is to make
18866 use of the package System.Dim.Mks, which is part of the GNAT library. This
18867 package defines a floating-point type MKS_Type, for which a sequence of
18868 dimension names are specified, together with their conventional abbreviations.
18869 The following should be read together with the full specification of the
18870 package, in file s-dimmks.ads.
18872 @smallexample @c ada
18873    type Mks_Type is new Long_Long_Float
18874      with
18875       Dimension_System => (
18876         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
18877         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
18878         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
18879         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
18880         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
18881         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
18882         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
18883 @end smallexample
18885 @noindent
18886 The package then defines a series of subtypes that correspond to these
18887 conventional units. For example:
18888 @smallexample @c ada
18889    subtype Length is Mks_Type
18890      with
18891       Dimension => (Symbol => 'm',
18892         Meter  => 1,
18893         others => 0);
18894 @end smallexample
18895 @noindent
18896 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
18897 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
18898 the SI system).
18900 The package also defines conventional names for values of each unit, for
18901 example:
18903 @smallexample @c ada
18904    m   : constant Length           := 1.0;
18905    kg  : constant Mass             := 1.0;
18906    s   : constant Time             := 1.0;
18907    A   : constant Electric_Current := 1.0;
18908 @end smallexample
18910 @noindent
18911 as well as useful multiples of these units:
18913 @smallexample @c ada
18914    cm  : constant Length := 1.0E-02;
18915    g   : constant Mass   := 1.0E-03;
18916    min : constant Time   := 60.0;
18917    day : constant TIme   := 60.0 * 24.0 * min;
18918   ...
18919 @end smallexample
18921 @noindent
18922 The user can then define a derived unit by providing the aspect that
18923 specifies its dimensions within the MKS system, as well as the string to
18924 be used for output of a value of that unit:
18926 @smallexample @c ada
18927   subtype Acceleration is Mks_Type
18928     with Dimension => ("m/sec^^^2", Meter => 1, Second => -2, others => 0);
18929 @end smallexample
18931 @noindent
18932 Here is a complete example of use:
18934 @smallexample @c ada
18935 with System.Dim.MKS; use System.Dim.Mks;
18936 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
18937 with Text_IO; use Text_IO;
18938 procedure Free_Fall is
18939   subtype Acceleration is Mks_Type
18940     with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
18941   G : constant acceleration := 9.81 * m / (s ** 2);
18942   T : Time := 10.0*s;
18943   Distance : Length;
18944 begin
18945   Put ("Gravitational constant: ");
18946   Put (G, Aft => 2, Exp => 0); Put_Line ("");
18947   Distance := 0.5 * G * T ** 2;
18948   Put ("distance travelled in 10 seconds of free fall ");
18949   Put (Distance, Aft => 2, Exp => 0);
18950   Put_Line ("");
18951 end Free_Fall;
18952 @end smallexample
18954 @noindent
18955 Execution of this program yields:
18956 @smallexample
18957 Gravitational constant:  9.81 m/sec^^^2
18958 distance travelled in 10 seconds of free fall 490.50 m
18959 @end smallexample
18961 @noindent
18962 However, incorrect assignments such as:
18964 @smallexample @c ada
18965    Distance := 5.0;
18966    Distance := 5.0 * kg:
18967 @end smallexample
18969 @noindent
18970 are rejected with the following diagnoses:
18972 @smallexample
18973    Distance := 5.0;
18974       >>> dimensions mismatch in assignment
18975       >>> left-hand side has dimension [L]
18976       >>> right-hand side is dimensionless
18978    Distance := 5.0 * kg:
18979       >>> dimensions mismatch in assignment
18980       >>> left-hand side has dimension [L]
18981       >>> right-hand side has dimension [M]
18982 @end smallexample
18984 @noindent
18985 The dimensions of an expression are properly displayed, even if there is
18986 no explicit subtype for it. If we add to the program:
18988 @smallexample @c ada
18989       Put ("Final velocity: ");
18990       Put (G * T, Aft =>2, Exp =>0);
18991       Put_Line ("");
18992 @end smallexample
18994 @noindent
18995 then the output includes:
18996 @smallexample
18997      Final velocity: 98.10 m.s**(-1)
18998 @end smallexample
19000 @c *********************************
19001 @node Generating Ada Bindings for C and C++ headers
19002 @chapter Generating Ada Bindings for C and C++ headers
19003 @findex binding
19005 @noindent
19006 GNAT now comes with a binding generator for C and C++ headers which is
19007 intended to do 95% of the tedious work of generating Ada specs from C
19008 or C++ header files.
19010 Note that this capability is not intended to generate 100% correct Ada specs,
19011 and will is some cases require manual adjustments, although it can often
19012 be used out of the box in practice.
19014 Some of the known limitations include:
19016 @itemize @bullet
19017 @item only very simple character constant macros are translated into Ada
19018 constants. Function macros (macros with arguments) are partially translated
19019 as comments, to be completed manually if needed.
19020 @item some extensions (e.g. vector types) are not supported
19021 @item pointers to pointers or complex structures are mapped to System.Address
19022 @item identifiers with identical name (except casing) will generate compilation
19023       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19024 @end itemize
19026 The code generated is using the Ada 2005 syntax, which makes it
19027 easier to interface with other languages than previous versions of Ada.
19029 @menu
19030 * Running the binding generator::
19031 * Generating bindings for C++ headers::
19032 * Switches::
19033 @end menu
19035 @node Running the binding generator
19036 @section Running the binding generator
19038 @noindent
19039 The binding generator is part of the @command{gcc} compiler and can be
19040 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19041 spec files for the header files specified on the command line, and all
19042 header files needed by these files transitively. For example:
19044 @smallexample
19045 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19046 $ gcc -c -gnat05 *.ads
19047 @end smallexample
19049 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19050 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19051 correspond to the files @file{/usr/include/time.h},
19052 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19053 mode these Ada specs.
19055 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19056 and will attempt to generate corresponding Ada comments.
19058 If you want to generate a single Ada file and not the transitive closure, you
19059 can use instead the @option{-fdump-ada-spec-slim} switch.
19061 You can optionally specify a parent unit, of which all generated units will
19062 be children, using @code{-fada-spec-parent=}@var{unit}.
19064 Note that we recommend when possible to use the @command{g++} driver to
19065 generate bindings, even for most C headers, since this will in general
19066 generate better Ada specs. For generating bindings for C++ headers, it is
19067 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
19068 is equivalent in this case. If @command{g++} cannot work on your C headers
19069 because of incompatibilities between C and C++, then you can fallback to
19070 @command{gcc} instead.
19072 For an example of better bindings generated from the C++ front-end,
19073 the name of the parameters (when available) are actually ignored by the C
19074 front-end. Consider the following C header:
19076 @smallexample
19077 extern void foo (int variable);
19078 @end smallexample
19080 with the C front-end, @code{variable} is ignored, and the above is handled as:
19082 @smallexample
19083 extern void foo (int);
19084 @end smallexample
19086 generating a generic:
19088 @smallexample
19089 procedure foo (param1 : int);
19090 @end smallexample
19092 with the C++ front-end, the name is available, and we generate:
19094 @smallexample
19095 procedure foo (variable : int);
19096 @end smallexample
19098 In some cases, the generated bindings will be more complete or more meaningful
19099 when defining some macros, which you can do via the @option{-D} switch. This
19100 is for example the case with @file{Xlib.h} under GNU/Linux:
19102 @smallexample
19103 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
19104 @end smallexample
19106 The above will generate more complete bindings than a straight call without
19107 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
19109 In other cases, it is not possible to parse a header file in a stand-alone
19110 manner, because other include files need to be included first. In this
19111 case, the solution is to create a small header file including the needed
19112 @code{#include} and possible @code{#define} directives. For example, to
19113 generate Ada bindings for @file{readline/readline.h}, you need to first
19114 include @file{stdio.h}, so you can create a file with the following two
19115 lines in e.g. @file{readline1.h}:
19117 @smallexample
19118 #include <stdio.h>
19119 #include <readline/readline.h>
19120 @end smallexample
19122 and then generate Ada bindings from this file:
19124 @smallexample
19125 $ g++ -c -fdump-ada-spec readline1.h
19126 @end smallexample
19128 @node Generating bindings for C++ headers
19129 @section Generating bindings for C++ headers
19131 @noindent
19132 Generating bindings for C++ headers is done using the same options, always
19133 with the @command{g++} compiler.
19135 In this mode, C++ classes will be mapped to Ada tagged types, constructors
19136 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
19137 multiple inheritance of abstract classes will be mapped to Ada interfaces
19138 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
19139 information on interfacing to C++).
19141 For example, given the following C++ header file:
19143 @smallexample
19144 @group
19145 @cartouche
19146 class Carnivore @{
19147 public:
19148    virtual int Number_Of_Teeth () = 0;
19151 class Domestic @{
19152 public:
19153    virtual void Set_Owner (char* Name) = 0;
19156 class Animal @{
19157 public:
19158   int Age_Count;
19159   virtual void Set_Age (int New_Age);
19162 class Dog : Animal, Carnivore, Domestic @{
19163  public:
19164   int  Tooth_Count;
19165   char *Owner;
19167   virtual int  Number_Of_Teeth ();
19168   virtual void Set_Owner (char* Name);
19170   Dog();
19172 @end cartouche
19173 @end group
19174 @end smallexample
19176 The corresponding Ada code is generated:
19178 @smallexample @c ada
19179 @group
19180 @cartouche
19181   package Class_Carnivore is
19182     type Carnivore is limited interface;
19183     pragma Import (CPP, Carnivore);
19185     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
19186   end;
19187   use Class_Carnivore;
19189   package Class_Domestic is
19190     type Domestic is limited interface;
19191     pragma Import (CPP, Domestic);
19193     procedure Set_Owner
19194       (this : access Domestic;
19195        Name : Interfaces.C.Strings.chars_ptr) is abstract;
19196   end;
19197   use Class_Domestic;
19199   package Class_Animal is
19200     type Animal is tagged limited record
19201       Age_Count : aliased int;
19202     end record;
19203     pragma Import (CPP, Animal);
19205     procedure Set_Age (this : access Animal; New_Age : int);
19206     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
19207   end;
19208   use Class_Animal;
19210   package Class_Dog is
19211     type Dog is new Animal and Carnivore and Domestic with record
19212       Tooth_Count : aliased int;
19213       Owner : Interfaces.C.Strings.chars_ptr;
19214     end record;
19215     pragma Import (CPP, Dog);
19217     function Number_Of_Teeth (this : access Dog) return int;
19218     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
19220     procedure Set_Owner
19221       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
19222     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
19224     function New_Dog return Dog;
19225     pragma CPP_Constructor (New_Dog);
19226     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
19227   end;
19228   use Class_Dog;
19229 @end cartouche
19230 @end group
19231 @end smallexample
19233 @node Switches
19234 @section Switches
19236 @table @option
19237 @item -fdump-ada-spec
19238 @cindex @option{-fdump-ada-spec} (@command{gcc})
19239 Generate Ada spec files for the given header files transitively (including
19240 all header files that these headers depend upon).
19242 @item -fdump-ada-spec-slim
19243 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
19244 Generate Ada spec files for the header files specified on the command line
19245 only.
19247 @item -fada-spec-parent=@var{unit}
19248 @cindex -fada-spec-parent (@command{gcc})
19249 Specifies that all files generated by @option{-fdump-ada-spec*} are
19250 to be child units of the specified parent unit.
19252 @item -C
19253 @cindex @option{-C} (@command{gcc})
19254 Extract comments from headers and generate Ada comments in the Ada spec files.
19255 @end table
19257 @node Other Utility Programs
19258 @chapter Other Utility Programs
19260 @noindent
19261 This chapter discusses some other utility programs available in the Ada
19262 environment.
19264 @menu
19265 * Using Other Utility Programs with GNAT::
19266 * The External Symbol Naming Scheme of GNAT::
19267 * Converting Ada Files to html with gnathtml::
19268 * Installing gnathtml::
19269 @ifset vms
19270 * LSE::
19271 * Profiling::
19272 @end ifset
19273 @end menu
19275 @node Using Other Utility Programs with GNAT
19276 @section Using Other Utility Programs with GNAT
19278 @noindent
19279 The object files generated by GNAT are in standard system format and in
19280 particular the debugging information uses this format. This means
19281 programs generated by GNAT can be used with existing utilities that
19282 depend on these formats.
19284 @ifclear vms
19285 In general, any utility program that works with C will also often work with
19286 Ada programs generated by GNAT. This includes software utilities such as
19287 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19288 as Purify.
19289 @end ifclear
19291 @node The External Symbol Naming Scheme of GNAT
19292 @section The External Symbol Naming Scheme of GNAT
19294 @noindent
19295 In order to interpret the output from GNAT, when using tools that are
19296 originally intended for use with other languages, it is useful to
19297 understand the conventions used to generate link names from the Ada
19298 entity names.
19300 All link names are in all lowercase letters. With the exception of library
19301 procedure names, the mechanism used is simply to use the full expanded
19302 Ada name with dots replaced by double underscores. For example, suppose
19303 we have the following package spec:
19305 @smallexample @c ada
19306 @group
19307 @cartouche
19308 package QRS is
19309    MN : Integer;
19310 end QRS;
19311 @end cartouche
19312 @end group
19313 @end smallexample
19315 @noindent
19316 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19317 the corresponding link name is @code{qrs__mn}.
19318 @findex Export
19319 Of course if a @code{pragma Export} is used this may be overridden:
19321 @smallexample @c ada
19322 @group
19323 @cartouche
19324 package Exports is
19325    Var1 : Integer;
19326    pragma Export (Var1, C, External_Name => "var1_name");
19327    Var2 : Integer;
19328    pragma Export (Var2, C, Link_Name => "var2_link_name");
19329 end Exports;
19330 @end cartouche
19331 @end group
19332 @end smallexample
19334 @noindent
19335 In this case, the link name for @var{Var1} is whatever link name the
19336 C compiler would assign for the C function @var{var1_name}. This typically
19337 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19338 system conventions, but other possibilities exist. The link name for
19339 @var{Var2} is @var{var2_link_name}, and this is not operating system
19340 dependent.
19342 @findex _main
19343 One exception occurs for library level procedures. A potential ambiguity
19344 arises between the required name @code{_main} for the C main program,
19345 and the name we would otherwise assign to an Ada library level procedure
19346 called @code{Main} (which might well not be the main program).
19348 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19349 names. So if we have a library level procedure such as
19351 @smallexample @c ada
19352 @group
19353 @cartouche
19354 procedure Hello (S : String);
19355 @end cartouche
19356 @end group
19357 @end smallexample
19359 @noindent
19360 the external name of this procedure will be @var{_ada_hello}.
19363 @node Converting Ada Files to html with gnathtml
19364 @section Converting Ada Files to HTML with @code{gnathtml}
19366 @noindent
19367 This @code{Perl} script allows Ada source files to be browsed using
19368 standard Web browsers. For installation procedure, see the section
19369 @xref{Installing gnathtml}.
19371 Ada reserved keywords are highlighted in a bold font and Ada comments in
19372 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19373 switch to suppress the generation of cross-referencing information, user
19374 defined variables and types will appear in a different color; you will
19375 be able to click on any identifier and go to its declaration.
19377 The command line is as follow:
19378 @smallexample
19379 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
19380 @c Expanding @ovar macro inline (explanation in macro def comments)
19381 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
19382 @end smallexample
19384 @noindent
19385 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19386 an html file for every ada file, and a global file called @file{index.htm}.
19387 This file is an index of every identifier defined in the files.
19389 The available ^switches^options^ are the following ones:
19391 @table @option
19392 @item -83
19393 @cindex @option{-83} (@code{gnathtml})
19394 Only the Ada 83 subset of keywords will be highlighted.
19396 @item -cc @var{color}
19397 @cindex @option{-cc} (@code{gnathtml})
19398 This option allows you to change the color used for comments. The default
19399 value is green. The color argument can be any name accepted by html.
19401 @item -d
19402 @cindex @option{-d} (@code{gnathtml})
19403 If the Ada files depend on some other files (for instance through
19404 @code{with} clauses, the latter files will also be converted to html.
19405 Only the files in the user project will be converted to html, not the files
19406 in the run-time library itself.
19408 @item -D
19409 @cindex @option{-D} (@code{gnathtml})
19410 This command is the same as @option{-d} above, but @command{gnathtml} will
19411 also look for files in the run-time library, and generate html files for them.
19413 @item -ext @var{extension}
19414 @cindex @option{-ext} (@code{gnathtml})
19415 This option allows you to change the extension of the generated HTML files.
19416 If you do not specify an extension, it will default to @file{htm}.
19418 @item -f
19419 @cindex @option{-f} (@code{gnathtml})
19420 By default, gnathtml will generate html links only for global entities
19421 ('with'ed units, global variables and types,@dots{}).  If you specify
19422 @option{-f} on the command line, then links will be generated for local
19423 entities too.
19425 @item -l @var{number}
19426 @cindex @option{-l} (@code{gnathtml})
19427 If this ^switch^option^ is provided and @var{number} is not 0, then
19428 @code{gnathtml} will number the html files every @var{number} line.
19430 @item -I @var{dir}
19431 @cindex @option{-I} (@code{gnathtml})
19432 Specify a directory to search for library files (@file{.ALI} files) and
19433 source files. You can provide several -I switches on the command line,
19434 and the directories will be parsed in the order of the command line.
19436 @item -o @var{dir}
19437 @cindex @option{-o} (@code{gnathtml})
19438 Specify the output directory for html files. By default, gnathtml will
19439 saved the generated html files in a subdirectory named @file{html/}.
19441 @item -p @var{file}
19442 @cindex @option{-p} (@code{gnathtml})
19443 If you are using Emacs and the most recent Emacs Ada mode, which provides
19444 a full Integrated Development Environment for compiling, checking,
19445 running and debugging applications, you may use @file{.gpr} files
19446 to give the directories where Emacs can find sources and object files.
19448 Using this ^switch^option^, you can tell gnathtml to use these files.
19449 This allows you to get an html version of your application, even if it
19450 is spread over multiple directories.
19452 @item -sc @var{color}
19453 @cindex @option{-sc} (@code{gnathtml})
19454 This ^switch^option^ allows you to change the color used for symbol
19455 definitions.
19456 The default value is red. The color argument can be any name accepted by html.
19458 @item -t @var{file}
19459 @cindex @option{-t} (@code{gnathtml})
19460 This ^switch^option^ provides the name of a file. This file contains a list of
19461 file names to be converted, and the effect is exactly as though they had
19462 appeared explicitly on the command line. This
19463 is the recommended way to work around the command line length limit on some
19464 systems.
19466 @end table
19468 @node Installing gnathtml
19469 @section Installing @code{gnathtml}
19471 @noindent
19472 @code{Perl} needs to be installed on your machine to run this script.
19473 @code{Perl} is freely available for almost every architecture and
19474 Operating System via the Internet.
19476 On Unix systems, you  may want to modify  the  first line of  the script
19477 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
19478 is. The syntax of this line is:
19479 @smallexample
19480 #!full_path_name_to_perl
19481 @end smallexample
19483 @noindent
19484 Alternatively, you may run the script using the following command line:
19486 @smallexample
19487 @c $ perl gnathtml.pl @ovar{switches} @var{files}
19488 @c Expanding @ovar macro inline (explanation in macro def comments)
19489 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
19490 @end smallexample
19492 @ifset vms
19493 @node LSE
19494 @section LSE
19495 @findex LSE
19497 @noindent
19498 The GNAT distribution provides an Ada 95 template for the HP Language
19499 Sensitive Editor (LSE), a component of DECset. In order to
19500 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19502 @node Profiling
19503 @section Profiling
19504 @findex PCA
19506 @noindent
19507 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19508 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19509 the collection phase with the /DEBUG qualifier.
19511 @smallexample
19512 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19513 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19514 $ RUN/DEBUG <PROGRAM_NAME>
19515 @end smallexample
19516 @noindent
19517 @end ifset
19519 @ifclear vms
19520 @c ******************************
19521 @node Code Coverage and Profiling
19522 @chapter Code Coverage and Profiling
19523 @cindex Code Coverage
19524 @cindex Profiling
19526 @noindent
19527 This chapter describes how to use @code{gcov} - coverage testing tool - and
19528 @code{gprof} - profiler tool - on your Ada programs.
19530 @menu
19531 * Code Coverage of Ada Programs using gcov::
19532 * Profiling an Ada Program using gprof::
19533 @end menu
19535 @node Code Coverage of Ada Programs using gcov
19536 @section Code Coverage of Ada Programs using gcov
19537 @cindex gcov
19538 @cindex -fprofile-arcs
19539 @cindex -ftest-coverage
19540 @cindex -coverage
19541 @cindex Code Coverage
19543 @noindent
19544 @code{gcov} is a test coverage program: it analyzes the execution of a given
19545 program on selected tests, to help you determine the portions of the program
19546 that are still untested.
19548 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
19549 User's Guide. You can refer to this documentation for a more complete
19550 description.
19552 This chapter provides a quick startup guide, and
19553 details some Gnat-specific features.
19555 @menu
19556 * Quick startup guide::
19557 * Gnat specifics::
19558 @end menu
19560 @node Quick startup guide
19561 @subsection Quick startup guide
19563 In order to perform coverage analysis of a program using @code{gcov}, 3
19564 steps are needed:
19566 @itemize @bullet
19567 @item
19568 Code instrumentation during the compilation process
19569 @item
19570 Execution of the instrumented program
19571 @item
19572 Execution of the @code{gcov} tool to generate the result.
19573 @end itemize
19575 The code instrumentation needed by gcov is created at the object level:
19576 The source code is not modified in any way, because the instrumentation code is
19577 inserted by gcc during the compilation process. To compile your code with code
19578 coverage activated, you need to recompile your whole project using the
19579 switches
19580 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19581 @code{-fprofile-arcs}.
19583 @smallexample
19584 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19585    -largs -fprofile-arcs
19586 @end smallexample
19588 This compilation process will create @file{.gcno} files together with
19589 the usual object files.
19591 Once the program is compiled with coverage instrumentation, you can
19592 run it as many times as needed - on portions of a test suite for
19593 example. The first execution will produce @file{.gcda} files at the
19594 same location as the @file{.gcno} files.  The following executions
19595 will update those files, so that a cumulative result of the covered
19596 portions of the program is generated.
19598 Finally, you need to call the @code{gcov} tool. The different options of
19599 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
19601 This will create annotated source files with a @file{.gcov} extension:
19602 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
19604 @node Gnat specifics
19605 @subsection Gnat specifics
19607 Because Ada semantics, portions of the source code may be shared among
19608 several object files. This is the case for example when generics are
19609 involved, when inlining is active  or when declarations generate  initialisation
19610 calls. In order to take
19611 into account this shared code, you need to call @code{gcov} on all
19612 source files of the tested program at once.
19614 The list of source files might exceed the system's maximum command line
19615 length. In order to bypass this limitation, a new mechanism has been
19616 implemented in @code{gcov}: you can now list all your project's files into a
19617 text file, and provide this file to gcov as a parameter,  preceded by a @@
19618 (e.g. @samp{gcov @@mysrclist.txt}).
19620 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
19621 not supported as there can be unresolved symbols during the final link.
19623 @node Profiling an Ada Program using gprof
19624 @section Profiling an Ada Program using gprof
19625 @cindex gprof
19626 @cindex -pg
19627 @cindex Profiling
19629 @noindent
19630 This section is not meant to be an exhaustive documentation of @code{gprof}.
19631 Full documentation for it can be found in the GNU Profiler User's Guide
19632 documentation that is part of this GNAT distribution.
19634 Profiling a program helps determine the parts of a program that are executed
19635 most often, and are therefore the most time-consuming.
19637 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19638 better handle Ada programs and multitasking.
19639 It is currently supported on the following platforms
19640 @itemize @bullet
19641 @item
19642 linux x86/x86_64
19643 @item
19644 solaris sparc/sparc64/x86
19645 @item
19646 windows x86
19647 @end itemize
19649 @noindent
19650 In order to profile a program using @code{gprof}, 3 steps are needed:
19652 @itemize @bullet
19653 @item
19654 Code instrumentation, requiring a full recompilation of the project with the
19655 proper switches.
19656 @item
19657 Execution of the program under the analysis conditions, i.e. with the desired
19658 input.
19659 @item
19660 Analysis of the results using the @code{gprof} tool.
19661 @end itemize
19663 @noindent
19664 The following sections detail the different steps, and indicate how
19665 to interpret the results:
19666 @menu
19667 * Compilation for profiling::
19668 * Program execution::
19669 * Running gprof::
19670 * Interpretation of profiling results::
19671 @end menu
19673 @node Compilation for profiling
19674 @subsection Compilation for profiling
19675 @cindex -pg
19676 @cindex Profiling
19678 In order to profile a program the first step is to tell the compiler
19679 to generate the necessary profiling information. The compiler switch to be used
19680 is @code{-pg}, which must be added to other compilation switches. This
19681 switch needs to be specified both during compilation and link stages, and can
19682 be specified once when using gnatmake:
19684 @smallexample
19685 gnatmake -f -pg -P my_project
19686 @end smallexample
19688 @noindent
19689 Note that only the objects that were compiled with the @samp{-pg} switch will
19690 be profiled; if you need to profile your whole project, use the @samp{-f}
19691 gnatmake switch to force full recompilation.
19693 @node Program execution
19694 @subsection Program execution
19696 @noindent
19697 Once the program has been compiled for profiling, you can run it as usual.
19699 The only constraint imposed by profiling is that the program must terminate
19700 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19701 properly analyzed.
19703 Once the program completes execution, a data file called @file{gmon.out} is
19704 generated in the directory where the program was launched from. If this file
19705 already exists, it will be overwritten.
19707 @node Running gprof
19708 @subsection Running gprof
19710 @noindent
19711 The @code{gprof} tool is called as follow:
19713 @smallexample
19714 gprof my_prog gmon.out
19715 @end smallexample
19717 @noindent
19718 or simpler:
19720 @smallexample
19721 gprof my_prog
19722 @end smallexample
19724 @noindent
19725 The complete form of the gprof command line is the following:
19727 @smallexample
19728 gprof [^switches^options^] [executable [data-file]]
19729 @end smallexample
19731 @noindent
19732 @code{gprof} supports numerous ^switch^options^. The order of these
19733 ^switch^options^ does not matter. The full list of options can be found in
19734 the GNU Profiler User's Guide documentation that comes with this documentation.
19736 The following is the subset of those switches that is most relevant:
19738 @table @option
19740 @item --demangle[=@var{style}]
19741 @itemx --no-demangle
19742 @cindex @option{--demangle} (@code{gprof})
19743 These options control whether symbol names should be demangled when
19744 printing output.  The default is to demangle C++ symbols.  The
19745 @code{--no-demangle} option may be used to turn off demangling. Different
19746 compilers have different mangling styles.  The optional demangling style
19747 argument can be used to choose an appropriate demangling style for your
19748 compiler, in particular Ada symbols generated by GNAT can be demangled using
19749 @code{--demangle=gnat}.
19751 @item -e @var{function_name}
19752 @cindex @option{-e} (@code{gprof})
19753 The @samp{-e @var{function}} option tells @code{gprof} not to print
19754 information about the function @var{function_name} (and its
19755 children@dots{}) in the call graph.  The function will still be listed
19756 as a child of any functions that call it, but its index number will be
19757 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
19758 given; only one @var{function_name} may be indicated with each @samp{-e}
19759 option.
19761 @item -E @var{function_name}
19762 @cindex @option{-E} (@code{gprof})
19763 The @code{-E @var{function}} option works like the @code{-e} option, but
19764 execution time spent in the function (and children who were not called from
19765 anywhere else), will not be used to compute the percentages-of-time for
19766 the call graph.  More than one @samp{-E} option may be given; only one
19767 @var{function_name} may be indicated with each @samp{-E} option.
19769 @item -f @var{function_name}
19770 @cindex @option{-f} (@code{gprof})
19771 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19772 call graph to the function @var{function_name} and its children (and
19773 their children@dots{}).  More than one @samp{-f} option may be given;
19774 only one @var{function_name} may be indicated with each @samp{-f}
19775 option.
19777 @item -F @var{function_name}
19778 @cindex @option{-F} (@code{gprof})
19779 The @samp{-F @var{function}} option works like the @code{-f} option, but
19780 only time spent in the function and its children (and their
19781 children@dots{}) will be used to determine total-time and
19782 percentages-of-time for the call graph.  More than one @samp{-F} option
19783 may be given; only one @var{function_name} may be indicated with each
19784 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
19786 @end table
19788 @node Interpretation of profiling results
19789 @subsection Interpretation of profiling results
19791 @noindent
19793 The results of the profiling analysis are represented by two arrays: the
19794 'flat profile' and the 'call graph'. Full documentation of those outputs
19795 can be found in the GNU Profiler User's Guide.
19797 The flat profile shows the time spent in each function of the program, and how
19798 many time it has been called. This allows you to locate easily the most
19799 time-consuming functions.
19801 The call graph shows, for each subprogram, the subprograms that call it,
19802 and the subprograms that it calls. It also provides an estimate of the time
19803 spent in each of those callers/called subprograms.
19804 @end ifclear
19806 @c ******************************
19807 @node Running and Debugging Ada Programs
19808 @chapter Running and Debugging Ada Programs
19809 @cindex Debugging
19811 @noindent
19812 This chapter discusses how to debug Ada programs.
19813 @ifset vms
19814 It applies to GNAT on the Alpha OpenVMS platform;
19815 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19816 since HP has implemented Ada support in the OpenVMS debugger on I64.
19817 @end ifset
19819 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19821 @enumerate
19822 @item
19823 The illegality may be a violation of the static semantics of Ada. In
19824 that case GNAT diagnoses the constructs in the program that are illegal.
19825 It is then a straightforward matter for the user to modify those parts of
19826 the program.
19828 @item
19829 The illegality may be a violation of the dynamic semantics of Ada. In
19830 that case the program compiles and executes, but may generate incorrect
19831 results, or may terminate abnormally with some exception.
19833 @item
19834 When presented with a program that contains convoluted errors, GNAT
19835 itself may terminate abnormally without providing full diagnostics on
19836 the incorrect user program.
19837 @end enumerate
19839 @menu
19840 * The GNAT Debugger GDB::
19841 * Running GDB::
19842 * Introduction to GDB Commands::
19843 * Using Ada Expressions::
19844 * Calling User-Defined Subprograms::
19845 * Using the Next Command in a Function::
19846 * Ada Exceptions::
19847 * Ada Tasks::
19848 * Debugging Generic Units::
19849 * Remote Debugging using gdbserver::
19850 * GNAT Abnormal Termination or Failure to Terminate::
19851 * Naming Conventions for GNAT Source Files::
19852 * Getting Internal Debugging Information::
19853 * Stack Traceback::
19854 @end menu
19856 @cindex Debugger
19857 @findex gdb
19859 @node The GNAT Debugger GDB
19860 @section The GNAT Debugger GDB
19862 @noindent
19863 @code{GDB} is a general purpose, platform-independent debugger that
19864 can be used to debug mixed-language programs compiled with @command{gcc},
19865 and in particular is capable of debugging Ada programs compiled with
19866 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19867 complex Ada data structures.
19869 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19870 @ifset vms
19871 located in the GNU:[DOCS] directory,
19872 @end ifset
19873 for full details on the usage of @code{GDB}, including a section on
19874 its usage on programs. This manual should be consulted for full
19875 details. The section that follows is a brief introduction to the
19876 philosophy and use of @code{GDB}.
19878 When GNAT programs are compiled, the compiler optionally writes debugging
19879 information into the generated object file, including information on
19880 line numbers, and on declared types and variables. This information is
19881 separate from the generated code. It makes the object files considerably
19882 larger, but it does not add to the size of the actual executable that
19883 will be loaded into memory, and has no impact on run-time performance. The
19884 generation of debug information is triggered by the use of the
19885 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19886 used to carry out the compilations. It is important to emphasize that
19887 the use of these options does not change the generated code.
19889 The debugging information is written in standard system formats that
19890 are used by many tools, including debuggers and profilers. The format
19891 of the information is typically designed to describe C types and
19892 semantics, but GNAT implements a translation scheme which allows full
19893 details about Ada types and variables to be encoded into these
19894 standard C formats. Details of this encoding scheme may be found in
19895 the file exp_dbug.ads in the GNAT source distribution. However, the
19896 details of this encoding are, in general, of no interest to a user,
19897 since @code{GDB} automatically performs the necessary decoding.
19899 When a program is bound and linked, the debugging information is
19900 collected from the object files, and stored in the executable image of
19901 the program. Again, this process significantly increases the size of
19902 the generated executable file, but it does not increase the size of
19903 the executable program itself. Furthermore, if this program is run in
19904 the normal manner, it runs exactly as if the debug information were
19905 not present, and takes no more actual memory.
19907 However, if the program is run under control of @code{GDB}, the
19908 debugger is activated.  The image of the program is loaded, at which
19909 point it is ready to run.  If a run command is given, then the program
19910 will run exactly as it would have if @code{GDB} were not present. This
19911 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19912 entirely non-intrusive until a breakpoint is encountered.  If no
19913 breakpoint is ever hit, the program will run exactly as it would if no
19914 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19915 the debugging information and can respond to user commands to inspect
19916 variables, and more generally to report on the state of execution.
19918 @c **************
19919 @node Running GDB
19920 @section Running GDB
19922 @noindent
19923 This section describes how to initiate the debugger.
19924 @c The above sentence is really just filler, but it was otherwise
19925 @c clumsy to get the first paragraph nonindented given the conditional
19926 @c nature of the description
19928 @ifclear vms
19929 The debugger can be launched from a @code{GPS} menu or
19930 directly from the command line. The description below covers the latter use.
19931 All the commands shown can be used in the @code{GPS} debug console window,
19932 but there are usually more GUI-based ways to achieve the same effect.
19933 @end ifclear
19935 The command to run @code{GDB} is
19937 @smallexample
19938 $ ^gdb program^GDB PROGRAM^
19939 @end smallexample
19941 @noindent
19942 where @code{^program^PROGRAM^} is the name of the executable file. This
19943 activates the debugger and results in a prompt for debugger commands.
19944 The simplest command is simply @code{run}, which causes the program to run
19945 exactly as if the debugger were not present. The following section
19946 describes some of the additional commands that can be given to @code{GDB}.
19948 @c *******************************
19949 @node Introduction to GDB Commands
19950 @section Introduction to GDB Commands
19952 @noindent
19953 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19954 Debugging with GDB, gdb, Debugging with GDB},
19955 @ifset vms
19956 located in the GNU:[DOCS] directory,
19957 @end ifset
19958 for extensive documentation on the use
19959 of these commands, together with examples of their use. Furthermore,
19960 the command @command{help} invoked from within GDB activates a simple help
19961 facility which summarizes the available commands and their options.
19962 In this section we summarize a few of the most commonly
19963 used commands to give an idea of what @code{GDB} is about. You should create
19964 a simple program with debugging information and experiment with the use of
19965 these @code{GDB} commands on the program as you read through the
19966 following section.
19968 @table @code
19969 @item set args @var{arguments}
19970 The @var{arguments} list above is a list of arguments to be passed to
19971 the program on a subsequent run command, just as though the arguments
19972 had been entered on a normal invocation of the program. The @code{set args}
19973 command is not needed if the program does not require arguments.
19975 @item run
19976 The @code{run} command causes execution of the program to start from
19977 the beginning. If the program is already running, that is to say if
19978 you are currently positioned at a breakpoint, then a prompt will ask
19979 for confirmation that you want to abandon the current execution and
19980 restart.
19982 @item breakpoint @var{location}
19983 The breakpoint command sets a breakpoint, that is to say a point at which
19984 execution will halt and @code{GDB} will await further
19985 commands. @var{location} is
19986 either a line number within a file, given in the format @code{file:linenumber},
19987 or it is the name of a subprogram. If you request that a breakpoint be set on
19988 a subprogram that is overloaded, a prompt will ask you to specify on which of
19989 those subprograms you want to breakpoint. You can also
19990 specify that all of them should be breakpointed. If the program is run
19991 and execution encounters the breakpoint, then the program
19992 stops and @code{GDB} signals that the breakpoint was encountered by
19993 printing the line of code before which the program is halted.
19995 @item catch exception @var{name}
19996 This command causes the program execution to stop whenever exception
19997 @var{name} is raised.  If @var{name} is omitted, then the execution is
19998 suspended when any exception is raised.
20000 @item print @var{expression}
20001 This will print the value of the given expression. Most simple
20002 Ada expression formats are properly handled by @code{GDB}, so the expression
20003 can contain function calls, variables, operators, and attribute references.
20005 @item continue
20006 Continues execution following a breakpoint, until the next breakpoint or the
20007 termination of the program.
20009 @item step
20010 Executes a single line after a breakpoint. If the next statement
20011 is a subprogram call, execution continues into (the first statement of)
20012 the called subprogram.
20014 @item next
20015 Executes a single line. If this line is a subprogram call, executes and
20016 returns from the call.
20018 @item list
20019 Lists a few lines around the current source location. In practice, it
20020 is usually more convenient to have a separate edit window open with the
20021 relevant source file displayed. Successive applications of this command
20022 print subsequent lines. The command can be given an argument which is a
20023 line number, in which case it displays a few lines around the specified one.
20025 @item backtrace
20026 Displays a backtrace of the call chain. This command is typically
20027 used after a breakpoint has occurred, to examine the sequence of calls that
20028 leads to the current breakpoint. The display includes one line for each
20029 activation record (frame) corresponding to an active subprogram.
20031 @item up
20032 At a breakpoint, @code{GDB} can display the values of variables local
20033 to the current frame. The command @code{up} can be used to
20034 examine the contents of other active frames, by moving the focus up
20035 the stack, that is to say from callee to caller, one frame at a time.
20037 @item down
20038 Moves the focus of @code{GDB} down from the frame currently being
20039 examined to the frame of its callee (the reverse of the previous command),
20041 @item frame @var{n}
20042 Inspect the frame with the given number. The value 0 denotes the frame
20043 of the current breakpoint, that is to say the top of the call stack.
20045 @end table
20047 @noindent
20048 The above list is a very short introduction to the commands that
20049 @code{GDB} provides. Important additional capabilities, including conditional
20050 breakpoints, the ability to execute command sequences on a breakpoint,
20051 the ability to debug at the machine instruction level and many other
20052 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20053 Debugging with GDB}.  Note that most commands can be abbreviated
20054 (for example, c for continue, bt for backtrace).
20056 @node Using Ada Expressions
20057 @section Using Ada Expressions
20058 @cindex Ada expressions
20060 @noindent
20061 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20062 extensions. The philosophy behind the design of this subset is
20064 @itemize @bullet
20065 @item
20066 That @code{GDB} should provide basic literals and access to operations for
20067 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20068 leaving more sophisticated computations to subprograms written into the
20069 program (which therefore may be called from @code{GDB}).
20071 @item
20072 That type safety and strict adherence to Ada language restrictions
20073 are not particularly important to the @code{GDB} user.
20075 @item
20076 That brevity is important to the @code{GDB} user.
20077 @end itemize
20079 @noindent
20080 Thus, for brevity, the debugger acts as if there were
20081 implicit @code{with} and @code{use} clauses in effect for all user-written
20082 packages, thus making it unnecessary to fully qualify most names with
20083 their packages, regardless of context. Where this causes ambiguity,
20084 @code{GDB} asks the user's intent.
20086 For details on the supported Ada syntax, see @ref{Top,, Debugging with
20087 GDB, gdb, Debugging with GDB}.
20089 @node Calling User-Defined Subprograms
20090 @section Calling User-Defined Subprograms
20092 @noindent
20093 An important capability of @code{GDB} is the ability to call user-defined
20094 subprograms while debugging. This is achieved simply by entering
20095 a subprogram call statement in the form:
20097 @smallexample
20098 call subprogram-name (parameters)
20099 @end smallexample
20101 @noindent
20102 The keyword @code{call} can be omitted in the normal case where the
20103 @code{subprogram-name} does not coincide with any of the predefined
20104 @code{GDB} commands.
20106 The effect is to invoke the given subprogram, passing it the
20107 list of parameters that is supplied. The parameters can be expressions and
20108 can include variables from the program being debugged. The
20109 subprogram must be defined
20110 at the library level within your program, and @code{GDB} will call the
20111 subprogram within the environment of your program execution (which
20112 means that the subprogram is free to access or even modify variables
20113 within your program).
20115 The most important use of this facility is in allowing the inclusion of
20116 debugging routines that are tailored to particular data structures
20117 in your program. Such debugging routines can be written to provide a suitably
20118 high-level description of an abstract type, rather than a low-level dump
20119 of its physical layout. After all, the standard
20120 @code{GDB print} command only knows the physical layout of your
20121 types, not their abstract meaning. Debugging routines can provide information
20122 at the desired semantic level and are thus enormously useful.
20124 For example, when debugging GNAT itself, it is crucial to have access to
20125 the contents of the tree nodes used to represent the program internally.
20126 But tree nodes are represented simply by an integer value (which in turn
20127 is an index into a table of nodes).
20128 Using the @code{print} command on a tree node would simply print this integer
20129 value, which is not very useful. But the PN routine (defined in file
20130 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20131 a useful high level representation of the tree node, which includes the
20132 syntactic category of the node, its position in the source, the integers
20133 that denote descendant nodes and parent node, as well as varied
20134 semantic information. To study this example in more detail, you might want to
20135 look at the body of the PN procedure in the stated file.
20137 @node Using the Next Command in a Function
20138 @section Using the Next Command in a Function
20140 @noindent
20141 When you use the @code{next} command in a function, the current source
20142 location will advance to the next statement as usual. A special case
20143 arises in the case of a @code{return} statement.
20145 Part of the code for a return statement is the ``epilog'' of the function.
20146 This is the code that returns to the caller. There is only one copy of
20147 this epilog code, and it is typically associated with the last return
20148 statement in the function if there is more than one return. In some
20149 implementations, this epilog is associated with the first statement
20150 of the function.
20152 The result is that if you use the @code{next} command from a return
20153 statement that is not the last return statement of the function you
20154 may see a strange apparent jump to the last return statement or to
20155 the start of the function. You should simply ignore this odd jump.
20156 The value returned is always that from the first return statement
20157 that was stepped through.
20159 @node Ada Exceptions
20160 @section Stopping when Ada Exceptions are Raised
20161 @cindex Exceptions
20163 @noindent
20164 You can set catchpoints that stop the program execution when your program
20165 raises selected exceptions.
20167 @table @code
20168 @item catch exception
20169 Set a catchpoint that stops execution whenever (any task in the) program
20170 raises any exception.
20172 @item catch exception @var{name}
20173 Set a catchpoint that stops execution whenever (any task in the) program
20174 raises the exception @var{name}.
20176 @item catch exception unhandled
20177 Set a catchpoint that stops executing whenever (any task in the) program
20178 raises an exception for which there is no handler.
20180 @item info exceptions
20181 @itemx info exceptions @var{regexp}
20182 The @code{info exceptions} command permits the user to examine all defined
20183 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20184 argument, prints out only those exceptions whose name matches @var{regexp}.
20185 @end table
20187 @node Ada Tasks
20188 @section Ada Tasks
20189 @cindex Tasks
20191 @noindent
20192 @code{GDB} allows the following task-related commands:
20194 @table @code
20195 @item info tasks
20196 This command shows a list of current Ada tasks, as in the following example:
20198 @smallexample
20199 @iftex
20200 @leftskip=0cm
20201 @end iftex
20202 (gdb) info tasks
20203   ID       TID P-ID   Thread Pri State                 Name
20204    1   8088000   0   807e000  15 Child Activation Wait main_task
20205    2   80a4000   1   80ae000  15 Accept/Select Wait    b
20206    3   809a800   1   80a4800  15 Child Activation Wait a
20207 *  4   80ae800   3   80b8000  15 Running               c
20208 @end smallexample
20210 @noindent
20211 In this listing, the asterisk before the first task indicates it to be the
20212 currently running task. The first column lists the task ID that is used
20213 to refer to tasks in the following commands.
20215 @item break @var{linespec} task @var{taskid}
20216 @itemx break @var{linespec} task @var{taskid} if @dots{}
20217 @cindex Breakpoints and tasks
20218 These commands are like the @code{break @dots{} thread @dots{}}.
20219 @var{linespec} specifies source lines.
20221 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20222 to specify that you only want @code{GDB} to stop the program when a
20223 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20224 numeric task identifiers assigned by @code{GDB}, shown in the first
20225 column of the @samp{info tasks} display.
20227 If you do not specify @samp{task @var{taskid}} when you set a
20228 breakpoint, the breakpoint applies to @emph{all} tasks of your
20229 program.
20231 You can use the @code{task} qualifier on conditional breakpoints as
20232 well; in this case, place @samp{task @var{taskid}} before the
20233 breakpoint condition (before the @code{if}).
20235 @item task @var{taskno}
20236 @cindex Task switching
20238 This command allows to switch to the task referred by @var{taskno}. In
20239 particular, This allows to browse the backtrace of the specified
20240 task. It is advised to switch back to the original task before
20241 continuing execution otherwise the scheduling of the program may be
20242 perturbed.
20243 @end table
20245 @noindent
20246 For more detailed information on the tasking support,
20247 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
20249 @node Debugging Generic Units
20250 @section Debugging Generic Units
20251 @cindex Debugging Generic Units
20252 @cindex Generics
20254 @noindent
20255 GNAT always uses code expansion for generic instantiation. This means that
20256 each time an instantiation occurs, a complete copy of the original code is
20257 made, with appropriate substitutions of formals by actuals.
20259 It is not possible to refer to the original generic entities in
20260 @code{GDB}, but it is always possible to debug a particular instance of
20261 a generic, by using the appropriate expanded names. For example, if we have
20263 @smallexample @c ada
20264 @group
20265 @cartouche
20266 procedure g is
20268    generic package k is
20269       procedure kp (v1 : in out integer);
20270    end k;
20272    package body k is
20273       procedure kp (v1 : in out integer) is
20274       begin
20275          v1 := v1 + 1;
20276       end kp;
20277    end k;
20279    package k1 is new k;
20280    package k2 is new k;
20282    var : integer := 1;
20284 begin
20285    k1.kp (var);
20286    k2.kp (var);
20287    k1.kp (var);
20288    k2.kp (var);
20289 end;
20290 @end cartouche
20291 @end group
20292 @end smallexample
20294 @noindent
20295 Then to break on a call to procedure kp in the k2 instance, simply
20296 use the command:
20298 @smallexample
20299 (gdb) break g.k2.kp
20300 @end smallexample
20302 @noindent
20303 When the breakpoint occurs, you can step through the code of the
20304 instance in the normal manner and examine the values of local variables, as for
20305 other units.
20307 @node Remote Debugging using gdbserver
20308 @section Remote Debugging using gdbserver
20309 @cindex Remote Debugging using gdbserver
20311 @noindent
20312 On platforms where gdbserver is supported, it is possible to use this tool
20313 to debug your application remotely.  This can be useful in situations
20314 where the program needs to be run on a target host that is different
20315 from the host used for development, particularly when the target has
20316 a limited amount of resources (either CPU and/or memory).
20318 To do so, start your program using gdbserver on the target machine.
20319 gdbserver then automatically suspends the execution of your program
20320 at its entry point, waiting for a debugger to connect to it.  The
20321 following commands starts an application and tells gdbserver to
20322 wait for a connection with the debugger on localhost port 4444.
20324 @smallexample
20325 $ gdbserver localhost:4444 program
20326 Process program created; pid = 5685
20327 Listening on port 4444
20328 @end smallexample
20330 Once gdbserver has started listening, we can tell the debugger to establish
20331 a connection with this gdbserver, and then start the same debugging session
20332 as if the program was being debugged on the same host, directly under
20333 the control of GDB.
20335 @smallexample
20336 $ gdb program
20337 (gdb) target remote targethost:4444
20338 Remote debugging using targethost:4444
20339 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
20340 (gdb) b foo.adb:3
20341 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
20342 (gdb) continue
20343 Continuing.
20345 Breakpoint 1, foo () at foo.adb:4
20346 4       end foo;
20347 @end smallexample
20349 It is also possible to use gdbserver to attach to an already running
20350 program, in which case the execution of that program is simply suspended
20351 until the connection between the debugger and gdbserver is established.
20353 For more information on how to use gdbserver, @ref{Top, Server, Using
20354 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
20355 for gdbserver on x86-linux, x86-windows and x86_64-linux.
20357 @node GNAT Abnormal Termination or Failure to Terminate
20358 @section GNAT Abnormal Termination or Failure to Terminate
20359 @cindex GNAT Abnormal Termination or Failure to Terminate
20361 @noindent
20362 When presented with programs that contain serious errors in syntax
20363 or semantics,
20364 GNAT may on rare occasions  experience problems in operation, such
20365 as aborting with a
20366 segmentation fault or illegal memory access, raising an internal
20367 exception, terminating abnormally, or failing to terminate at all.
20368 In such cases, you can activate
20369 various features of GNAT that can help you pinpoint the construct in your
20370 program that is the likely source of the problem.
20372 The following strategies are presented in increasing order of
20373 difficulty, corresponding to your experience in using GNAT and your
20374 familiarity with compiler internals.
20376 @enumerate
20377 @item
20378 Run @command{gcc} with the @option{-gnatf}. This first
20379 switch causes all errors on a given line to be reported. In its absence,
20380 only the first error on a line is displayed.
20382 The @option{-gnatdO} switch causes errors to be displayed as soon as they
20383 are encountered, rather than after compilation is terminated. If GNAT
20384 terminates prematurely or goes into an infinite loop, the last error
20385 message displayed may help to pinpoint the culprit.
20387 @item
20388 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
20389 mode, @command{gcc} produces ongoing information about the progress of the
20390 compilation and provides the name of each procedure as code is
20391 generated. This switch allows you to find which Ada procedure was being
20392 compiled when it encountered a code generation problem.
20394 @item
20395 @cindex @option{-gnatdc} switch
20396 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
20397 switch that does for the front-end what @option{^-v^VERBOSE^} does
20398 for the back end. The system prints the name of each unit,
20399 either a compilation unit or nested unit, as it is being analyzed.
20400 @item
20401 Finally, you can start
20402 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
20403 front-end of GNAT, and can be run independently (normally it is just
20404 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
20405 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
20406 @code{where} command is the first line of attack; the variable
20407 @code{lineno} (seen by @code{print lineno}), used by the second phase of
20408 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
20409 which the execution stopped, and @code{input_file name} indicates the name of
20410 the source file.
20411 @end enumerate
20413 @node Naming Conventions for GNAT Source Files
20414 @section Naming Conventions for GNAT Source Files
20416 @noindent
20417 In order to examine the workings of the GNAT system, the following
20418 brief description of its organization may be helpful:
20420 @itemize @bullet
20421 @item
20422 Files with prefix @file{^sc^SC^} contain the lexical scanner.
20424 @item
20425 All files prefixed with @file{^par^PAR^} are components of the parser. The
20426 numbers correspond to chapters of the Ada Reference Manual. For example,
20427 parsing of select statements can be found in @file{par-ch9.adb}.
20429 @item
20430 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
20431 numbers correspond to chapters of the Ada standard. For example, all
20432 issues involving context clauses can be found in @file{sem_ch10.adb}. In
20433 addition, some features of the language require sufficient special processing
20434 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
20435 dynamic dispatching, etc.
20437 @item
20438 All files prefixed with @file{^exp^EXP^} perform normalization and
20439 expansion of the intermediate representation (abstract syntax tree, or AST).
20440 these files use the same numbering scheme as the parser and semantics files.
20441 For example, the construction of record initialization procedures is done in
20442 @file{exp_ch3.adb}.
20444 @item
20445 The files prefixed with @file{^bind^BIND^} implement the binder, which
20446 verifies the consistency of the compilation, determines an order of
20447 elaboration, and generates the bind file.
20449 @item
20450 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20451 data structures used by the front-end.
20453 @item
20454 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20455 the abstract syntax tree as produced by the parser.
20457 @item
20458 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20459 all entities, computed during semantic analysis.
20461 @item
20462 Library management issues are dealt with in files with prefix
20463 @file{^lib^LIB^}.
20465 @item
20466 @findex Ada
20467 @cindex Annex A
20468 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20469 defined in Annex A.
20471 @item
20472 @findex Interfaces
20473 @cindex Annex B
20474 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20475 defined in Annex B.
20477 @item
20478 @findex System
20479 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20480 both language-defined children and GNAT run-time routines.
20482 @item
20483 @findex GNAT
20484 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
20485 general-purpose packages, fully documented in their specs. All
20486 the other @file{.c} files are modifications of common @command{gcc} files.
20487 @end itemize
20489 @node Getting Internal Debugging Information
20490 @section Getting Internal Debugging Information
20492 @noindent
20493 Most compilers have internal debugging switches and modes. GNAT
20494 does also, except GNAT internal debugging switches and modes are not
20495 secret. A summary and full description of all the compiler and binder
20496 debug flags are in the file @file{debug.adb}. You must obtain the
20497 sources of the compiler to see the full detailed effects of these flags.
20499 The switches that print the source of the program (reconstructed from
20500 the internal tree) are of general interest for user programs, as are the
20501 options to print
20502 the full internal tree, and the entity table (the symbol table
20503 information). The reconstructed source provides a readable version of the
20504 program after the front-end has completed analysis and  expansion,
20505 and is useful when studying the performance of specific constructs.
20506 For example, constraint checks are indicated, complex aggregates
20507 are replaced with loops and assignments, and tasking primitives
20508 are replaced with run-time calls.
20510 @node Stack Traceback
20511 @section Stack Traceback
20512 @cindex traceback
20513 @cindex stack traceback
20514 @cindex stack unwinding
20516 @noindent
20517 Traceback is a mechanism to display the sequence of subprogram calls that
20518 leads to a specified execution point in a program. Often (but not always)
20519 the execution point is an instruction at which an exception has been raised.
20520 This mechanism is also known as @i{stack unwinding} because it obtains
20521 its information by scanning the run-time stack and recovering the activation
20522 records of all active subprograms. Stack unwinding is one of the most
20523 important tools for program debugging.
20525 The first entry stored in traceback corresponds to the deepest calling level,
20526 that is to say the subprogram currently executing the instruction
20527 from which we want to obtain the traceback.
20529 Note that there is no runtime performance penalty when stack traceback
20530 is enabled, and no exception is raised during program execution.
20532 @menu
20533 * Non-Symbolic Traceback::
20534 * Symbolic Traceback::
20535 @end menu
20537 @node Non-Symbolic Traceback
20538 @subsection Non-Symbolic Traceback
20539 @cindex traceback, non-symbolic
20541 @noindent
20542 Note: this feature is not supported on all platforms. See
20543 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20544 platforms.
20546 @menu
20547 * Tracebacks From an Unhandled Exception::
20548 * Tracebacks From Exception Occurrences (non-symbolic)::
20549 * Tracebacks From Anywhere in a Program (non-symbolic)::
20550 @end menu
20552 @node Tracebacks From an Unhandled Exception
20553 @subsubsection Tracebacks From an Unhandled Exception
20555 @noindent
20556 A runtime non-symbolic traceback is a list of addresses of call instructions.
20557 To enable this feature you must use the @option{-E}
20558 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20559 of exception information. You can retrieve this information using the
20560 @code{addr2line} tool.
20562 Here is a simple example:
20564 @smallexample @c ada
20565 @cartouche
20566 procedure STB is
20568    procedure P1 is
20569    begin
20570       raise Constraint_Error;
20571    end P1;
20573    procedure P2 is
20574    begin
20575       P1;
20576    end P2;
20578 begin
20579    P2;
20580 end STB;
20581 @end cartouche
20582 @end smallexample
20584 @smallexample
20585 $ gnatmake stb -bargs -E
20586 $ stb
20588 Execution terminated by unhandled exception
20589 Exception name: CONSTRAINT_ERROR
20590 Message: stb.adb:5
20591 Call stack traceback locations:
20592 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20593 @end smallexample
20595 @noindent
20596 As we see the traceback lists a sequence of addresses for the unhandled
20597 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20598 guess that this exception come from procedure P1. To translate these
20599 addresses into the source lines where the calls appear, the
20600 @code{addr2line} tool, described below, is invaluable. The use of this tool
20601 requires the program to be compiled with debug information.
20603 @smallexample
20604 $ gnatmake -g stb -bargs -E
20605 $ stb
20607 Execution terminated by unhandled exception
20608 Exception name: CONSTRAINT_ERROR
20609 Message: stb.adb:5
20610 Call stack traceback locations:
20611 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20613 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20614    0x4011f1 0x77e892a4
20616 00401373 at d:/stb/stb.adb:5
20617 0040138B at d:/stb/stb.adb:10
20618 0040139C at d:/stb/stb.adb:14
20619 00401335 at d:/stb/b~stb.adb:104
20620 004011C4 at /build/@dots{}/crt1.c:200
20621 004011F1 at /build/@dots{}/crt1.c:222
20622 77E892A4 in ?? at ??:0
20623 @end smallexample
20625 @noindent
20626 The @code{addr2line} tool has several other useful options:
20628 @table @code
20629 @item --functions
20630 to get the function name corresponding to any location
20632 @item --demangle=gnat
20633 to use the gnat decoding mode for the function names. Note that
20634 for binutils version 2.9.x the option is simply @option{--demangle}.
20635 @end table
20637 @smallexample
20638 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20639    0x40139c 0x401335 0x4011c4 0x4011f1
20641 00401373 in stb.p1 at d:/stb/stb.adb:5
20642 0040138B in stb.p2 at d:/stb/stb.adb:10
20643 0040139C in stb at d:/stb/stb.adb:14
20644 00401335 in main at d:/stb/b~stb.adb:104
20645 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
20646 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
20647 @end smallexample
20649 @noindent
20650 From this traceback we can see that the exception was raised in
20651 @file{stb.adb} at line 5, which was reached from a procedure call in
20652 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20653 which contains the call to the main program.
20654 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20655 and the output will vary from platform to platform.
20657 It is also possible to use @code{GDB} with these traceback addresses to debug
20658 the program. For example, we can break at a given code location, as reported
20659 in the stack traceback:
20661 @smallexample
20662 $ gdb -nw stb
20663 @ifclear vms
20664 @noindent
20665 Furthermore, this feature is not implemented inside Windows DLL. Only
20666 the non-symbolic traceback is reported in this case.
20667 @end ifclear
20669 (gdb) break *0x401373
20670 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20671 @end smallexample
20673 @noindent
20674 It is important to note that the stack traceback addresses
20675 do not change when debug information is included. This is particularly useful
20676 because it makes it possible to release software without debug information (to
20677 minimize object size), get a field report that includes a stack traceback
20678 whenever an internal bug occurs, and then be able to retrieve the sequence
20679 of calls with the same program compiled with debug information.
20681 @node Tracebacks From Exception Occurrences (non-symbolic)
20682 @subsubsection Tracebacks From Exception Occurrences
20684 @noindent
20685 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20686 The stack traceback is attached to the exception information string, and can
20687 be retrieved in an exception handler within the Ada program, by means of the
20688 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20690 @smallexample @c ada
20691 with Ada.Text_IO;
20692 with Ada.Exceptions;
20694 procedure STB is
20696    use Ada;
20697    use Ada.Exceptions;
20699    procedure P1 is
20700       K : Positive := 1;
20701    begin
20702       K := K - 1;
20703    exception
20704       when E : others =>
20705          Text_IO.Put_Line (Exception_Information (E));
20706    end P1;
20708    procedure P2 is
20709    begin
20710       P1;
20711    end P2;
20713 begin
20714    P2;
20715 end STB;
20716 @end smallexample
20718 @noindent
20719 This program will output:
20721 @smallexample
20722 $ stb
20724 Exception name: CONSTRAINT_ERROR
20725 Message: stb.adb:12
20726 Call stack traceback locations:
20727 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20728 @end smallexample
20730 @node Tracebacks From Anywhere in a Program (non-symbolic)
20731 @subsubsection Tracebacks From Anywhere in a Program
20733 @noindent
20734 It is also possible to retrieve a stack traceback from anywhere in a
20735 program. For this you need to
20736 use the @code{GNAT.Traceback} API. This package includes a procedure called
20737 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20738 display procedures described below. It is not necessary to use the
20739 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20740 is invoked explicitly.
20742 @noindent
20743 In the following example we compute a traceback at a specific location in
20744 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20745 convert addresses to strings:
20747 @smallexample @c ada
20748 with Ada.Text_IO;
20749 with GNAT.Traceback;
20750 with GNAT.Debug_Utilities;
20752 procedure STB is
20754    use Ada;
20755    use GNAT;
20756    use GNAT.Traceback;
20758    procedure P1 is
20759       TB  : Tracebacks_Array (1 .. 10);
20760       --  We are asking for a maximum of 10 stack frames.
20761       Len : Natural;
20762       --  Len will receive the actual number of stack frames returned.
20763    begin
20764       Call_Chain (TB, Len);
20766       Text_IO.Put ("In STB.P1 : ");
20768       for K in 1 .. Len loop
20769          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20770          Text_IO.Put (' ');
20771       end loop;
20773       Text_IO.New_Line;
20774    end P1;
20776    procedure P2 is
20777    begin
20778       P1;
20779    end P2;
20781 begin
20782    P2;
20783 end STB;
20784 @end smallexample
20786 @smallexample
20787 $ gnatmake -g stb
20788 $ stb
20790 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20791 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20792 @end smallexample
20794 @noindent
20795 You can then get further information by invoking the @code{addr2line}
20796 tool as described earlier (note that the hexadecimal addresses
20797 need to be specified in C format, with a leading ``0x'').
20799 @node Symbolic Traceback
20800 @subsection Symbolic Traceback
20801 @cindex traceback, symbolic
20803 @noindent
20804 A symbolic traceback is a stack traceback in which procedure names are
20805 associated with each code location.
20807 @noindent
20808 Note that this feature is not supported on all platforms. See
20809 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20810 list of currently supported platforms.
20812 @noindent
20813 Note that the symbolic traceback requires that the program be compiled
20814 with debug information. If it is not compiled with debug information
20815 only the non-symbolic information will be valid.
20817 @menu
20818 * Tracebacks From Exception Occurrences (symbolic)::
20819 * Tracebacks From Anywhere in a Program (symbolic)::
20820 @end menu
20822 @node Tracebacks From Exception Occurrences (symbolic)
20823 @subsubsection Tracebacks From Exception Occurrences
20825 @smallexample @c ada
20826 with Ada.Text_IO;
20827 with GNAT.Traceback.Symbolic;
20829 procedure STB is
20831    procedure P1 is
20832    begin
20833       raise Constraint_Error;
20834    end P1;
20836    procedure P2 is
20837    begin
20838       P1;
20839    end P2;
20841    procedure P3 is
20842    begin
20843       P2;
20844    end P3;
20846 begin
20847    P3;
20848 exception
20849    when E : others =>
20850       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20851 end STB;
20852 @end smallexample
20854 @smallexample
20855 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20856 $ stb
20858 0040149F in stb.p1 at stb.adb:8
20859 004014B7 in stb.p2 at stb.adb:13
20860 004014CF in stb.p3 at stb.adb:18
20861 004015DD in ada.stb at stb.adb:22
20862 00401461 in main at b~stb.adb:168
20863 004011C4 in __mingw_CRTStartup at crt1.c:200
20864 004011F1 in mainCRTStartup at crt1.c:222
20865 77E892A4 in ?? at ??:0
20866 @end smallexample
20868 @noindent
20869 In the above example the ``.\'' syntax in the @command{gnatmake} command
20870 is currently required by @command{addr2line} for files that are in
20871 the current working directory.
20872 Moreover, the exact sequence of linker options may vary from platform
20873 to platform.
20874 The above @option{-largs} section is for Windows platforms. By contrast,
20875 under Unix there is no need for the @option{-largs} section.
20876 Differences across platforms are due to details of linker implementation.
20878 @node Tracebacks From Anywhere in a Program (symbolic)
20879 @subsubsection Tracebacks From Anywhere in a Program
20881 @noindent
20882 It is possible to get a symbolic stack traceback
20883 from anywhere in a program, just as for non-symbolic tracebacks.
20884 The first step is to obtain a non-symbolic
20885 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20886 information. Here is an example:
20888 @smallexample @c ada
20889 with Ada.Text_IO;
20890 with GNAT.Traceback;
20891 with GNAT.Traceback.Symbolic;
20893 procedure STB is
20895    use Ada;
20896    use GNAT.Traceback;
20897    use GNAT.Traceback.Symbolic;
20899    procedure P1 is
20900       TB  : Tracebacks_Array (1 .. 10);
20901       --  We are asking for a maximum of 10 stack frames.
20902       Len : Natural;
20903       --  Len will receive the actual number of stack frames returned.
20904    begin
20905       Call_Chain (TB, Len);
20906       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20907    end P1;
20909    procedure P2 is
20910    begin
20911       P1;
20912    end P2;
20914 begin
20915    P2;
20916 end STB;
20917 @end smallexample
20919 @c ******************************
20920 @ifset vms
20921 @node Compatibility with HP Ada
20922 @chapter Compatibility with HP Ada
20923 @cindex Compatibility
20925 @noindent
20926 @cindex DEC Ada
20927 @cindex HP Ada
20928 @cindex Compatibility between GNAT and HP Ada
20929 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20930 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20931 GNAT is highly compatible
20932 with HP Ada, and it should generally be straightforward to port code
20933 from the HP Ada environment to GNAT. However, there are a few language
20934 and implementation differences of which the user must be aware. These
20935 differences are discussed in this chapter. In
20936 addition, the operating environment and command structure for the
20937 compiler are different, and these differences are also discussed.
20939 For further details on these and other compatibility issues,
20940 see Appendix E of the HP publication
20941 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20943 Except where otherwise indicated, the description of GNAT for OpenVMS
20944 applies to both the Alpha and I64 platforms.
20946 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20947 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20949 The discussion in this chapter addresses specifically the implementation
20950 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20951 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20952 GNAT always follows the Alpha implementation.
20954 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20955 attributes are recognized, although only a subset of them can sensibly
20956 be implemented.  The description of pragmas in
20957 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20958 indicates whether or not they are applicable to non-VMS systems.
20960 @menu
20961 * Ada Language Compatibility::
20962 * Differences in the Definition of Package System::
20963 * Language-Related Features::
20964 * The Package STANDARD::
20965 * The Package SYSTEM::
20966 * Tasking and Task-Related Features::
20967 * Pragmas and Pragma-Related Features::
20968 * Library of Predefined Units::
20969 * Bindings::
20970 * Main Program Definition::
20971 * Implementation-Defined Attributes::
20972 * Compiler and Run-Time Interfacing::
20973 * Program Compilation and Library Management::
20974 * Input-Output::
20975 * Implementation Limits::
20976 * Tools and Utilities::
20977 @end menu
20979 @node Ada Language Compatibility
20980 @section Ada Language Compatibility
20982 @noindent
20983 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20984 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20985 with Ada 83, and therefore Ada 83 programs will compile
20986 and run under GNAT with
20987 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20988 provides details on specific incompatibilities.
20990 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20991 as well as the pragma @code{ADA_83}, to force the compiler to
20992 operate in Ada 83 mode. This mode does not guarantee complete
20993 conformance to Ada 83, but in practice is sufficient to
20994 eliminate most sources of incompatibilities.
20995 In particular, it eliminates the recognition of the
20996 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20997 in Ada 83 programs is legal, and handles the cases of packages
20998 with optional bodies, and generics that instantiate unconstrained
20999 types without the use of @code{(<>)}.
21001 @node Differences in the Definition of Package System
21002 @section Differences in the Definition of Package @code{System}
21004 @noindent
21005 An Ada compiler is allowed to add
21006 implementation-dependent declarations to package @code{System}.
21007 In normal mode,
21008 GNAT does not take advantage of this permission, and the version of
21009 @code{System} provided by GNAT exactly matches that defined in the Ada
21010 Reference Manual.
21012 However, HP Ada adds an extensive set of declarations to package
21013 @code{System},
21014 as fully documented in the HP Ada manuals. To minimize changes required
21015 for programs that make use of these extensions, GNAT provides the pragma
21016 @code{Extend_System} for extending the definition of package System. By using:
21017 @cindex pragma @code{Extend_System}
21018 @cindex @code{Extend_System} pragma
21020 @smallexample @c ada
21021 @group
21022 @cartouche
21023 pragma Extend_System (Aux_DEC);
21024 @end cartouche
21025 @end group
21026 @end smallexample
21028 @noindent
21029 the set of definitions in @code{System} is extended to include those in
21030 package @code{System.Aux_DEC}.
21031 @cindex @code{System.Aux_DEC} package
21032 @cindex @code{Aux_DEC} package (child of @code{System})
21033 These definitions are incorporated directly into package @code{System},
21034 as though they had been declared there. For a
21035 list of the declarations added, see the spec of this package,
21036 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21037 @cindex @file{s-auxdec.ads} file
21038 The pragma @code{Extend_System} is a configuration pragma, which means that
21039 it can be placed in the file @file{gnat.adc}, so that it will automatically
21040 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21041 for further details.
21043 An alternative approach that avoids the use of the non-standard
21044 @code{Extend_System} pragma is to add a context clause to the unit that
21045 references these facilities:
21047 @smallexample @c ada
21048 @cartouche
21049 with System.Aux_DEC;
21050 use  System.Aux_DEC;
21051 @end cartouche
21052 @end smallexample
21054 @noindent
21055 The effect is not quite semantically identical to incorporating
21056 the declarations directly into package @code{System},
21057 but most programs will not notice a difference
21058 unless they use prefix notation (e.g.@: @code{System.Integer_8})
21059 to reference the entities directly in package @code{System}.
21060 For units containing such references,
21061 the prefixes must either be removed, or the pragma @code{Extend_System}
21062 must be used.
21064 @node Language-Related Features
21065 @section Language-Related Features
21067 @noindent
21068 The following sections highlight differences in types,
21069 representations of types, operations, alignment, and
21070 related topics.
21072 @menu
21073 * Integer Types and Representations::
21074 * Floating-Point Types and Representations::
21075 * Pragmas Float_Representation and Long_Float::
21076 * Fixed-Point Types and Representations::
21077 * Record and Array Component Alignment::
21078 * Address Clauses::
21079 * Other Representation Clauses::
21080 @end menu
21082 @node Integer Types and Representations
21083 @subsection Integer Types and Representations
21085 @noindent
21086 The set of predefined integer types is identical in HP Ada and GNAT.
21087 Furthermore the representation of these integer types is also identical,
21088 including the capability of size clauses forcing biased representation.
21090 In addition,
21091 HP Ada for OpenVMS Alpha systems has defined the
21092 following additional integer types in package @code{System}:
21094 @itemize @bullet
21096 @item
21097 @code{INTEGER_8}
21099 @item
21100 @code{INTEGER_16}
21102 @item
21103 @code{INTEGER_32}
21105 @item
21106 @code{INTEGER_64}
21108 @item
21109 @code{LARGEST_INTEGER}
21110 @end itemize
21112 @noindent
21113 In GNAT, the first four of these types may be obtained from the
21114 standard Ada package @code{Interfaces}.
21115 Alternatively, by use of the pragma @code{Extend_System}, identical
21116 declarations can be referenced directly in package @code{System}.
21117 On both GNAT and HP Ada, the maximum integer size is 64 bits.
21119 @node Floating-Point Types and Representations
21120 @subsection Floating-Point Types and Representations
21121 @cindex Floating-Point types
21123 @noindent
21124 The set of predefined floating-point types is identical in HP Ada and GNAT.
21125 Furthermore the representation of these floating-point
21126 types is also identical. One important difference is that the default
21127 representation for HP Ada is @code{VAX_Float}, but the default representation
21128 for GNAT is IEEE.
21130 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
21131 pragma @code{Float_Representation} as described in the HP Ada
21132 documentation.
21133 For example, the declarations:
21135 @smallexample @c ada
21136 @cartouche
21137 type F_Float is digits 6;
21138 pragma Float_Representation (VAX_Float, F_Float);
21139 @end cartouche
21140 @end smallexample
21142 @noindent
21143 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21144 format.
21145 This set of declarations actually appears in @code{System.Aux_DEC},
21146 which contains
21147 the full set of additional floating-point declarations provided in
21148 the HP Ada version of package @code{System}.
21149 This and similar declarations may be accessed in a user program
21150 by using pragma @code{Extend_System}. The use of this
21151 pragma, and the related pragma @code{Long_Float} is described in further
21152 detail in the following section.
21154 @node Pragmas Float_Representation and Long_Float
21155 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
21157 @noindent
21158 HP Ada provides the pragma @code{Float_Representation}, which
21159 acts as a program library switch to allow control over
21160 the internal representation chosen for the predefined
21161 floating-point types declared in the package @code{Standard}.
21162 The format of this pragma is as follows:
21164 @smallexample @c ada
21165 @cartouche
21166 pragma Float_Representation(VAX_Float | IEEE_Float);
21167 @end cartouche
21168 @end smallexample
21170 @noindent
21171 This pragma controls the representation of floating-point
21172 types as follows:
21174 @itemize @bullet
21175 @item
21176 @code{VAX_Float} specifies that floating-point
21177 types are represented by default with the VAX system hardware types
21178 @code{F-floating}, @code{D-floating}, @code{G-floating}.
21179 Note that the @code{H-floating}
21180 type was available only on VAX systems, and is not available
21181 in either HP Ada or GNAT.
21183 @item
21184 @code{IEEE_Float} specifies that floating-point
21185 types are represented by default with the IEEE single and
21186 double floating-point types.
21187 @end itemize
21189 @noindent
21190 GNAT provides an identical implementation of the pragma
21191 @code{Float_Representation}, except that it functions as a
21192 configuration pragma. Note that the
21193 notion of configuration pragma corresponds closely to the
21194 HP Ada notion of a program library switch.
21196 When no pragma is used in GNAT, the default is @code{IEEE_Float},
21197 which is different
21198 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
21199 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
21200 advisable to change the format of numbers passed to standard library
21201 routines, and if necessary explicit type conversions may be needed.
21203 The use of @code{IEEE_Float} is recommended in GNAT since it is more
21204 efficient, and (given that it conforms to an international standard)
21205 potentially more portable.
21206 The situation in which @code{VAX_Float} may be useful is in interfacing
21207 to existing code and data that expect the use of @code{VAX_Float}.
21208 In such a situation use the predefined @code{VAX_Float}
21209 types in package @code{System}, as extended by
21210 @code{Extend_System}. For example, use @code{System.F_Float}
21211 to specify the 32-bit @code{F-Float} format.
21213 @noindent
21214 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
21215 to allow control over the internal representation chosen
21216 for the predefined type @code{Long_Float} and for floating-point
21217 type declarations with digits specified in the range 7 .. 15.
21218 The format of this pragma is as follows:
21220 @smallexample @c ada
21221 @cartouche
21222 pragma Long_Float (D_FLOAT | G_FLOAT);
21223 @end cartouche
21224 @end smallexample
21226 @node Fixed-Point Types and Representations
21227 @subsection Fixed-Point Types and Representations
21229 @noindent
21230 On HP Ada for OpenVMS Alpha systems, rounding is
21231 away from zero for both positive and negative numbers.
21232 Therefore, @code{+0.5} rounds to @code{1},
21233 and @code{-0.5} rounds to @code{-1}.
21235 On GNAT the results of operations
21236 on fixed-point types are in accordance with the Ada
21237 rules. In particular, results of operations on decimal
21238 fixed-point types are truncated.
21240 @node Record and Array Component Alignment
21241 @subsection Record and Array Component Alignment
21243 @noindent
21244 On HP Ada for OpenVMS Alpha, all non-composite components
21245 are aligned on natural boundaries. For example, 1-byte
21246 components are aligned on byte boundaries, 2-byte
21247 components on 2-byte boundaries, 4-byte components on 4-byte
21248 byte boundaries, and so on. The OpenVMS Alpha hardware
21249 runs more efficiently with naturally aligned data.
21251 On GNAT, alignment rules are compatible
21252 with HP Ada for OpenVMS Alpha.
21254 @node Address Clauses
21255 @subsection Address Clauses
21257 @noindent
21258 In HP Ada and GNAT, address clauses are supported for
21259 objects and imported subprograms.
21260 The predefined type @code{System.Address} is a private type
21261 in both compilers on Alpha OpenVMS, with the same representation
21262 (it is simply a machine pointer). Addition, subtraction, and comparison
21263 operations are available in the standard Ada package
21264 @code{System.Storage_Elements}, or in package @code{System}
21265 if it is extended to include @code{System.Aux_DEC} using a
21266 pragma @code{Extend_System} as previously described.
21268 Note that code that @code{with}'s both this extended package @code{System}
21269 and the package @code{System.Storage_Elements} should not @code{use}
21270 both packages, or ambiguities will result. In general it is better
21271 not to mix these two sets of facilities. The Ada package was
21272 designed specifically to provide the kind of features that HP Ada
21273 adds directly to package @code{System}.
21275 The type @code{System.Address} is a 64-bit integer type in GNAT for
21276 I64 OpenVMS.  For more information,
21277 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21279 GNAT is compatible with HP Ada in its handling of address
21280 clauses, except for some limitations in
21281 the form of address clauses for composite objects with
21282 initialization. Such address clauses are easily replaced
21283 by the use of an explicitly-defined constant as described
21284 in the Ada Reference Manual (13.1(22)). For example, the sequence
21285 of declarations:
21287 @smallexample @c ada
21288 @cartouche
21289 X, Y : Integer := Init_Func;
21290 Q : String (X .. Y) := "abc";
21291 @dots{}
21292 for Q'Address use Compute_Address;
21293 @end cartouche
21294 @end smallexample
21296 @noindent
21297 will be rejected by GNAT, since the address cannot be computed at the time
21298 that @code{Q} is declared. To achieve the intended effect, write instead:
21300 @smallexample @c ada
21301 @group
21302 @cartouche
21303 X, Y : Integer := Init_Func;
21304 Q_Address : constant Address := Compute_Address;
21305 Q : String (X .. Y) := "abc";
21306 @dots{}
21307 for Q'Address use Q_Address;
21308 @end cartouche
21309 @end group
21310 @end smallexample
21312 @noindent
21313 which will be accepted by GNAT (and other Ada compilers), and is also
21314 compatible with Ada 83. A fuller description of the restrictions
21315 on address specifications is found in @ref{Top, GNAT Reference Manual,
21316 About This Guide, gnat_rm, GNAT Reference Manual}.
21318 @node Other Representation Clauses
21319 @subsection Other Representation Clauses
21321 @noindent
21322 GNAT implements in a compatible manner all the representation
21323 clauses supported by HP Ada. In addition, GNAT
21324 implements the representation clause forms that were introduced in Ada 95,
21325 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
21327 @node The Package STANDARD
21328 @section The Package @code{STANDARD}
21330 @noindent
21331 The package @code{STANDARD}, as implemented by HP Ada, is fully
21332 described in the @cite{Ada Reference Manual} and in the
21333 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
21334 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
21336 In addition, HP Ada supports the Latin-1 character set in
21337 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
21338 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
21339 the type @code{WIDE_CHARACTER}.
21341 The floating-point types supported by GNAT are those
21342 supported by HP Ada, but the defaults are different, and are controlled by
21343 pragmas. See @ref{Floating-Point Types and Representations}, for details.
21345 @node The Package SYSTEM
21346 @section The Package @code{SYSTEM}
21348 @noindent
21349 HP Ada provides a specific version of the package
21350 @code{SYSTEM} for each platform on which the language is implemented.
21351 For the complete spec of the package @code{SYSTEM}, see
21352 Appendix F of the @cite{HP Ada Language Reference Manual}.
21354 On HP Ada, the package @code{SYSTEM} includes the following conversion
21355 functions:
21356 @itemize @bullet
21357 @item @code{TO_ADDRESS(INTEGER)}
21359 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
21361 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
21363 @item @code{TO_INTEGER(ADDRESS)}
21365 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
21367 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
21368 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
21369 @end itemize
21371 @noindent
21372 By default, GNAT supplies a version of @code{SYSTEM} that matches
21373 the definition given in the @cite{Ada Reference Manual}.
21374 This
21375 is a subset of the HP system definitions, which is as
21376 close as possible to the original definitions. The only difference
21377 is that the definition of @code{SYSTEM_NAME} is different:
21379 @smallexample @c ada
21380 @cartouche
21381 type Name is (SYSTEM_NAME_GNAT);
21382 System_Name : constant Name := SYSTEM_NAME_GNAT;
21383 @end cartouche
21384 @end smallexample
21386 @noindent
21387 Also, GNAT adds the Ada declarations for
21388 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
21390 However, the use of the following pragma causes GNAT
21391 to extend the definition of package @code{SYSTEM} so that it
21392 encompasses the full set of HP-specific extensions,
21393 including the functions listed above:
21395 @smallexample @c ada
21396 @cartouche
21397 pragma Extend_System (Aux_DEC);
21398 @end cartouche
21399 @end smallexample
21401 @noindent
21402 The pragma @code{Extend_System} is a configuration pragma that
21403 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
21404 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
21406 HP Ada does not allow the recompilation of the package
21407 @code{SYSTEM}. Instead HP Ada provides several pragmas
21408 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
21409 to modify values in the package @code{SYSTEM}.
21410 On OpenVMS Alpha systems, the pragma
21411 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
21412 its single argument.
21414 GNAT does permit the recompilation of package @code{SYSTEM} using
21415 the special switch @option{-gnatg}, and this switch can be used if
21416 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
21417 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
21418 or @code{MEMORY_SIZE} by any other means.
21420 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
21421 enumeration literal @code{SYSTEM_NAME_GNAT}.
21423 The definitions provided by the use of
21425 @smallexample @c ada
21426 pragma Extend_System (AUX_Dec);
21427 @end smallexample
21429 @noindent
21430 are virtually identical to those provided by the HP Ada 83 package
21431 @code{SYSTEM}. One important difference is that the name of the
21432 @code{TO_ADDRESS}
21433 function for type @code{UNSIGNED_LONGWORD} is changed to
21434 @code{TO_ADDRESS_LONG}.
21435 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
21436 discussion of why this change was necessary.
21438 @noindent
21439 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
21440 is in fact
21441 an extension to Ada 83 not strictly compatible with the reference manual.
21442 GNAT, in order to be exactly compatible with the standard,
21443 does not provide this capability. In HP Ada 83, the
21444 point of this definition is to deal with a call like:
21446 @smallexample @c ada
21447 TO_ADDRESS (16#12777#);
21448 @end smallexample
21450 @noindent
21451 Normally, according to Ada 83 semantics, one would expect this to be
21452 ambiguous, since it matches both the @code{INTEGER} and
21453 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
21454 However, in HP Ada 83, there is no ambiguity, since the
21455 definition using @i{universal_integer} takes precedence.
21457 In GNAT, since the version with @i{universal_integer} cannot be supplied,
21458 it is
21459 not possible to be 100% compatible. Since there are many programs using
21460 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
21461 GNAT was
21462 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
21463 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
21465 @smallexample @c ada
21466 function To_Address (X : Integer) return Address;
21467 pragma Pure_Function (To_Address);
21469 function To_Address_Long (X : Unsigned_Longword) return Address;
21470 pragma Pure_Function (To_Address_Long);
21471 @end smallexample
21473 @noindent
21474 This means that programs using @code{TO_ADDRESS} for
21475 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
21477 @node Tasking and Task-Related Features
21478 @section Tasking and Task-Related Features
21480 @noindent
21481 This section compares the treatment of tasking in GNAT
21482 and in HP Ada for OpenVMS Alpha.
21483 The GNAT description applies to both Alpha and I64 OpenVMS.
21484 For detailed information on tasking in
21485 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
21486 relevant run-time reference manual.
21488 @menu
21489 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
21490 * Assigning Task IDs::
21491 * Task IDs and Delays::
21492 * Task-Related Pragmas::
21493 * Scheduling and Task Priority::
21494 * The Task Stack::
21495 * External Interrupts::
21496 @end menu
21498 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21499 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21501 @noindent
21502 On OpenVMS Alpha systems, each Ada task (except a passive
21503 task) is implemented as a single stream of execution
21504 that is created and managed by the kernel. On these
21505 systems, HP Ada tasking support is based on DECthreads,
21506 an implementation of the POSIX standard for threads.
21508 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
21509 code that calls DECthreads routines can be used together.
21510 The interaction between Ada tasks and DECthreads routines
21511 can have some benefits. For example when on OpenVMS Alpha,
21512 HP Ada can call C code that is already threaded.
21514 GNAT uses the facilities of DECthreads,
21515 and Ada tasks are mapped to threads.
21517 @node Assigning Task IDs
21518 @subsection Assigning Task IDs
21520 @noindent
21521 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
21522 the environment task that executes the main program. On
21523 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21524 that have been created but are not yet activated.
21526 On OpenVMS Alpha systems, task IDs are assigned at
21527 activation. On GNAT systems, task IDs are also assigned at
21528 task creation but do not have the same form or values as
21529 task ID values in HP Ada. There is no null task, and the
21530 environment task does not have a specific task ID value.
21532 @node Task IDs and Delays
21533 @subsection Task IDs and Delays
21535 @noindent
21536 On OpenVMS Alpha systems, tasking delays are implemented
21537 using Timer System Services. The Task ID is used for the
21538 identification of the timer request (the @code{REQIDT} parameter).
21539 If Timers are used in the application take care not to use
21540 @code{0} for the identification, because cancelling such a timer
21541 will cancel all timers and may lead to unpredictable results.
21543 @node Task-Related Pragmas
21544 @subsection Task-Related Pragmas
21546 @noindent
21547 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21548 specification of the size of the guard area for a task
21549 stack. (The guard area forms an area of memory that has no
21550 read or write access and thus helps in the detection of
21551 stack overflow.) On OpenVMS Alpha systems, if the pragma
21552 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21553 area is created. In the absence of a pragma @code{TASK_STORAGE},
21554 a default guard area is created.
21556 GNAT supplies the following task-related pragmas:
21558 @itemize @bullet
21559 @item  @code{TASK_INFO}
21561 This pragma appears within a task definition and
21562 applies to the task in which it appears. The argument
21563 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21565 @item  @code{TASK_STORAGE}
21567 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
21568 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21569 @code{SUPPRESS}, and @code{VOLATILE}.
21570 @end itemize
21571 @node Scheduling and Task Priority
21572 @subsection Scheduling and Task Priority
21574 @noindent
21575 HP Ada implements the Ada language requirement that
21576 when two tasks are eligible for execution and they have
21577 different priorities, the lower priority task does not
21578 execute while the higher priority task is waiting. The HP
21579 Ada Run-Time Library keeps a task running until either the
21580 task is suspended or a higher priority task becomes ready.
21582 On OpenVMS Alpha systems, the default strategy is round-
21583 robin with preemption. Tasks of equal priority take turns
21584 at the processor. A task is run for a certain period of
21585 time and then placed at the tail of the ready queue for
21586 its priority level.
21588 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21589 which can be used to enable or disable round-robin
21590 scheduling of tasks with the same priority.
21591 See the relevant HP Ada run-time reference manual for
21592 information on using the pragmas to control HP Ada task
21593 scheduling.
21595 GNAT follows the scheduling rules of Annex D (Real-Time
21596 Annex) of the @cite{Ada Reference Manual}. In general, this
21597 scheduling strategy is fully compatible with HP Ada
21598 although it provides some additional constraints (as
21599 fully documented in Annex D).
21600 GNAT implements time slicing control in a manner compatible with
21601 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21602 are identical to the HP Ada 83 pragma of the same name.
21603 Note that it is not possible to mix GNAT tasking and
21604 HP Ada 83 tasking in the same program, since the two run-time
21605 libraries are not compatible.
21607 @node The Task Stack
21608 @subsection The Task Stack
21610 @noindent
21611 In HP Ada, a task stack is allocated each time a
21612 non-passive task is activated. As soon as the task is
21613 terminated, the storage for the task stack is deallocated.
21614 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21615 a default stack size is used. Also, regardless of the size
21616 specified, some additional space is allocated for task
21617 management purposes. On OpenVMS Alpha systems, at least
21618 one page is allocated.
21620 GNAT handles task stacks in a similar manner. In accordance with
21621 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
21622 an alternative method for controlling the task stack size.
21623 The specification of the attribute @code{T'STORAGE_SIZE} is also
21624 supported in a manner compatible with HP Ada.
21626 @node External Interrupts
21627 @subsection External Interrupts
21629 @noindent
21630 On HP Ada, external interrupts can be associated with task entries.
21631 GNAT is compatible with HP Ada in its handling of external interrupts.
21633 @node Pragmas and Pragma-Related Features
21634 @section Pragmas and Pragma-Related Features
21636 @noindent
21637 Both HP Ada and GNAT supply all language-defined pragmas
21638 as specified by the Ada 83 standard. GNAT also supplies all
21639 language-defined pragmas introduced by Ada 95 and Ada 2005.
21640 In addition, GNAT implements the implementation-defined pragmas
21641 from HP Ada 83.
21643 @itemize @bullet
21644 @item  @code{AST_ENTRY}
21646 @item  @code{COMMON_OBJECT}
21648 @item  @code{COMPONENT_ALIGNMENT}
21650 @item  @code{EXPORT_EXCEPTION}
21652 @item  @code{EXPORT_FUNCTION}
21654 @item  @code{EXPORT_OBJECT}
21656 @item  @code{EXPORT_PROCEDURE}
21658 @item  @code{EXPORT_VALUED_PROCEDURE}
21660 @item  @code{FLOAT_REPRESENTATION}
21662 @item  @code{IDENT}
21664 @item  @code{IMPORT_EXCEPTION}
21666 @item  @code{IMPORT_FUNCTION}
21668 @item  @code{IMPORT_OBJECT}
21670 @item  @code{IMPORT_PROCEDURE}
21672 @item  @code{IMPORT_VALUED_PROCEDURE}
21674 @item  @code{INLINE_GENERIC}
21676 @item  @code{INTERFACE_NAME}
21678 @item  @code{LONG_FLOAT}
21680 @item  @code{MAIN_STORAGE}
21682 @item  @code{PASSIVE}
21684 @item  @code{PSECT_OBJECT}
21686 @item  @code{SHARE_GENERIC}
21688 @item  @code{SUPPRESS_ALL}
21690 @item  @code{TASK_STORAGE}
21692 @item  @code{TIME_SLICE}
21694 @item  @code{TITLE}
21695 @end itemize
21697 @noindent
21698 These pragmas are all fully implemented, with the exception of @code{TITLE},
21699 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21700 recognized, but which have no
21701 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21702 use of Ada protected objects. In GNAT, all generics are inlined.
21704 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21705 a separate subprogram specification which must appear before the
21706 subprogram body.
21708 GNAT also supplies a number of implementation-defined pragmas including the
21709 following:
21711 @itemize @bullet
21712 @item  @code{ABORT_DEFER}
21714 @item  @code{ADA_83}
21716 @item  @code{ADA_95}
21718 @item  @code{ADA_05}
21720 @item  @code{Ada_2005}
21722 @item  @code{Ada_12}
21724 @item  @code{Ada_2012}
21726 @item  @code{ANNOTATE}
21728 @item  @code{ASSERT}
21730 @item  @code{C_PASS_BY_COPY}
21732 @item  @code{CPP_CLASS}
21734 @item  @code{CPP_CONSTRUCTOR}
21736 @item  @code{CPP_DESTRUCTOR}
21738 @item  @code{DEBUG}
21740 @item  @code{EXTEND_SYSTEM}
21742 @item  @code{LINKER_ALIAS}
21744 @item  @code{LINKER_SECTION}
21746 @item  @code{MACHINE_ATTRIBUTE}
21748 @item  @code{NO_RETURN}
21750 @item  @code{PURE_FUNCTION}
21752 @item  @code{SOURCE_FILE_NAME}
21754 @item  @code{SOURCE_REFERENCE}
21756 @item  @code{TASK_INFO}
21758 @item  @code{UNCHECKED_UNION}
21760 @item  @code{UNIMPLEMENTED_UNIT}
21762 @item  @code{UNIVERSAL_DATA}
21764 @item  @code{UNSUPPRESS}
21766 @item  @code{WARNINGS}
21768 @item  @code{WEAK_EXTERNAL}
21769 @end itemize
21771 @noindent
21772 For full details on these and other GNAT implementation-defined pragmas,
21773 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21774 Manual}.
21776 @menu
21777 * Restrictions on the Pragma INLINE::
21778 * Restrictions on the Pragma INTERFACE::
21779 * Restrictions on the Pragma SYSTEM_NAME::
21780 @end menu
21782 @node Restrictions on the Pragma INLINE
21783 @subsection Restrictions on Pragma @code{INLINE}
21785 @noindent
21786 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21787 @itemize @bullet
21788 @item  Parameters cannot have a task type.
21790 @item  Function results cannot be task types, unconstrained
21791 array types, or unconstrained types with discriminants.
21793 @item  Bodies cannot declare the following:
21794 @itemize @bullet
21795 @item  Subprogram body or stub (imported subprogram is allowed)
21797 @item  Tasks
21799 @item  Generic declarations
21801 @item  Instantiations
21803 @item  Exceptions
21805 @item  Access types (types derived from access types allowed)
21807 @item  Array or record types
21809 @item  Dependent tasks
21811 @item  Direct recursive calls of subprogram or containing
21812 subprogram, directly or via a renaming
21814 @end itemize
21815 @end itemize
21817 @noindent
21818 In GNAT, the only restriction on pragma @code{INLINE} is that the
21819 body must occur before the call if both are in the same
21820 unit, and the size must be appropriately small. There are
21821 no other specific restrictions which cause subprograms to
21822 be incapable of being inlined.
21824 @node  Restrictions on the Pragma INTERFACE
21825 @subsection  Restrictions on Pragma @code{INTERFACE}
21827 @noindent
21828 The following restrictions on pragma @code{INTERFACE}
21829 are enforced by both HP Ada and GNAT:
21830 @itemize @bullet
21831 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21832 Default is the default on OpenVMS Alpha systems.
21834 @item  Parameter passing: Language specifies default
21835 mechanisms but can be overridden with an @code{EXPORT} pragma.
21837 @itemize @bullet
21838 @item  Ada: Use internal Ada rules.
21840 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21841 record or task type. Result cannot be a string, an
21842 array, or a record.
21844 @item  Fortran: Parameters cannot have a task type. Result cannot
21845 be a string, an array, or a record.
21846 @end itemize
21847 @end itemize
21849 @noindent
21850 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21851 record parameters for all languages.
21853 @node  Restrictions on the Pragma SYSTEM_NAME
21854 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21856 @noindent
21857 For HP Ada for OpenVMS Alpha, the enumeration literal
21858 for the type @code{NAME} is @code{OPENVMS_AXP}.
21859 In GNAT, the enumeration
21860 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21862 @node  Library of Predefined Units
21863 @section  Library of Predefined Units
21865 @noindent
21866 A library of predefined units is provided as part of the
21867 HP Ada and GNAT implementations. HP Ada does not provide
21868 the package @code{MACHINE_CODE} but instead recommends importing
21869 assembler code.
21871 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21872 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21873 version.
21874 The HP Ada Predefined Library units are modified to remove post-Ada 83
21875 incompatibilities and to make them interoperable with GNAT
21876 (@pxref{Changes to DECLIB}, for details).
21877 The units are located in the @file{DECLIB} directory.
21879 The GNAT RTL is contained in
21880 the @file{ADALIB} directory, and
21881 the default search path is set up to find @code{DECLIB} units in preference
21882 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21883 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21885 @menu
21886 * Changes to DECLIB::
21887 @end menu
21889 @node Changes to DECLIB
21890 @subsection Changes to @code{DECLIB}
21892 @noindent
21893 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21894 compatibility are minor and include the following:
21896 @itemize @bullet
21897 @item  Adjusting the location of pragmas and record representation
21898 clauses to obey Ada 95 (and thus Ada 2005) rules
21900 @item  Adding the proper notation to generic formal parameters
21901 that take unconstrained types in instantiation
21903 @item  Adding pragma @code{ELABORATE_BODY} to package specs
21904 that have package bodies not otherwise allowed
21906 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21907 ``@code{PROTECTD}''.
21908 Currently these are found only in the @code{STARLET} package spec.
21910 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21911 where the address size is constrained to 32 bits.
21912 @end itemize
21914 @noindent
21915 None of the above changes is visible to users.
21917 @node Bindings
21918 @section Bindings
21920 @noindent
21921 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21922 @itemize @bullet
21924 @item  Command Language Interpreter (CLI interface)
21926 @item  DECtalk Run-Time Library (DTK interface)
21928 @item  Librarian utility routines (LBR interface)
21930 @item  General Purpose Run-Time Library (LIB interface)
21932 @item  Math Run-Time Library (MTH interface)
21934 @item  National Character Set Run-Time Library (NCS interface)
21936 @item  Compiled Code Support Run-Time Library (OTS interface)
21938 @item  Parallel Processing Run-Time Library (PPL interface)
21940 @item  Screen Management Run-Time Library (SMG interface)
21942 @item  Sort Run-Time Library (SOR interface)
21944 @item  String Run-Time Library (STR interface)
21946 @item STARLET System Library
21947 @findex Starlet
21949 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21951 @item  X Windows Toolkit (XT interface)
21953 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21954 @end itemize
21956 @noindent
21957 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21958 directory, on both the Alpha and I64 OpenVMS platforms.
21960 The X components of DECLIB compatibility package are located in a separate
21961 library, called XDECGNAT, which is not linked with by default; this library
21962 must be explicitly linked with any application that makes use of any X facilities,
21963 with a command similar to
21965 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21967 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21968 in the
21969 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21970 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21971 @code{Xt}, and @code{X_Lib}
21972 causing the default X/Motif sharable image libraries to be linked in. This
21973 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21974 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21976 It may be necessary to edit these options files to update or correct the
21977 library names if, for example, the newer X/Motif bindings from
21978 @file{ADA$EXAMPLES}
21979 had been (previous to installing GNAT) copied and renamed to supersede the
21980 default @file{ADA$PREDEFINED} versions.
21982 @menu
21983 * Shared Libraries and Options Files::
21984 * Interfaces to C::
21985 @end menu
21987 @node Shared Libraries and Options Files
21988 @subsection Shared Libraries and Options Files
21990 @noindent
21991 When using the HP Ada
21992 predefined X and Motif bindings, the linking with their sharable images is
21993 done automatically by @command{GNAT LINK}.
21994 When using other X and Motif bindings, you need
21995 to add the corresponding sharable images to the command line for
21996 @code{GNAT LINK}. When linking with shared libraries, or with
21997 @file{.OPT} files, you must
21998 also add them to the command line for @command{GNAT LINK}.
22000 A shared library to be used with GNAT is built in the same way as other
22001 libraries under VMS. The VMS Link command can be used in standard fashion.
22003 @node Interfaces to C
22004 @subsection Interfaces to C
22006 @noindent
22007 HP Ada
22008 provides the following Ada types and operations:
22010 @itemize @bullet
22011 @item C types package (@code{C_TYPES})
22013 @item C strings (@code{C_TYPES.NULL_TERMINATED})
22015 @item Other_types (@code{SHORT_INT})
22016 @end itemize
22018 @noindent
22019 Interfacing to C with GNAT, you can use the above approach
22020 described for HP Ada or the facilities of Annex B of
22021 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
22022 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22023 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
22025 The @option{-gnatF} qualifier forces default and explicit
22026 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22027 to be uppercased for compatibility with the default behavior
22028 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22030 @node Main Program Definition
22031 @section Main Program Definition
22033 @noindent
22034 The following section discusses differences in the
22035 definition of main programs on HP Ada and GNAT.
22036 On HP Ada, main programs are defined to meet the
22037 following conditions:
22038 @itemize @bullet
22039 @item  Procedure with no formal parameters (returns @code{0} upon
22040 normal completion)
22042 @item  Procedure with no formal parameters (returns @code{42} when
22043 an unhandled exception is raised)
22045 @item  Function with no formal parameters whose returned value
22046 is of a discrete type
22048 @item  Procedure with one @code{out} formal of a discrete type for
22049 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
22051 @end itemize
22053 @noindent
22054 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22055 a main function or main procedure returns a discrete
22056 value whose size is less than 64 bits (32 on VAX systems),
22057 the value is zero- or sign-extended as appropriate.
22058 On GNAT, main programs are defined as follows:
22059 @itemize @bullet
22060 @item  Must be a non-generic, parameterless subprogram that
22061 is either a procedure or function returning an Ada
22062 @code{STANDARD.INTEGER} (the predefined type)
22064 @item  Cannot be a generic subprogram or an instantiation of a
22065 generic subprogram
22066 @end itemize
22068 @node Implementation-Defined Attributes
22069 @section Implementation-Defined Attributes
22071 @noindent
22072 GNAT provides all HP Ada implementation-defined
22073 attributes.
22075 @node Compiler and Run-Time Interfacing
22076 @section Compiler and Run-Time Interfacing
22078 @noindent
22079 HP Ada provides the following qualifiers to pass options to the linker
22080 (ACS LINK):
22081 @itemize @bullet
22082 @item  @option{/WAIT} and @option{/SUBMIT}
22084 @item  @option{/COMMAND}
22086 @item  @option{/@r{[}NO@r{]}MAP}
22088 @item  @option{/OUTPUT=@var{file-spec}}
22090 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22091 @end itemize
22093 @noindent
22094 To pass options to the linker, GNAT provides the following
22095 switches:
22097 @itemize @bullet
22098 @item   @option{/EXECUTABLE=@var{exec-name}}
22100 @item   @option{/VERBOSE}
22102 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22103 @end itemize
22105 @noindent
22106 For more information on these switches, see
22107 @ref{Switches for gnatlink}.
22108 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
22109 to control optimization. HP Ada also supplies the
22110 following pragmas:
22111 @itemize @bullet
22112 @item  @code{OPTIMIZE}
22114 @item  @code{INLINE}
22116 @item  @code{INLINE_GENERIC}
22118 @item  @code{SUPPRESS_ALL}
22120 @item  @code{PASSIVE}
22121 @end itemize
22123 @noindent
22124 In GNAT, optimization is controlled strictly by command
22125 line parameters, as described in the corresponding section of this guide.
22126 The HP pragmas for control of optimization are
22127 recognized but ignored.
22129 Note that in GNAT, the default is optimization off, whereas in HP Ada
22130 the default is that optimization is turned on.
22132 @node Program Compilation and Library Management
22133 @section Program Compilation and Library Management
22135 @noindent
22136 HP Ada and GNAT provide a comparable set of commands to
22137 build programs. HP Ada also provides a program library,
22138 which is a concept that does not exist on GNAT. Instead,
22139 GNAT provides directories of sources that are compiled as
22140 needed.
22142 The following table summarizes
22143 the HP Ada commands and provides
22144 equivalent GNAT commands. In this table, some GNAT
22145 equivalents reflect the fact that GNAT does not use the
22146 concept of a program library. Instead, it uses a model
22147 in which collections of source and object files are used
22148 in a manner consistent with other languages like C and
22149 Fortran. Therefore, standard system file commands are used
22150 to manipulate these elements. Those GNAT commands are marked with
22151 an asterisk.
22152 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
22154 @need 1500
22155 @multitable @columnfractions .35 .65
22157 @item @emph{HP Ada Command}
22158 @tab @emph{GNAT Equivalent / Description}
22160 @item @command{ADA}
22161 @tab @command{GNAT COMPILE}@*
22162 Invokes the compiler to compile one or more Ada source files.
22164 @item @command{ACS ATTACH}@*
22165 @tab [No equivalent]@*
22166 Switches control of terminal from current process running the program
22167 library manager.
22169 @item @command{ACS CHECK}
22170 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
22171 Forms the execution closure of one
22172 or more compiled units and checks completeness and currency.
22174 @item @command{ACS COMPILE}
22175 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22176 Forms the execution closure of one or
22177 more specified units, checks completeness and currency,
22178 identifies units that have revised source files, compiles same,
22179 and recompiles units that are or will become obsolete.
22180 Also completes incomplete generic instantiations.
22182 @item @command{ACS COPY FOREIGN}
22183 @tab Copy (*)@*
22184 Copies a foreign object file into the program library as a
22185 library unit body.
22187 @item @command{ACS COPY UNIT}
22188 @tab Copy (*)@*
22189 Copies a compiled unit from one program library to another.
22191 @item @command{ACS CREATE LIBRARY}
22192 @tab Create /directory (*)@*
22193 Creates a program library.
22195 @item @command{ACS CREATE SUBLIBRARY}
22196 @tab Create /directory (*)@*
22197 Creates a program sublibrary.
22199 @item @command{ACS DELETE LIBRARY}
22200 @tab @*
22201 Deletes a program library and its contents.
22203 @item @command{ACS DELETE SUBLIBRARY}
22204 @tab @*
22205 Deletes a program sublibrary and its contents.
22207 @item @command{ACS DELETE UNIT}
22208 @tab Delete file (*)@*
22209 On OpenVMS systems, deletes one or more compiled units from
22210 the current program library.
22212 @item @command{ACS DIRECTORY}
22213 @tab Directory (*)@*
22214 On OpenVMS systems, lists units contained in the current
22215 program library.
22217 @item @command{ACS ENTER FOREIGN}
22218 @tab Copy (*)@*
22219 Allows the import of a foreign body as an Ada library
22220 spec and enters a reference to a pointer.
22222 @item @command{ACS ENTER UNIT}
22223 @tab Copy (*)@*
22224 Enters a reference (pointer) from the current program library to
22225 a unit compiled into another program library.
22227 @item @command{ACS EXIT}
22228 @tab [No equivalent]@*
22229 Exits from the program library manager.
22231 @item @command{ACS EXPORT}
22232 @tab Copy (*)@*
22233 Creates an object file that contains system-specific object code
22234 for one or more units. With GNAT, object files can simply be copied
22235 into the desired directory.
22237 @item @command{ACS EXTRACT SOURCE}
22238 @tab Copy (*)@*
22239 Allows access to the copied source file for each Ada compilation unit
22241 @item @command{ACS HELP}
22242 @tab @command{HELP GNAT}@*
22243 Provides online help.
22245 @item @command{ACS LINK}
22246 @tab @command{GNAT LINK}@*
22247 Links an object file containing Ada units into an executable file.
22249 @item @command{ACS LOAD}
22250 @tab Copy (*)@*
22251 Loads (partially compiles) Ada units into the program library.
22252 Allows loading a program from a collection of files into a library
22253 without knowing the relationship among units.
22255 @item @command{ACS MERGE}
22256 @tab Copy (*)@*
22257 Merges into the current program library, one or more units from
22258 another library where they were modified.
22260 @item @command{ACS RECOMPILE}
22261 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22262 Recompiles from   external or copied source files any obsolete
22263 unit in the closure. Also, completes any incomplete generic
22264 instantiations.
22266 @item @command{ACS REENTER}
22267 @tab @command{GNAT MAKE}@*
22268 Reenters current references to units compiled after last entered
22269 with the @command{ACS ENTER UNIT} command.
22271 @item @command{ACS SET LIBRARY}
22272 @tab Set default (*)@*
22273 Defines a program library to be the compilation context as well
22274 as the target library for compiler output and commands in general.
22276 @item @command{ACS SET PRAGMA}
22277 @tab Edit @file{gnat.adc} (*)@*
22278 Redefines specified  values of the library characteristics
22279 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
22280 and @code{Float_Representation}.
22282 @item @command{ACS SET SOURCE}
22283 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
22284 Defines the source file search list for the @command{ACS COMPILE} command.
22286 @item @command{ACS SHOW LIBRARY}
22287 @tab Directory (*)@*
22288 Lists information about one or more program libraries.
22290 @item @command{ACS SHOW PROGRAM}
22291 @tab [No equivalent]@*
22292 Lists information about the execution closure of one or
22293 more units in the program library.
22295 @item @command{ACS SHOW SOURCE}
22296 @tab Show logical @code{ADA_INCLUDE_PATH}@*
22297 Shows the source file search used when compiling units.
22299 @item @command{ACS SHOW VERSION}
22300 @tab Compile with @option{VERBOSE} option
22301 Displays the version number of the compiler and program library
22302 manager used.
22304 @item @command{ACS SPAWN}
22305 @tab [No equivalent]@*
22306 Creates a subprocess of the current process (same as @command{DCL SPAWN}
22307 command).
22309 @item @command{ACS VERIFY}
22310 @tab [No equivalent]@*
22311 Performs a series of consistency checks on a program library to
22312 determine whether the library structure and library files are in
22313 valid form.
22314 @end multitable
22316 @noindent
22318 @node Input-Output
22319 @section Input-Output
22321 @noindent
22322 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22323 Management Services (RMS) to perform operations on
22324 external files.
22326 @noindent
22327 HP Ada and GNAT predefine an identical set of input-
22328 output packages. To make the use of the
22329 generic @code{TEXT_IO} operations more convenient, HP Ada
22330 provides predefined library packages that instantiate the
22331 integer and floating-point operations for the predefined
22332 integer and floating-point types as shown in the following table.
22334 @multitable @columnfractions .45 .55
22335 @item @emph{Package Name} @tab Instantiation
22337 @item @code{INTEGER_TEXT_IO}
22338 @tab @code{INTEGER_IO(INTEGER)}
22340 @item @code{SHORT_INTEGER_TEXT_IO}
22341 @tab @code{INTEGER_IO(SHORT_INTEGER)}
22343 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
22344 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
22346 @item @code{FLOAT_TEXT_IO}
22347 @tab @code{FLOAT_IO(FLOAT)}
22349 @item @code{LONG_FLOAT_TEXT_IO}
22350 @tab @code{FLOAT_IO(LONG_FLOAT)}
22351 @end multitable
22353 @noindent
22354 The HP Ada predefined packages and their operations
22355 are implemented using OpenVMS Alpha files and input-output
22356 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
22357 Familiarity with the following is recommended:
22358 @itemize @bullet
22359 @item  RMS file organizations and access methods
22361 @item  OpenVMS file specifications and directories
22363 @item  OpenVMS File Definition Language (FDL)
22364 @end itemize
22366 @noindent
22367 GNAT provides I/O facilities that are completely
22368 compatible with HP Ada. The distribution includes the
22369 standard HP Ada versions of all I/O packages, operating
22370 in a manner compatible with HP Ada. In particular, the
22371 following packages are by default the HP Ada (Ada 83)
22372 versions of these packages rather than the renamings
22373 suggested in Annex J of the Ada Reference Manual:
22374 @itemize @bullet
22375 @item  @code{TEXT_IO}
22377 @item  @code{SEQUENTIAL_IO}
22379 @item  @code{DIRECT_IO}
22380 @end itemize
22382 @noindent
22383 The use of the standard child package syntax (for
22384 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
22385 packages.
22386 GNAT provides HP-compatible predefined instantiations
22387 of the @code{TEXT_IO} packages, and also
22388 provides the standard predefined instantiations required
22389 by the @cite{Ada Reference Manual}.
22391 For further information on how GNAT interfaces to the file
22392 system or how I/O is implemented in programs written in
22393 mixed languages, see @ref{Implementation of the Standard I/O,,,
22394 gnat_rm, GNAT Reference Manual}.
22395 This chapter covers the following:
22396 @itemize @bullet
22397 @item  Standard I/O packages
22399 @item  @code{FORM} strings
22401 @item  @code{ADA.DIRECT_IO}
22403 @item  @code{ADA.SEQUENTIAL_IO}
22405 @item  @code{ADA.TEXT_IO}
22407 @item  Stream pointer positioning
22409 @item  Reading and writing non-regular files
22411 @item  @code{GET_IMMEDIATE}
22413 @item  Treating @code{TEXT_IO} files as streams
22415 @item  Shared files
22417 @item  Open modes
22418 @end itemize
22420 @node Implementation Limits
22421 @section Implementation Limits
22423 @noindent
22424 The following table lists implementation limits for HP Ada
22425 and GNAT systems.
22426 @multitable @columnfractions .60 .20 .20
22427 @sp 1
22428 @item  @emph{Compilation Parameter}
22429 @tab   @emph{HP Ada}
22430 @tab   @emph{GNAT}
22431 @sp 1
22433 @item  In a subprogram or entry  declaration, maximum number of
22434 formal parameters that are of an unconstrained record type
22435 @tab   32
22436 @tab   No set limit
22437 @sp 1
22439 @item  Maximum identifier length (number of characters)
22440 @tab   255
22441 @tab   32766
22442 @sp 1
22444 @item  Maximum number of characters in a source line
22445 @tab   255
22446 @tab   32766
22447 @sp 1
22449 @item  Maximum collection size   (number of bytes)
22450 @tab   2**31-1
22451 @tab   2**31-1
22452 @sp 1
22454 @item  Maximum number of discriminants for a record type
22455 @tab   245
22456 @tab   No set limit
22457 @sp 1
22459 @item  Maximum number of formal parameters in an entry or
22460 subprogram declaration
22461 @tab   246
22462 @tab    No set limit
22463 @sp 1
22465 @item  Maximum number of dimensions in an array type
22466 @tab   255
22467 @tab   No set limit
22468 @sp 1
22470 @item  Maximum number of library  units and subunits in a compilation.
22471 @tab   4095
22472 @tab   No set limit
22473 @sp 1
22475 @item  Maximum number of library units and subunits in an execution.
22476 @tab   16383
22477 @tab   No set limit
22478 @sp 1
22480 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22481 or @code{PSECT_OBJECT}
22482 @tab   32757
22483 @tab   No set limit
22484 @sp 1
22486 @item  Maximum number of enumeration literals in an enumeration type
22487 definition
22488 @tab   65535
22489 @tab   No set limit
22490 @sp 1
22492 @item  Maximum number of lines in a source file
22493 @tab   65534
22494 @tab   No set limit
22495 @sp 1
22497 @item  Maximum number of bits in any object
22498 @tab   2**31-1
22499 @tab   2**31-1
22500 @sp 1
22502 @item  Maximum size of the static portion of a stack frame (approximate)
22503 @tab   2**31-1
22504 @tab   2**31-1
22505 @end multitable
22507 @node Tools and Utilities
22508 @section Tools and Utilities
22510 @noindent
22511 The following table lists some of the OpenVMS development tools
22512 available for HP Ada, and the corresponding tools for
22513 use with @value{EDITION} on Alpha and I64 platforms.
22514 Aside from the debugger, all the OpenVMS tools identified are part
22515 of the DECset package.
22517 @iftex
22518 @c Specify table in TeX since Texinfo does a poor job
22519 @tex
22520 \smallskip
22521 \smallskip
22522 \settabs\+Language-Sensitive Editor\quad
22523    &Product with HP Ada\quad
22524    &\cr
22525 \+\it Tool
22526    &\it Product with HP Ada
22527    & \it Product with @value{EDITION}\cr
22528 \smallskip
22529 \+Code Management System
22530    &HP CMS
22531    & HP CMS\cr
22532 \smallskip
22533 \+Language-Sensitive Editor
22534    &HP LSE
22535    & emacs or HP LSE (Alpha)\cr
22537    &
22538    & HP LSE (I64)\cr
22539 \smallskip
22540 \+Debugger
22541    &OpenVMS Debug
22542    & gdb (Alpha),\cr
22544    &
22545    & OpenVMS Debug (I64)\cr
22546 \smallskip
22547 \+Source Code Analyzer /
22548    &HP SCA
22549    & GNAT XREF\cr
22550 \+Cross Referencer
22551    &
22552    &\cr
22553 \smallskip
22554 \+Test Manager
22555    &HP Digital Test
22556    & HP DTM\cr
22558    &Manager (DTM)
22559    &\cr
22560 \smallskip
22561 \+Performance and
22562    & HP PCA
22563    & HP PCA\cr
22564 \+Coverage Analyzer
22565    &
22566    &\cr
22567 \smallskip
22568 \+Module Management
22569    & HP MMS
22570    & Not applicable\cr
22571 \+ System
22572    &
22573    &\cr
22574 \smallskip
22575 \smallskip
22576 @end tex
22577 @end iftex
22579 @ifnottex
22580 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
22581 @c the TeX version above for the printed version
22582 @flushleft
22583 @c @multitable @columnfractions .3 .4 .4
22584 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22585 @item @i{Tool}
22586 @tab @i{Tool with HP Ada}
22587 @tab @i{Tool with @value{EDITION}}
22588 @item Code Management@*System
22589 @tab HP CMS
22590 @tab HP CMS
22591 @item Language-Sensitive@*Editor
22592 @tab HP LSE
22593 @tab emacs or HP LSE (Alpha)
22594 @item
22595 @tab
22596 @tab HP LSE (I64)
22597 @item Debugger
22598 @tab OpenVMS Debug
22599 @tab gdb (Alpha),
22600 @item
22601 @tab
22602 @tab OpenVMS Debug (I64)
22603 @item Source Code Analyzer /@*Cross Referencer
22604 @tab HP SCA
22605 @tab GNAT XREF
22606 @item Test Manager
22607 @tab HP Digital Test@*Manager (DTM)
22608 @tab HP DTM
22609 @item Performance and@*Coverage Analyzer
22610 @tab HP PCA
22611 @tab HP PCA
22612 @item Module Management@*System
22613 @tab HP MMS
22614 @tab Not applicable
22615 @end multitable
22616 @end flushleft
22617 @end ifnottex
22619 @end ifset
22621 @c **************************************
22622 @node Platform-Specific Information for the Run-Time Libraries
22623 @appendix Platform-Specific Information for the Run-Time Libraries
22624 @cindex Tasking and threads libraries
22625 @cindex Threads libraries and tasking
22626 @cindex Run-time libraries (platform-specific information)
22628 @noindent
22629 The GNAT run-time implementation may vary with respect to both the
22630 underlying threads library and the exception handling scheme.
22631 For threads support, one or more of the following are supplied:
22632 @itemize @bullet
22633 @item @b{native threads library}, a binding to the thread package from
22634 the underlying operating system
22636 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22637 POSIX thread package
22638 @end itemize
22640 @noindent
22641 For exception handling, either or both of two models are supplied:
22642 @itemize @bullet
22643 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22644 Most programs should experience a substantial speed improvement by
22645 being compiled with a ZCX run-time.
22646 This is especially true for
22647 tasking applications or applications with many exception handlers.}
22648 @cindex Zero-Cost Exceptions
22649 @cindex ZCX (Zero-Cost Exceptions)
22650 which uses binder-generated tables that
22651 are interrogated at run time to locate a handler
22653 @item @b{setjmp / longjmp} (``SJLJ''),
22654 @cindex setjmp/longjmp Exception Model
22655 @cindex SJLJ (setjmp/longjmp Exception Model)
22656 which uses dynamically-set data to establish
22657 the set of handlers
22658 @end itemize
22660 @noindent
22661 This appendix summarizes which combinations of threads and exception support
22662 are supplied on various GNAT platforms.
22663 It then shows how to select a particular library either
22664 permanently or temporarily,
22665 explains the properties of (and tradeoffs among) the various threads
22666 libraries, and provides some additional
22667 information about several specific platforms.
22669 @menu
22670 * Summary of Run-Time Configurations::
22671 * Specifying a Run-Time Library::
22672 * Choosing the Scheduling Policy::
22673 * Solaris-Specific Considerations::
22674 * Linux-Specific Considerations::
22675 * AIX-Specific Considerations::
22676 * RTX-Specific Considerations::
22677 * HP-UX-Specific Considerations::
22678 @end menu
22680 @node Summary of Run-Time Configurations
22681 @section Summary of Run-Time Configurations
22683 @multitable @columnfractions .30 .70
22684 @item @b{alpha-openvms}
22685 @item @code{@ @ }@i{rts-native (default)}
22686 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22687 @item @code{@ @ @ @ }Exceptions @tab ZCX
22689 @item @code{@ @ }@i{rts-sjlj}
22690 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22691 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22693 @item @b{ia64-hp_linux}
22694 @item @code{@ @ }@i{rts-native (default)}
22695 @item @code{@ @ @ @ }Tasking    @tab pthread library
22696 @item @code{@ @ @ @ }Exceptions @tab ZCX
22698 @item @b{ia64-hpux}
22699 @item @code{@ @ }@i{rts-native (default)}
22700 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22701 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22703 @item @b{ia64-openvms}
22704 @item @code{@ @ }@i{rts-native (default)}
22705 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22706 @item @code{@ @ @ @ }Exceptions @tab ZCX
22708 @item @b{ia64-sgi_linux}
22709 @item @code{@ @ }@i{rts-native (default)}
22710 @item @code{@ @ @ @ }Tasking    @tab pthread library
22711 @item @code{@ @ @ @ }Exceptions @tab ZCX
22713 @item @b{pa-hpux}
22714 @item @code{@ @ }@i{rts-native (default)}
22715 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22716 @item @code{@ @ @ @ }Exceptions @tab ZCX
22718 @item @code{@ @ }@i{rts-sjlj}
22719 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22720 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22722 @item @b{ppc-aix}
22723 @item @code{@ @ }@i{rts-native (default)}
22724 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22725 @item @code{@ @ @ @ }Exceptions @tab ZCX
22727 @item @code{@ @ }@i{rts-sjlj}
22728 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22729 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22731 @item @b{ppc-darwin}
22732 @item @code{@ @ }@i{rts-native (default)}
22733 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22734 @item @code{@ @ @ @ }Exceptions @tab ZCX
22736 @item @b{sparc-solaris}  @tab
22737 @item @code{@ @ }@i{rts-native (default)}
22738 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22739 @item @code{@ @ @ @ }Exceptions @tab ZCX
22741 @item @code{@ @ }@i{rts-pthread}
22742 @item @code{@ @ @ @ }Tasking    @tab pthread library
22743 @item @code{@ @ @ @ }Exceptions @tab ZCX
22745 @item @code{@ @ }@i{rts-sjlj}
22746 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22747 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22749 @item @b{sparc64-solaris}  @tab
22750 @item @code{@ @ }@i{rts-native (default)}
22751 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22752 @item @code{@ @ @ @ }Exceptions @tab ZCX
22754 @item @b{x86-linux}
22755 @item @code{@ @ }@i{rts-native (default)}
22756 @item @code{@ @ @ @ }Tasking    @tab pthread library
22757 @item @code{@ @ @ @ }Exceptions @tab ZCX
22759 @item @code{@ @ }@i{rts-sjlj}
22760 @item @code{@ @ @ @ }Tasking    @tab pthread library
22761 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22763 @item @b{x86-lynx}
22764 @item @code{@ @ }@i{rts-native (default)}
22765 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22766 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22768 @item @b{x86-solaris}
22769 @item @code{@ @ }@i{rts-native (default)}
22770 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22771 @item @code{@ @ @ @ }Exceptions @tab ZCX
22773 @item @code{@ @ }@i{rts-sjlj}
22774 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22775 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22777 @item @b{x86-windows}
22778 @item @code{@ @ }@i{rts-native (default)}
22779 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22780 @item @code{@ @ @ @ }Exceptions @tab ZCX
22782 @item @code{@ @ }@i{rts-sjlj}
22783 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22784 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22786 @item @b{x86-windows-rtx}
22787 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22788 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22789 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22791 @item @code{@ @ }@i{rts-rtx-w32}
22792 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22793 @item @code{@ @ @ @ }Exceptions @tab ZCX
22795 @item @b{x86_64-linux}
22796 @item @code{@ @ }@i{rts-native (default)}
22797 @item @code{@ @ @ @ }Tasking    @tab pthread library
22798 @item @code{@ @ @ @ }Exceptions @tab ZCX
22800 @item @code{@ @ }@i{rts-sjlj}
22801 @item @code{@ @ @ @ }Tasking    @tab pthread library
22802 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22804 @end multitable
22806 @node Specifying a Run-Time Library
22807 @section Specifying a Run-Time Library
22809 @noindent
22810 The @file{adainclude} subdirectory containing the sources of the GNAT
22811 run-time library, and the @file{adalib} subdirectory containing the
22812 @file{ALI} files and the static and/or shared GNAT library, are located
22813 in the gcc target-dependent area:
22815 @smallexample
22816 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22817 @end smallexample
22819 @noindent
22820 As indicated above, on some platforms several run-time libraries are supplied.
22821 These libraries are installed in the target dependent area and
22822 contain a complete source and binary subdirectory. The detailed description
22823 below explains the differences between the different libraries in terms of
22824 their thread support.
22826 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22827 This default run time is selected by the means of soft links.
22828 For example on x86-linux:
22830 @smallexample
22831 @group
22832  $(target-dir)
22833      |
22834      +--- adainclude----------+
22835      |                        |
22836      +--- adalib-----------+  |
22837      |                     |  |
22838      +--- rts-native       |  |
22839      |    |                |  |
22840      |    +--- adainclude <---+
22841      |    |                |
22842      |    +--- adalib <----+
22843      |
22844      +--- rts-sjlj
22845           |
22846           +--- adainclude
22847           |
22848           +--- adalib
22849 @end group
22850 @end smallexample
22852 @noindent
22853 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22854 these soft links can be modified with the following commands:
22856 @smallexample
22857 $ cd $target
22858 $ rm -f adainclude adalib
22859 $ ln -s rts-sjlj/adainclude adainclude
22860 $ ln -s rts-sjlj/adalib adalib
22861 @end smallexample
22863 @noindent
22864 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22865 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22866 @file{$target/ada_object_path}.
22868 Selecting another run-time library temporarily can be
22869 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22870 @cindex @option{--RTS} option
22872 @node Choosing the Scheduling Policy
22873 @section Choosing the Scheduling Policy
22875 @noindent
22876 When using a POSIX threads implementation, you have a choice of several
22877 scheduling policies: @code{SCHED_FIFO},
22878 @cindex @code{SCHED_FIFO} scheduling policy
22879 @code{SCHED_RR}
22880 @cindex @code{SCHED_RR} scheduling policy
22881 and @code{SCHED_OTHER}.
22882 @cindex @code{SCHED_OTHER} scheduling policy
22883 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22884 or @code{SCHED_RR} requires special (e.g., root) privileges.
22886 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22887 @code{SCHED_FIFO},
22888 @cindex @code{SCHED_FIFO} scheduling policy
22889 you can use one of the following:
22891 @itemize @bullet
22892 @item
22893 @code{pragma Time_Slice (0.0)}
22894 @cindex pragma Time_Slice
22895 @item
22896 the corresponding binder option @option{-T0}
22897 @cindex @option{-T0} option
22898 @item
22899 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22900 @cindex pragma Task_Dispatching_Policy
22901 @end itemize
22903 @noindent
22904 To specify @code{SCHED_RR},
22905 @cindex @code{SCHED_RR} scheduling policy
22906 you should use @code{pragma Time_Slice} with a
22907 value greater than @code{0.0}, or else use the corresponding @option{-T}
22908 binder option.
22910 @node Solaris-Specific Considerations
22911 @section Solaris-Specific Considerations
22912 @cindex Solaris Sparc threads libraries
22914 @noindent
22915 This section addresses some topics related to the various threads libraries
22916 on Sparc Solaris.
22918 @menu
22919 * Solaris Threads Issues::
22920 @end menu
22922 @node Solaris Threads Issues
22923 @subsection Solaris Threads Issues
22925 @noindent
22926 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22927 library based on POSIX threads --- @emph{rts-pthread}.
22928 @cindex rts-pthread threads library
22929 This run-time library has the advantage of being mostly shared across all
22930 POSIX-compliant thread implementations, and it also provides under
22931 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22932 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22933 and @code{PTHREAD_PRIO_PROTECT}
22934 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22935 semantics that can be selected using the predefined pragma
22936 @code{Locking_Policy}
22937 @cindex pragma Locking_Policy (under rts-pthread)
22938 with respectively
22939 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22940 @cindex @code{Inheritance_Locking} (under rts-pthread)
22941 @cindex @code{Ceiling_Locking} (under rts-pthread)
22943 As explained above, the native run-time library is based on the Solaris thread
22944 library (@code{libthread}) and is the default library.
22946 When the Solaris threads library is used (this is the default), programs
22947 compiled with GNAT can automatically take advantage of
22948 and can thus execute on multiple processors.
22949 The user can alternatively specify a processor on which the program should run
22950 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22951 is made by
22952 setting the environment variable @env{GNAT_PROCESSOR}
22953 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22954 to one of the following:
22956 @table @code
22957 @item -2
22958 Use the default configuration (run the program on all
22959 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22960 unset
22962 @item -1
22963 Let the run-time implementation choose one processor and run the program on
22964 that processor
22966 @item 0 .. Last_Proc
22967 Run the program on the specified processor.
22968 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22969 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22970 @end table
22972 @node Linux-Specific Considerations
22973 @section Linux-Specific Considerations
22974 @cindex Linux threads libraries
22976 @noindent
22977 On GNU/Linux without NPTL support (usually system with GNU C Library
22978 older than 2.3), the signal model is not POSIX compliant, which means
22979 that to send a signal to the process, you need to send the signal to all
22980 threads, e.g.@: by using @code{killpg()}.
22982 @node AIX-Specific Considerations
22983 @section AIX-Specific Considerations
22984 @cindex AIX resolver library
22986 @noindent
22987 On AIX, the resolver library initializes some internal structure on
22988 the first call to @code{get*by*} functions, which are used to implement
22989 @code{GNAT.Sockets.Get_Host_By_Name} and
22990 @code{GNAT.Sockets.Get_Host_By_Address}.
22991 If such initialization occurs within an Ada task, and the stack size for
22992 the task is the default size, a stack overflow may occur.
22994 To avoid this overflow, the user should either ensure that the first call
22995 to @code{GNAT.Sockets.Get_Host_By_Name} or
22996 @code{GNAT.Sockets.Get_Host_By_Addrss}
22997 occurs in the environment task, or use @code{pragma Storage_Size} to
22998 specify a sufficiently large size for the stack of the task that contains
22999 this call.
23001 @node RTX-Specific Considerations
23002 @section RTX-Specific Considerations
23003 @cindex RTX libraries
23005 @noindent
23006 The Real-time Extension (RTX) to Windows is based on the Windows Win32
23007 API. Applications can be built to work in two different modes:
23009 @itemize @bullet
23010 @item
23011 Windows executables that run in Ring 3 to utilize memory protection
23012 (@emph{rts-rtx-w32}).
23014 @item
23015 Real-time subsystem (RTSS) executables that run in Ring 0, where
23016 performance can be optimized with RTSS applications taking precedent
23017 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
23018 the Microsoft linker to handle RTSS libraries.
23020 @end itemize
23022 @node HP-UX-Specific Considerations
23023 @section HP-UX-Specific Considerations
23024 @cindex HP-UX Scheduling
23026 @noindent
23027 On HP-UX, appropriate privileges are required to change the scheduling
23028 parameters of a task. The calling process must have appropriate
23029 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
23030 successfully change the scheduling parameters.
23032 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
23033 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
23034 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
23036 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
23037 one of the following:
23039 @itemize @bullet
23040 @item
23041 @code{pragma Time_Slice (0.0)}
23042 @cindex pragma Time_Slice
23043 @item
23044 the corresponding binder option @option{-T0}
23045 @cindex @option{-T0} option
23046 @item
23047 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23048 @cindex pragma Task_Dispatching_Policy
23049 @end itemize
23051 @noindent
23052 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
23053 you should use @code{pragma Time_Slice} with a
23054 value greater than @code{0.0}, or use the corresponding @option{-T}
23055 binder option, or set the @code{pragma Task_Dispatching_Policy
23056 (Round_Robin_Within_Priorities)}.
23058 @c *******************************
23059 @node Example of Binder Output File
23060 @appendix Example of Binder Output File
23062 @noindent
23063 This Appendix displays the source code for @command{gnatbind}'s output
23064 file generated for a simple ``Hello World'' program.
23065 Comments have been added for clarification purposes.
23067 @smallexample @c adanocomment
23068 @iftex
23069 @leftskip=0cm
23070 @end iftex
23071 --  The package is called Ada_Main unless this name is actually used
23072 --  as a unit name in the partition, in which case some other unique
23073 --  name is used.
23075 with System;
23076 package ada_main is
23078    Elab_Final_Code : Integer;
23079    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
23081    --  The main program saves the parameters (argument count,
23082    --  argument values, environment pointer) in global variables
23083    --  for later access by other units including
23084    --  Ada.Command_Line.
23086    gnat_argc : Integer;
23087    gnat_argv : System.Address;
23088    gnat_envp : System.Address;
23090    --  The actual variables are stored in a library routine. This
23091    --  is useful for some shared library situations, where there
23092    --  are problems if variables are not in the library.
23094    pragma Import (C, gnat_argc);
23095    pragma Import (C, gnat_argv);
23096    pragma Import (C, gnat_envp);
23098    --  The exit status is similarly an external location
23100    gnat_exit_status : Integer;
23101    pragma Import (C, gnat_exit_status);
23103    GNAT_Version : constant String :=
23104                     "GNAT Version: 6.0.0w (20061115)";
23105    pragma Export (C, GNAT_Version, "__gnat_version");
23107    --  This is the generated adafinal routine that performs
23108    --  finalization at the end of execution. In the case where
23109    --  Ada is the main program, this main program makes a call
23110    --  to adafinal at program termination.
23112    procedure adafinal;
23113    pragma Export (C, adafinal, "adafinal");
23115    --  This is the generated adainit routine that performs
23116    --  initialization at the start of execution. In the case
23117    --  where Ada is the main program, this main program makes
23118    --  a call to adainit at program startup.
23120    procedure adainit;
23121    pragma Export (C, adainit, "adainit");
23123    --  This routine is called at the start of execution. It is
23124    --  a dummy routine that is used by the debugger to breakpoint
23125    --  at the start of execution.
23127    procedure Break_Start;
23128    pragma Import (C, Break_Start, "__gnat_break_start");
23130    --  This is the actual generated main program (it would be
23131    --  suppressed if the no main program switch were used). As
23132    --  required by standard system conventions, this program has
23133    --  the external name main.
23135    function main
23136      (argc : Integer;
23137       argv : System.Address;
23138       envp : System.Address)
23139       return Integer;
23140    pragma Export (C, main, "main");
23142    --  The following set of constants give the version
23143    --  identification values for every unit in the bound
23144    --  partition. This identification is computed from all
23145    --  dependent semantic units, and corresponds to the
23146    --  string that would be returned by use of the
23147    --  Body_Version or Version attributes.
23149    type Version_32 is mod 2 ** 32;
23150    u00001 : constant Version_32 := 16#7880BEB3#;
23151    u00002 : constant Version_32 := 16#0D24CBD0#;
23152    u00003 : constant Version_32 := 16#3283DBEB#;
23153    u00004 : constant Version_32 := 16#2359F9ED#;
23154    u00005 : constant Version_32 := 16#664FB847#;
23155    u00006 : constant Version_32 := 16#68E803DF#;
23156    u00007 : constant Version_32 := 16#5572E604#;
23157    u00008 : constant Version_32 := 16#46B173D8#;
23158    u00009 : constant Version_32 := 16#156A40CF#;
23159    u00010 : constant Version_32 := 16#033DABE0#;
23160    u00011 : constant Version_32 := 16#6AB38FEA#;
23161    u00012 : constant Version_32 := 16#22B6217D#;
23162    u00013 : constant Version_32 := 16#68A22947#;
23163    u00014 : constant Version_32 := 16#18CC4A56#;
23164    u00015 : constant Version_32 := 16#08258E1B#;
23165    u00016 : constant Version_32 := 16#367D5222#;
23166    u00017 : constant Version_32 := 16#20C9ECA4#;
23167    u00018 : constant Version_32 := 16#50D32CB6#;
23168    u00019 : constant Version_32 := 16#39A8BB77#;
23169    u00020 : constant Version_32 := 16#5CF8FA2B#;
23170    u00021 : constant Version_32 := 16#2F1EB794#;
23171    u00022 : constant Version_32 := 16#31AB6444#;
23172    u00023 : constant Version_32 := 16#1574B6E9#;
23173    u00024 : constant Version_32 := 16#5109C189#;
23174    u00025 : constant Version_32 := 16#56D770CD#;
23175    u00026 : constant Version_32 := 16#02F9DE3D#;
23176    u00027 : constant Version_32 := 16#08AB6B2C#;
23177    u00028 : constant Version_32 := 16#3FA37670#;
23178    u00029 : constant Version_32 := 16#476457A0#;
23179    u00030 : constant Version_32 := 16#731E1B6E#;
23180    u00031 : constant Version_32 := 16#23C2E789#;
23181    u00032 : constant Version_32 := 16#0F1BD6A1#;
23182    u00033 : constant Version_32 := 16#7C25DE96#;
23183    u00034 : constant Version_32 := 16#39ADFFA2#;
23184    u00035 : constant Version_32 := 16#571DE3E7#;
23185    u00036 : constant Version_32 := 16#5EB646AB#;
23186    u00037 : constant Version_32 := 16#4249379B#;
23187    u00038 : constant Version_32 := 16#0357E00A#;
23188    u00039 : constant Version_32 := 16#3784FB72#;
23189    u00040 : constant Version_32 := 16#2E723019#;
23190    u00041 : constant Version_32 := 16#623358EA#;
23191    u00042 : constant Version_32 := 16#107F9465#;
23192    u00043 : constant Version_32 := 16#6843F68A#;
23193    u00044 : constant Version_32 := 16#63305874#;
23194    u00045 : constant Version_32 := 16#31E56CE1#;
23195    u00046 : constant Version_32 := 16#02917970#;
23196    u00047 : constant Version_32 := 16#6CCBA70E#;
23197    u00048 : constant Version_32 := 16#41CD4204#;
23198    u00049 : constant Version_32 := 16#572E3F58#;
23199    u00050 : constant Version_32 := 16#20729FF5#;
23200    u00051 : constant Version_32 := 16#1D4F93E8#;
23201    u00052 : constant Version_32 := 16#30B2EC3D#;
23202    u00053 : constant Version_32 := 16#34054F96#;
23203    u00054 : constant Version_32 := 16#5A199860#;
23204    u00055 : constant Version_32 := 16#0E7F912B#;
23205    u00056 : constant Version_32 := 16#5760634A#;
23206    u00057 : constant Version_32 := 16#5D851835#;
23208    --  The following Export pragmas export the version numbers
23209    --  with symbolic names ending in B (for body) or S
23210    --  (for spec) so that they can be located in a link. The
23211    --  information provided here is sufficient to track down
23212    --  the exact versions of units used in a given build.
23214    pragma Export (C, u00001, "helloB");
23215    pragma Export (C, u00002, "system__standard_libraryB");
23216    pragma Export (C, u00003, "system__standard_libraryS");
23217    pragma Export (C, u00004, "adaS");
23218    pragma Export (C, u00005, "ada__text_ioB");
23219    pragma Export (C, u00006, "ada__text_ioS");
23220    pragma Export (C, u00007, "ada__exceptionsB");
23221    pragma Export (C, u00008, "ada__exceptionsS");
23222    pragma Export (C, u00009, "gnatS");
23223    pragma Export (C, u00010, "gnat__heap_sort_aB");
23224    pragma Export (C, u00011, "gnat__heap_sort_aS");
23225    pragma Export (C, u00012, "systemS");
23226    pragma Export (C, u00013, "system__exception_tableB");
23227    pragma Export (C, u00014, "system__exception_tableS");
23228    pragma Export (C, u00015, "gnat__htableB");
23229    pragma Export (C, u00016, "gnat__htableS");
23230    pragma Export (C, u00017, "system__exceptionsS");
23231    pragma Export (C, u00018, "system__machine_state_operationsB");
23232    pragma Export (C, u00019, "system__machine_state_operationsS");
23233    pragma Export (C, u00020, "system__machine_codeS");
23234    pragma Export (C, u00021, "system__storage_elementsB");
23235    pragma Export (C, u00022, "system__storage_elementsS");
23236    pragma Export (C, u00023, "system__secondary_stackB");
23237    pragma Export (C, u00024, "system__secondary_stackS");
23238    pragma Export (C, u00025, "system__parametersB");
23239    pragma Export (C, u00026, "system__parametersS");
23240    pragma Export (C, u00027, "system__soft_linksB");
23241    pragma Export (C, u00028, "system__soft_linksS");
23242    pragma Export (C, u00029, "system__stack_checkingB");
23243    pragma Export (C, u00030, "system__stack_checkingS");
23244    pragma Export (C, u00031, "system__tracebackB");
23245    pragma Export (C, u00032, "system__tracebackS");
23246    pragma Export (C, u00033, "ada__streamsS");
23247    pragma Export (C, u00034, "ada__tagsB");
23248    pragma Export (C, u00035, "ada__tagsS");
23249    pragma Export (C, u00036, "system__string_opsB");
23250    pragma Export (C, u00037, "system__string_opsS");
23251    pragma Export (C, u00038, "interfacesS");
23252    pragma Export (C, u00039, "interfaces__c_streamsB");
23253    pragma Export (C, u00040, "interfaces__c_streamsS");
23254    pragma Export (C, u00041, "system__file_ioB");
23255    pragma Export (C, u00042, "system__file_ioS");
23256    pragma Export (C, u00043, "ada__finalizationB");
23257    pragma Export (C, u00044, "ada__finalizationS");
23258    pragma Export (C, u00045, "system__finalization_rootB");
23259    pragma Export (C, u00046, "system__finalization_rootS");
23260    pragma Export (C, u00047, "system__finalization_implementationB");
23261    pragma Export (C, u00048, "system__finalization_implementationS");
23262    pragma Export (C, u00049, "system__string_ops_concat_3B");
23263    pragma Export (C, u00050, "system__string_ops_concat_3S");
23264    pragma Export (C, u00051, "system__stream_attributesB");
23265    pragma Export (C, u00052, "system__stream_attributesS");
23266    pragma Export (C, u00053, "ada__io_exceptionsS");
23267    pragma Export (C, u00054, "system__unsigned_typesS");
23268    pragma Export (C, u00055, "system__file_control_blockS");
23269    pragma Export (C, u00056, "ada__finalization__list_controllerB");
23270    pragma Export (C, u00057, "ada__finalization__list_controllerS");
23272    -- BEGIN ELABORATION ORDER
23273    -- ada (spec)
23274    -- gnat (spec)
23275    -- gnat.heap_sort_a (spec)
23276    -- gnat.heap_sort_a (body)
23277    -- gnat.htable (spec)
23278    -- gnat.htable (body)
23279    -- interfaces (spec)
23280    -- system (spec)
23281    -- system.machine_code (spec)
23282    -- system.parameters (spec)
23283    -- system.parameters (body)
23284    -- interfaces.c_streams (spec)
23285    -- interfaces.c_streams (body)
23286    -- system.standard_library (spec)
23287    -- ada.exceptions (spec)
23288    -- system.exception_table (spec)
23289    -- system.exception_table (body)
23290    -- ada.io_exceptions (spec)
23291    -- system.exceptions (spec)
23292    -- system.storage_elements (spec)
23293    -- system.storage_elements (body)
23294    -- system.machine_state_operations (spec)
23295    -- system.machine_state_operations (body)
23296    -- system.secondary_stack (spec)
23297    -- system.stack_checking (spec)
23298    -- system.soft_links (spec)
23299    -- system.soft_links (body)
23300    -- system.stack_checking (body)
23301    -- system.secondary_stack (body)
23302    -- system.standard_library (body)
23303    -- system.string_ops (spec)
23304    -- system.string_ops (body)
23305    -- ada.tags (spec)
23306    -- ada.tags (body)
23307    -- ada.streams (spec)
23308    -- system.finalization_root (spec)
23309    -- system.finalization_root (body)
23310    -- system.string_ops_concat_3 (spec)
23311    -- system.string_ops_concat_3 (body)
23312    -- system.traceback (spec)
23313    -- system.traceback (body)
23314    -- ada.exceptions (body)
23315    -- system.unsigned_types (spec)
23316    -- system.stream_attributes (spec)
23317    -- system.stream_attributes (body)
23318    -- system.finalization_implementation (spec)
23319    -- system.finalization_implementation (body)
23320    -- ada.finalization (spec)
23321    -- ada.finalization (body)
23322    -- ada.finalization.list_controller (spec)
23323    -- ada.finalization.list_controller (body)
23324    -- system.file_control_block (spec)
23325    -- system.file_io (spec)
23326    -- system.file_io (body)
23327    -- ada.text_io (spec)
23328    -- ada.text_io (body)
23329    -- hello (body)
23330    -- END ELABORATION ORDER
23332 end ada_main;
23334 --  The following source file name pragmas allow the generated file
23335 --  names to be unique for different main programs. They are needed
23336 --  since the package name will always be Ada_Main.
23338 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
23339 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
23341 --  Generated package body for Ada_Main starts here
23343 package body ada_main is
23345    --  The actual finalization is performed by calling the
23346    --  library routine in System.Standard_Library.Adafinal
23348    procedure Do_Finalize;
23349    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
23351    -------------
23352    -- adainit --
23353    -------------
23355 @findex adainit
23356    procedure adainit is
23358       --  These booleans are set to True once the associated unit has
23359       --  been elaborated. It is also used to avoid elaborating the
23360       --  same unit twice.
23362       E040 : Boolean;
23363       pragma Import (Ada, E040, "interfaces__c_streams_E");
23365       E008 : Boolean;
23366       pragma Import (Ada, E008, "ada__exceptions_E");
23368       E014 : Boolean;
23369       pragma Import (Ada, E014, "system__exception_table_E");
23371       E053 : Boolean;
23372       pragma Import (Ada, E053, "ada__io_exceptions_E");
23374       E017 : Boolean;
23375       pragma Import (Ada, E017, "system__exceptions_E");
23377       E024 : Boolean;
23378       pragma Import (Ada, E024, "system__secondary_stack_E");
23380       E030 : Boolean;
23381       pragma Import (Ada, E030, "system__stack_checking_E");
23383       E028 : Boolean;
23384       pragma Import (Ada, E028, "system__soft_links_E");
23386       E035 : Boolean;
23387       pragma Import (Ada, E035, "ada__tags_E");
23389       E033 : Boolean;
23390       pragma Import (Ada, E033, "ada__streams_E");
23392       E046 : Boolean;
23393       pragma Import (Ada, E046, "system__finalization_root_E");
23395       E048 : Boolean;
23396       pragma Import (Ada, E048, "system__finalization_implementation_E");
23398       E044 : Boolean;
23399       pragma Import (Ada, E044, "ada__finalization_E");
23401       E057 : Boolean;
23402       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23404       E055 : Boolean;
23405       pragma Import (Ada, E055, "system__file_control_block_E");
23407       E042 : Boolean;
23408       pragma Import (Ada, E042, "system__file_io_E");
23410       E006 : Boolean;
23411       pragma Import (Ada, E006, "ada__text_io_E");
23413       --  Set_Globals is a library routine that stores away the
23414       --  value of the indicated set of global values in global
23415       --  variables within the library.
23417       procedure Set_Globals
23418         (Main_Priority            : Integer;
23419          Time_Slice_Value         : Integer;
23420          WC_Encoding              : Character;
23421          Locking_Policy           : Character;
23422          Queuing_Policy           : Character;
23423          Task_Dispatching_Policy  : Character;
23424          Adafinal                 : System.Address;
23425          Unreserve_All_Interrupts : Integer;
23426          Exception_Tracebacks     : Integer);
23427 @findex __gnat_set_globals
23428       pragma Import (C, Set_Globals, "__gnat_set_globals");
23430       --  SDP_Table_Build is a library routine used to build the
23431       --  exception tables. See unit Ada.Exceptions in files
23432       --  a-except.ads/adb for full details of how zero cost
23433       --  exception handling works. This procedure, the call to
23434       --  it, and the two following tables are all omitted if the
23435       --  build is in longjmp/setjmp exception mode.
23437 @findex SDP_Table_Build
23438 @findex Zero Cost Exceptions
23439       procedure SDP_Table_Build
23440         (SDP_Addresses   : System.Address;
23441          SDP_Count       : Natural;
23442          Elab_Addresses  : System.Address;
23443          Elab_Addr_Count : Natural);
23444       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
23446       --  Table of Unit_Exception_Table addresses. Used for zero
23447       --  cost exception handling to build the top level table.
23449       ST : aliased constant array (1 .. 23) of System.Address := (
23450         Hello'UET_Address,
23451         Ada.Text_Io'UET_Address,
23452         Ada.Exceptions'UET_Address,
23453         Gnat.Heap_Sort_A'UET_Address,
23454         System.Exception_Table'UET_Address,
23455         System.Machine_State_Operations'UET_Address,
23456         System.Secondary_Stack'UET_Address,
23457         System.Parameters'UET_Address,
23458         System.Soft_Links'UET_Address,
23459         System.Stack_Checking'UET_Address,
23460         System.Traceback'UET_Address,
23461         Ada.Streams'UET_Address,
23462         Ada.Tags'UET_Address,
23463         System.String_Ops'UET_Address,
23464         Interfaces.C_Streams'UET_Address,
23465         System.File_Io'UET_Address,
23466         Ada.Finalization'UET_Address,
23467         System.Finalization_Root'UET_Address,
23468         System.Finalization_Implementation'UET_Address,
23469         System.String_Ops_Concat_3'UET_Address,
23470         System.Stream_Attributes'UET_Address,
23471         System.File_Control_Block'UET_Address,
23472         Ada.Finalization.List_Controller'UET_Address);
23474       --  Table of addresses of elaboration routines. Used for
23475       --  zero cost exception handling to make sure these
23476       --  addresses are included in the top level procedure
23477       --  address table.
23479       EA : aliased constant array (1 .. 23) of System.Address := (
23480         adainit'Code_Address,
23481         Do_Finalize'Code_Address,
23482         Ada.Exceptions'Elab_Spec'Address,
23483         System.Exceptions'Elab_Spec'Address,
23484         Interfaces.C_Streams'Elab_Spec'Address,
23485         System.Exception_Table'Elab_Body'Address,
23486         Ada.Io_Exceptions'Elab_Spec'Address,
23487         System.Stack_Checking'Elab_Spec'Address,
23488         System.Soft_Links'Elab_Body'Address,
23489         System.Secondary_Stack'Elab_Body'Address,
23490         Ada.Tags'Elab_Spec'Address,
23491         Ada.Tags'Elab_Body'Address,
23492         Ada.Streams'Elab_Spec'Address,
23493         System.Finalization_Root'Elab_Spec'Address,
23494         Ada.Exceptions'Elab_Body'Address,
23495         System.Finalization_Implementation'Elab_Spec'Address,
23496         System.Finalization_Implementation'Elab_Body'Address,
23497         Ada.Finalization'Elab_Spec'Address,
23498         Ada.Finalization.List_Controller'Elab_Spec'Address,
23499         System.File_Control_Block'Elab_Spec'Address,
23500         System.File_Io'Elab_Body'Address,
23501         Ada.Text_Io'Elab_Spec'Address,
23502         Ada.Text_Io'Elab_Body'Address);
23504    --  Start of processing for adainit
23506    begin
23508       --  Call SDP_Table_Build to build the top level procedure
23509       --  table for zero cost exception handling (omitted in
23510       --  longjmp/setjmp mode).
23512       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23514       --  Call Set_Globals to record various information for
23515       --  this partition.  The values are derived by the binder
23516       --  from information stored in the ali files by the compiler.
23518 @findex __gnat_set_globals
23519       Set_Globals
23520         (Main_Priority            => -1,
23521          --  Priority of main program, -1 if no pragma Priority used
23523          Time_Slice_Value         => -1,
23524          --  Time slice from Time_Slice pragma, -1 if none used
23526          WC_Encoding              => 'b',
23527          --  Wide_Character encoding used, default is brackets
23529          Locking_Policy           => ' ',
23530          --  Locking_Policy used, default of space means not
23531          --  specified, otherwise it is the first character of
23532          --  the policy name.
23534          Queuing_Policy           => ' ',
23535          --  Queuing_Policy used, default of space means not
23536          --  specified, otherwise it is the first character of
23537          --  the policy name.
23539          Task_Dispatching_Policy  => ' ',
23540          --  Task_Dispatching_Policy used, default of space means
23541          --  not specified, otherwise first character of the
23542          --  policy name.
23544          Adafinal                 => System.Null_Address,
23545          --  Address of Adafinal routine, not used anymore
23547          Unreserve_All_Interrupts => 0,
23548          --  Set true if pragma Unreserve_All_Interrupts was used
23550          Exception_Tracebacks     => 0);
23551          --  Indicates if exception tracebacks are enabled
23553       Elab_Final_Code := 1;
23555       --  Now we have the elaboration calls for all units in the partition.
23556       --  The Elab_Spec and Elab_Body attributes generate references to the
23557       --  implicit elaboration procedures generated by the compiler for
23558       --  each unit that requires elaboration.
23560       if not E040 then
23561          Interfaces.C_Streams'Elab_Spec;
23562       end if;
23563       E040 := True;
23564       if not E008 then
23565          Ada.Exceptions'Elab_Spec;
23566       end if;
23567       if not E014 then
23568          System.Exception_Table'Elab_Body;
23569          E014 := True;
23570       end if;
23571       if not E053 then
23572          Ada.Io_Exceptions'Elab_Spec;
23573          E053 := True;
23574       end if;
23575       if not E017 then
23576          System.Exceptions'Elab_Spec;
23577          E017 := True;
23578       end if;
23579       if not E030 then
23580          System.Stack_Checking'Elab_Spec;
23581       end if;
23582       if not E028 then
23583          System.Soft_Links'Elab_Body;
23584          E028 := True;
23585       end if;
23586       E030 := True;
23587       if not E024 then
23588          System.Secondary_Stack'Elab_Body;
23589          E024 := True;
23590       end if;
23591       if not E035 then
23592          Ada.Tags'Elab_Spec;
23593       end if;
23594       if not E035 then
23595          Ada.Tags'Elab_Body;
23596          E035 := True;
23597       end if;
23598       if not E033 then
23599          Ada.Streams'Elab_Spec;
23600          E033 := True;
23601       end if;
23602       if not E046 then
23603          System.Finalization_Root'Elab_Spec;
23604       end if;
23605       E046 := True;
23606       if not E008 then
23607          Ada.Exceptions'Elab_Body;
23608          E008 := True;
23609       end if;
23610       if not E048 then
23611          System.Finalization_Implementation'Elab_Spec;
23612       end if;
23613       if not E048 then
23614          System.Finalization_Implementation'Elab_Body;
23615          E048 := True;
23616       end if;
23617       if not E044 then
23618          Ada.Finalization'Elab_Spec;
23619       end if;
23620       E044 := True;
23621       if not E057 then
23622          Ada.Finalization.List_Controller'Elab_Spec;
23623       end if;
23624       E057 := True;
23625       if not E055 then
23626          System.File_Control_Block'Elab_Spec;
23627          E055 := True;
23628       end if;
23629       if not E042 then
23630          System.File_Io'Elab_Body;
23631          E042 := True;
23632       end if;
23633       if not E006 then
23634          Ada.Text_Io'Elab_Spec;
23635       end if;
23636       if not E006 then
23637          Ada.Text_Io'Elab_Body;
23638          E006 := True;
23639       end if;
23641       Elab_Final_Code := 0;
23642    end adainit;
23644    --------------
23645    -- adafinal --
23646    --------------
23648 @findex adafinal
23649    procedure adafinal is
23650    begin
23651       Do_Finalize;
23652    end adafinal;
23654    ----------
23655    -- main --
23656    ----------
23658    --  main is actually a function, as in the ANSI C standard,
23659    --  defined to return the exit status. The three parameters
23660    --  are the argument count, argument values and environment
23661    --  pointer.
23663 @findex Main Program
23664    function main
23665      (argc : Integer;
23666       argv : System.Address;
23667       envp : System.Address)
23668       return Integer
23669    is
23670       --  The initialize routine performs low level system
23671       --  initialization using a standard library routine which
23672       --  sets up signal handling and performs any other
23673       --  required setup. The routine can be found in file
23674       --  a-init.c.
23676 @findex __gnat_initialize
23677       procedure initialize;
23678       pragma Import (C, initialize, "__gnat_initialize");
23680       --  The finalize routine performs low level system
23681       --  finalization using a standard library routine. The
23682       --  routine is found in file a-final.c and in the standard
23683       --  distribution is a dummy routine that does nothing, so
23684       --  really this is a hook for special user finalization.
23686 @findex __gnat_finalize
23687       procedure finalize;
23688       pragma Import (C, finalize, "__gnat_finalize");
23690       --  We get to the main program of the partition by using
23691       --  pragma Import because if we try to with the unit and
23692       --  call it Ada style, then not only do we waste time
23693       --  recompiling it, but also, we don't really know the right
23694       --  switches (e.g.@: identifier character set) to be used
23695       --  to compile it.
23697       procedure Ada_Main_Program;
23698       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23700    --  Start of processing for main
23702    begin
23703       --  Save global variables
23705       gnat_argc := argc;
23706       gnat_argv := argv;
23707       gnat_envp := envp;
23709       --  Call low level system initialization
23711       Initialize;
23713       --  Call our generated Ada initialization routine
23715       adainit;
23717       --  This is the point at which we want the debugger to get
23718       --  control
23720       Break_Start;
23722       --  Now we call the main program of the partition
23724       Ada_Main_Program;
23726       --  Perform Ada finalization
23728       adafinal;
23730       --  Perform low level system finalization
23732       Finalize;
23734       --  Return the proper exit status
23735       return (gnat_exit_status);
23736    end;
23738 --  This section is entirely comments, so it has no effect on the
23739 --  compilation of the Ada_Main package. It provides the list of
23740 --  object files and linker options, as well as some standard
23741 --  libraries needed for the link. The gnatlink utility parses
23742 --  this b~hello.adb file to read these comment lines to generate
23743 --  the appropriate command line arguments for the call to the
23744 --  system linker. The BEGIN/END lines are used for sentinels for
23745 --  this parsing operation.
23747 --  The exact file names will of course depend on the environment,
23748 --  host/target and location of files on the host system.
23750 @findex Object file list
23751 -- BEGIN Object file/option list
23752    --   ./hello.o
23753    --   -L./
23754    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23755    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23756 -- END Object file/option list
23758 end ada_main;
23759 @end smallexample
23761 @noindent
23762 The Ada code in the above example is exactly what is generated by the
23763 binder. We have added comments to more clearly indicate the function
23764 of each part of the generated @code{Ada_Main} package.
23766 The code is standard Ada in all respects, and can be processed by any
23767 tools that handle Ada. In particular, it is possible to use the debugger
23768 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23769 suppose that for reasons that you do not understand, your program is crashing
23770 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23771 you can place a breakpoint on the call:
23773 @smallexample @c ada
23774 Ada.Text_Io'Elab_Body;
23775 @end smallexample
23777 @noindent
23778 and trace the elaboration routine for this package to find out where
23779 the problem might be (more usually of course you would be debugging
23780 elaboration code in your own application).
23782 @node Elaboration Order Handling in GNAT
23783 @appendix Elaboration Order Handling in GNAT
23784 @cindex Order of elaboration
23785 @cindex Elaboration control
23787 @menu
23788 * Elaboration Code::
23789 * Checking the Elaboration Order::
23790 * Controlling the Elaboration Order::
23791 * Controlling Elaboration in GNAT - Internal Calls::
23792 * Controlling Elaboration in GNAT - External Calls::
23793 * Default Behavior in GNAT - Ensuring Safety::
23794 * Treatment of Pragma Elaborate::
23795 * Elaboration Issues for Library Tasks::
23796 * Mixing Elaboration Models::
23797 * What to Do If the Default Elaboration Behavior Fails::
23798 * Elaboration for Dispatching Calls::
23799 * Summary of Procedures for Elaboration Control::
23800 * Other Elaboration Order Considerations::
23801 @end menu
23803 @noindent
23804 This chapter describes the handling of elaboration code in Ada and
23805 in GNAT, and discusses how the order of elaboration of program units can
23806 be controlled in GNAT, either automatically or with explicit programming
23807 features.
23809 @node Elaboration Code
23810 @section Elaboration Code
23812 @noindent
23813 Ada provides rather general mechanisms for executing code at elaboration
23814 time, that is to say before the main program starts executing. Such code arises
23815 in three contexts:
23817 @table @asis
23818 @item Initializers for variables.
23819 Variables declared at the library level, in package specs or bodies, can
23820 require initialization that is performed at elaboration time, as in:
23821 @smallexample @c ada
23822 @cartouche
23823 Sqrt_Half : Float := Sqrt (0.5);
23824 @end cartouche
23825 @end smallexample
23827 @item Package initialization code
23828 Code in a @code{BEGIN-END} section at the outer level of a package body is
23829 executed as part of the package body elaboration code.
23831 @item Library level task allocators
23832 Tasks that are declared using task allocators at the library level
23833 start executing immediately and hence can execute at elaboration time.
23834 @end table
23836 @noindent
23837 Subprogram calls are possible in any of these contexts, which means that
23838 any arbitrary part of the program may be executed as part of the elaboration
23839 code. It is even possible to write a program which does all its work at
23840 elaboration time, with a null main program, although stylistically this
23841 would usually be considered an inappropriate way to structure
23842 a program.
23844 An important concern arises in the context of elaboration code:
23845 we have to be sure that it is executed in an appropriate order. What we
23846 have is a series of elaboration code sections, potentially one section
23847 for each unit in the program. It is important that these execute
23848 in the correct order. Correctness here means that, taking the above
23849 example of the declaration of @code{Sqrt_Half},
23850 if some other piece of
23851 elaboration code references @code{Sqrt_Half},
23852 then it must run after the
23853 section of elaboration code that contains the declaration of
23854 @code{Sqrt_Half}.
23856 There would never be any order of elaboration problem if we made a rule
23857 that whenever you @code{with} a unit, you must elaborate both the spec and body
23858 of that unit before elaborating the unit doing the @code{with}'ing:
23860 @smallexample @c ada
23861 @group
23862 @cartouche
23863 with Unit_1;
23864 package Unit_2 is @dots{}
23865 @end cartouche
23866 @end group
23867 @end smallexample
23869 @noindent
23870 would require that both the body and spec of @code{Unit_1} be elaborated
23871 before the spec of @code{Unit_2}. However, a rule like that would be far too
23872 restrictive. In particular, it would make it impossible to have routines
23873 in separate packages that were mutually recursive.
23875 You might think that a clever enough compiler could look at the actual
23876 elaboration code and determine an appropriate correct order of elaboration,
23877 but in the general case, this is not possible. Consider the following
23878 example.
23880 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23881 that references
23882 the variable @code{Sqrt_1}, which is declared in the elaboration code
23883 of the body of @code{Unit_1}:
23885 @smallexample @c ada
23886 @cartouche
23887 Sqrt_1 : Float := Sqrt (0.1);
23888 @end cartouche
23889 @end smallexample
23891 @noindent
23892 The elaboration code of the body of @code{Unit_1} also contains:
23894 @smallexample @c ada
23895 @group
23896 @cartouche
23897 if expression_1 = 1 then
23898    Q := Unit_2.Func_2;
23899 end if;
23900 @end cartouche
23901 @end group
23902 @end smallexample
23904 @noindent
23905 @code{Unit_2} is exactly parallel,
23906 it has a procedure @code{Func_2} that references
23907 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23908 the body @code{Unit_2}:
23910 @smallexample @c ada
23911 @cartouche
23912 Sqrt_2 : Float := Sqrt (0.1);
23913 @end cartouche
23914 @end smallexample
23916 @noindent
23917 The elaboration code of the body of @code{Unit_2} also contains:
23919 @smallexample @c ada
23920 @group
23921 @cartouche
23922 if expression_2 = 2 then
23923    Q := Unit_1.Func_1;
23924 end if;
23925 @end cartouche
23926 @end group
23927 @end smallexample
23929 @noindent
23930 Now the question is, which of the following orders of elaboration is
23931 acceptable:
23933 @smallexample
23934 @group
23935 Spec of Unit_1
23936 Spec of Unit_2
23937 Body of Unit_1
23938 Body of Unit_2
23939 @end group
23940 @end smallexample
23942 @noindent
23945 @smallexample
23946 @group
23947 Spec of Unit_2
23948 Spec of Unit_1
23949 Body of Unit_2
23950 Body of Unit_1
23951 @end group
23952 @end smallexample
23954 @noindent
23955 If you carefully analyze the flow here, you will see that you cannot tell
23956 at compile time the answer to this question.
23957 If @code{expression_1} is not equal to 1,
23958 and @code{expression_2} is not equal to 2,
23959 then either order is acceptable, because neither of the function calls is
23960 executed. If both tests evaluate to true, then neither order is acceptable
23961 and in fact there is no correct order.
23963 If one of the two expressions is true, and the other is false, then one
23964 of the above orders is correct, and the other is incorrect. For example,
23965 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23966 then the call to @code{Func_1}
23967 will occur, but not the call to @code{Func_2.}
23968 This means that it is essential
23969 to elaborate the body of @code{Unit_1} before
23970 the body of @code{Unit_2}, so the first
23971 order of elaboration is correct and the second is wrong.
23973 By making @code{expression_1} and @code{expression_2}
23974 depend on input data, or perhaps
23975 the time of day, we can make it impossible for the compiler or binder
23976 to figure out which of these expressions will be true, and hence it
23977 is impossible to guarantee a safe order of elaboration at run time.
23979 @node Checking the Elaboration Order
23980 @section Checking the Elaboration Order
23982 @noindent
23983 In some languages that involve the same kind of elaboration problems,
23984 e.g.@: Java and C++, the programmer is expected to worry about these
23985 ordering problems himself, and it is common to
23986 write a program in which an incorrect elaboration order  gives
23987 surprising results, because it references variables before they
23988 are initialized.
23989 Ada is designed to be a safe language, and a programmer-beware approach is
23990 clearly not sufficient. Consequently, the language provides three lines
23991 of defense:
23993 @table @asis
23994 @item Standard rules
23995 Some standard rules restrict the possible choice of elaboration
23996 order. In particular, if you @code{with} a unit, then its spec is always
23997 elaborated before the unit doing the @code{with}. Similarly, a parent
23998 spec is always elaborated before the child spec, and finally
23999 a spec is always elaborated before its corresponding body.
24001 @item Dynamic elaboration checks
24002 @cindex Elaboration checks
24003 @cindex Checks, elaboration
24004 Dynamic checks are made at run time, so that if some entity is accessed
24005 before it is elaborated (typically  by means of a subprogram call)
24006 then the exception (@code{Program_Error}) is raised.
24008 @item Elaboration control
24009 Facilities are provided for the programmer to specify the desired order
24010 of elaboration.
24011 @end table
24013 Let's look at these facilities in more detail. First, the rules for
24014 dynamic checking. One possible rule would be simply to say that the
24015 exception is raised if you access a variable which has not yet been
24016 elaborated. The trouble with this approach is that it could require
24017 expensive checks on every variable reference. Instead Ada has two
24018 rules which are a little more restrictive, but easier to check, and
24019 easier to state:
24021 @table @asis
24022 @item Restrictions on calls
24023 A subprogram can only be called at elaboration time if its body
24024 has been elaborated. The rules for elaboration given above guarantee
24025 that the spec of the subprogram has been elaborated before the
24026 call, but not the body. If this rule is violated, then the
24027 exception @code{Program_Error} is raised.
24029 @item Restrictions on instantiations
24030 A generic unit can only be instantiated if the body of the generic
24031 unit has been elaborated. Again, the rules for elaboration given above
24032 guarantee that the spec of the generic unit has been elaborated
24033 before the instantiation, but not the body. If this rule is
24034 violated, then the exception @code{Program_Error} is raised.
24035 @end table
24037 @noindent
24038 The idea is that if the body has been elaborated, then any variables
24039 it references must have been elaborated; by checking for the body being
24040 elaborated we guarantee that none of its references causes any
24041 trouble. As we noted above, this is a little too restrictive, because a
24042 subprogram that has no non-local references in its body may in fact be safe
24043 to call. However, it really would be unsafe to rely on this, because
24044 it would mean that the caller was aware of details of the implementation
24045 in the body. This goes against the basic tenets of Ada.
24047 A plausible implementation can be described as follows.
24048 A Boolean variable is associated with each subprogram
24049 and each generic unit. This variable is initialized to False, and is set to
24050 True at the point body is elaborated. Every call or instantiation checks the
24051 variable, and raises @code{Program_Error} if the variable is False.
24053 Note that one might think that it would be good enough to have one Boolean
24054 variable for each package, but that would not deal with cases of trying
24055 to call a body in the same package as the call
24056 that has not been elaborated yet.
24057 Of course a compiler may be able to do enough analysis to optimize away
24058 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24059 does such optimizations, but still the easiest conceptual model is to
24060 think of there being one variable per subprogram.
24062 @node Controlling the Elaboration Order
24063 @section Controlling the Elaboration Order
24065 @noindent
24066 In the previous section we discussed the rules in Ada which ensure
24067 that @code{Program_Error} is raised if an incorrect elaboration order is
24068 chosen. This prevents erroneous executions, but we need mechanisms to
24069 specify a correct execution and avoid the exception altogether.
24070 To achieve this, Ada provides a number of features for controlling
24071 the order of elaboration. We discuss these features in this section.
24073 First, there are several ways of indicating to the compiler that a given
24074 unit has no elaboration problems:
24076 @table @asis
24077 @item packages that do not require a body
24078 A library package that does not require a body does not permit
24079 a body (this rule was introduced in Ada 95).
24080 Thus if we have a such a package, as in:
24082 @smallexample @c ada
24083 @group
24084 @cartouche
24085 package Definitions is
24086    generic
24087       type m is new integer;
24088    package Subp is
24089       type a is array (1 .. 10) of m;
24090       type b is array (1 .. 20) of m;
24091    end Subp;
24092 end Definitions;
24093 @end cartouche
24094 @end group
24095 @end smallexample
24097 @noindent
24098 A package that @code{with}'s @code{Definitions} may safely instantiate
24099 @code{Definitions.Subp} because the compiler can determine that there
24100 definitely is no package body to worry about in this case
24102 @item pragma Pure
24103 @cindex pragma Pure
24104 @findex Pure
24105 Places sufficient restrictions on a unit to guarantee that
24106 no call to any subprogram in the unit can result in an
24107 elaboration problem. This means that the compiler does not need
24108 to worry about the point of elaboration of such units, and in
24109 particular, does not need to check any calls to any subprograms
24110 in this unit.
24112 @item pragma Preelaborate
24113 @findex Preelaborate
24114 @cindex pragma Preelaborate
24115 This pragma places slightly less stringent restrictions on a unit than
24116 does pragma Pure,
24117 but these restrictions are still sufficient to ensure that there
24118 are no elaboration problems with any calls to the unit.
24120 @item pragma Elaborate_Body
24121 @findex Elaborate_Body
24122 @cindex pragma Elaborate_Body
24123 This pragma requires that the body of a unit be elaborated immediately
24124 after its spec. Suppose a unit @code{A} has such a pragma,
24125 and unit @code{B} does
24126 a @code{with} of unit @code{A}. Recall that the standard rules require
24127 the spec of unit @code{A}
24128 to be elaborated before the @code{with}'ing unit; given the pragma in
24129 @code{A}, we also know that the body of @code{A}
24130 will be elaborated before @code{B}, so
24131 that calls to @code{A} are safe and do not need a check.
24132 @end table
24134 @noindent
24135 Note that,
24136 unlike pragma @code{Pure} and pragma @code{Preelaborate},
24137 the use of
24138 @code{Elaborate_Body} does not guarantee that the program is
24139 free of elaboration problems, because it may not be possible
24140 to satisfy the requested elaboration order.
24141 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
24142 If a programmer
24143 marks @code{Unit_1} as @code{Elaborate_Body},
24144 and not @code{Unit_2,} then the order of
24145 elaboration will be:
24147 @smallexample
24148 @group
24149 Spec of Unit_2
24150 Spec of Unit_1
24151 Body of Unit_1
24152 Body of Unit_2
24153 @end group
24154 @end smallexample
24156 @noindent
24157 Now that means that the call to @code{Func_1} in @code{Unit_2}
24158 need not be checked,
24159 it must be safe. But the call to @code{Func_2} in
24160 @code{Unit_1} may still fail if
24161 @code{Expression_1} is equal to 1,
24162 and the programmer must still take
24163 responsibility for this not being the case.
24165 If all units carry a pragma @code{Elaborate_Body}, then all problems are
24166 eliminated, except for calls entirely within a body, which are
24167 in any case fully under programmer control. However, using the pragma
24168 everywhere is not always possible.
24169 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
24170 we marked both of them as having pragma @code{Elaborate_Body}, then
24171 clearly there would be no possible elaboration order.
24173 The above pragmas allow a server to guarantee safe use by clients, and
24174 clearly this is the preferable approach. Consequently a good rule
24175 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
24176 and if this is not possible,
24177 mark them as @code{Elaborate_Body} if possible.
24178 As we have seen, there are situations where neither of these
24179 three pragmas can be used.
24180 So we also provide methods for clients to control the
24181 order of elaboration of the servers on which they depend:
24183 @table @asis
24184 @item pragma Elaborate (unit)
24185 @findex Elaborate
24186 @cindex pragma Elaborate
24187 This pragma is placed in the context clause, after a @code{with} clause,
24188 and it requires that the body of the named unit be elaborated before
24189 the unit in which the pragma occurs. The idea is to use this pragma
24190 if the current unit calls at elaboration time, directly or indirectly,
24191 some subprogram in the named unit.
24193 @item pragma Elaborate_All (unit)
24194 @findex Elaborate_All
24195 @cindex pragma Elaborate_All
24196 This is a stronger version of the Elaborate pragma. Consider the
24197 following example:
24199 @smallexample
24200 Unit A @code{with}'s unit B and calls B.Func in elab code
24201 Unit B @code{with}'s unit C, and B.Func calls C.Func
24202 @end smallexample
24204 @noindent
24205 Now if we put a pragma @code{Elaborate (B)}
24206 in unit @code{A}, this ensures that the
24207 body of @code{B} is elaborated before the call, but not the
24208 body of @code{C}, so
24209 the call to @code{C.Func} could still cause @code{Program_Error} to
24210 be raised.
24212 The effect of a pragma @code{Elaborate_All} is stronger, it requires
24213 not only that the body of the named unit be elaborated before the
24214 unit doing the @code{with}, but also the bodies of all units that the
24215 named unit uses, following @code{with} links transitively. For example,
24216 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
24217 then it requires
24218 not only that the body of @code{B} be elaborated before @code{A},
24219 but also the
24220 body of @code{C}, because @code{B} @code{with}'s @code{C}.
24221 @end table
24223 @noindent
24224 We are now in a position to give a usage rule in Ada for avoiding
24225 elaboration problems, at least if dynamic dispatching and access to
24226 subprogram values are not used. We will handle these cases separately
24227 later.
24229 The rule is simple. If a unit has elaboration code that can directly or
24230 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
24231 a generic package in a @code{with}'ed unit,
24232 then if the @code{with}'ed unit does not have
24233 pragma @code{Pure} or @code{Preelaborate}, then the client should have
24234 a pragma @code{Elaborate_All}
24235 for the @code{with}'ed unit. By following this rule a client is
24236 assured that calls can be made without risk of an exception.
24238 For generic subprogram instantiations, the rule can be relaxed to
24239 require only a pragma @code{Elaborate} since elaborating the body
24240 of a subprogram cannot cause any transitive elaboration (we are
24241 not calling the subprogram in this case, just elaborating its
24242 declaration).
24244 If this rule is not followed, then a program may be in one of four
24245 states:
24247 @table @asis
24248 @item No order exists
24249 No order of elaboration exists which follows the rules, taking into
24250 account any @code{Elaborate}, @code{Elaborate_All},
24251 or @code{Elaborate_Body} pragmas. In
24252 this case, an Ada compiler must diagnose the situation at bind
24253 time, and refuse to build an executable program.
24255 @item One or more orders exist, all incorrect
24256 One or more acceptable elaboration orders exist, and all of them
24257 generate an elaboration order problem. In this case, the binder
24258 can build an executable program, but @code{Program_Error} will be raised
24259 when the program is run.
24261 @item Several orders exist, some right, some incorrect
24262 One or more acceptable elaboration orders exists, and some of them
24263 work, and some do not. The programmer has not controlled
24264 the order of elaboration, so the binder may or may not pick one of
24265 the correct orders, and the program may or may not raise an
24266 exception when it is run. This is the worst case, because it means
24267 that the program may fail when moved to another compiler, or even
24268 another version of the same compiler.
24270 @item One or more orders exists, all correct
24271 One ore more acceptable elaboration orders exist, and all of them
24272 work. In this case the program runs successfully. This state of
24273 affairs can be guaranteed by following the rule we gave above, but
24274 may be true even if the rule is not followed.
24275 @end table
24277 @noindent
24278 Note that one additional advantage of following our rules on the use
24279 of @code{Elaborate} and @code{Elaborate_All}
24280 is that the program continues to stay in the ideal (all orders OK) state
24281 even if maintenance
24282 changes some bodies of some units. Conversely, if a program that does
24283 not follow this rule happens to be safe at some point, this state of affairs
24284 may deteriorate silently as a result of maintenance changes.
24286 You may have noticed that the above discussion did not mention
24287 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
24288 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
24289 code in the body makes calls to some other unit, so it is still necessary
24290 to use @code{Elaborate_All} on such units.
24292 @node Controlling Elaboration in GNAT - Internal Calls
24293 @section Controlling Elaboration in GNAT - Internal Calls
24295 @noindent
24296 In the case of internal calls, i.e., calls within a single package, the
24297 programmer has full control over the order of elaboration, and it is up
24298 to the programmer to elaborate declarations in an appropriate order. For
24299 example writing:
24301 @smallexample @c ada
24302 @group
24303 @cartouche
24304 function One return Float;
24306 Q : Float := One;
24308 function One return Float is
24309 begin
24310      return 1.0;
24311 end One;
24312 @end cartouche
24313 @end group
24314 @end smallexample
24316 @noindent
24317 will obviously raise @code{Program_Error} at run time, because function
24318 One will be called before its body is elaborated. In this case GNAT will
24319 generate a warning that the call will raise @code{Program_Error}:
24321 @smallexample
24322 @group
24323 @cartouche
24324  1. procedure y is
24325  2.    function One return Float;
24326  3.
24327  4.    Q : Float := One;
24328                     |
24329     >>> warning: cannot call "One" before body is elaborated
24330     >>> warning: Program_Error will be raised at run time
24332  5.
24333  6.    function One return Float is
24334  7.    begin
24335  8.         return 1.0;
24336  9.    end One;
24338 11. begin
24339 12.    null;
24340 13. end;
24341 @end cartouche
24342 @end group
24343 @end smallexample
24345 @noindent
24346 Note that in this particular case, it is likely that the call is safe, because
24347 the function @code{One} does not access any global variables.
24348 Nevertheless in Ada, we do not want the validity of the check to depend on
24349 the contents of the body (think about the separate compilation case), so this
24350 is still wrong, as we discussed in the previous sections.
24352 The error is easily corrected by rearranging the declarations so that the
24353 body of @code{One} appears before the declaration containing the call
24354 (note that in Ada 95 and Ada 2005,
24355 declarations can appear in any order, so there is no restriction that
24356 would prevent this reordering, and if we write:
24358 @smallexample @c ada
24359 @group
24360 @cartouche
24361 function One return Float;
24363 function One return Float is
24364 begin
24365      return 1.0;
24366 end One;
24368 Q : Float := One;
24369 @end cartouche
24370 @end group
24371 @end smallexample
24373 @noindent
24374 then all is well, no warning is generated, and no
24375 @code{Program_Error} exception
24376 will be raised.
24377 Things are more complicated when a chain of subprograms is executed:
24379 @smallexample @c ada
24380 @group
24381 @cartouche
24382 function A return Integer;
24383 function B return Integer;
24384 function C return Integer;
24386 function B return Integer is begin return A; end;
24387 function C return Integer is begin return B; end;
24389 X : Integer := C;
24391 function A return Integer is begin return 1; end;
24392 @end cartouche
24393 @end group
24394 @end smallexample
24396 @noindent
24397 Now the call to @code{C}
24398 at elaboration time in the declaration of @code{X} is correct, because
24399 the body of @code{C} is already elaborated,
24400 and the call to @code{B} within the body of
24401 @code{C} is correct, but the call
24402 to @code{A} within the body of @code{B} is incorrect, because the body
24403 of @code{A} has not been elaborated, so @code{Program_Error}
24404 will be raised on the call to @code{A}.
24405 In this case GNAT will generate a
24406 warning that @code{Program_Error} may be
24407 raised at the point of the call. Let's look at the warning:
24409 @smallexample
24410 @group
24411 @cartouche
24412  1. procedure x is
24413  2.    function A return Integer;
24414  3.    function B return Integer;
24415  4.    function C return Integer;
24416  5.
24417  6.    function B return Integer is begin return A; end;
24418                                                     |
24419     >>> warning: call to "A" before body is elaborated may
24420                  raise Program_Error
24421     >>> warning: "B" called at line 7
24422     >>> warning: "C" called at line 9
24424  7.    function C return Integer is begin return B; end;
24425  8.
24426  9.    X : Integer := C;
24428 11.    function A return Integer is begin return 1; end;
24430 13. begin
24431 14.    null;
24432 15. end;
24433 @end cartouche
24434 @end group
24435 @end smallexample
24437 @noindent
24438 Note that the message here says ``may raise'', instead of the direct case,
24439 where the message says ``will be raised''. That's because whether
24440 @code{A} is
24441 actually called depends in general on run-time flow of control.
24442 For example, if the body of @code{B} said
24444 @smallexample @c ada
24445 @group
24446 @cartouche
24447 function B return Integer is
24448 begin
24449    if some-condition-depending-on-input-data then
24450       return A;
24451    else
24452       return 1;
24453    end if;
24454 end B;
24455 @end cartouche
24456 @end group
24457 @end smallexample
24459 @noindent
24460 then we could not know until run time whether the incorrect call to A would
24461 actually occur, so @code{Program_Error} might
24462 or might not be raised. It is possible for a compiler to
24463 do a better job of analyzing bodies, to
24464 determine whether or not @code{Program_Error}
24465 might be raised, but it certainly
24466 couldn't do a perfect job (that would require solving the halting problem
24467 and is provably impossible), and because this is a warning anyway, it does
24468 not seem worth the effort to do the analysis. Cases in which it
24469 would be relevant are rare.
24471 In practice, warnings of either of the forms given
24472 above will usually correspond to
24473 real errors, and should be examined carefully and eliminated.
24474 In the rare case where a warning is bogus, it can be suppressed by any of
24475 the following methods:
24477 @itemize @bullet
24478 @item
24479 Compile with the @option{-gnatws} switch set
24481 @item
24482 Suppress @code{Elaboration_Check} for the called subprogram
24484 @item
24485 Use pragma @code{Warnings_Off} to turn warnings off for the call
24486 @end itemize
24488 @noindent
24489 For the internal elaboration check case,
24490 GNAT by default generates the
24491 necessary run-time checks to ensure
24492 that @code{Program_Error} is raised if any
24493 call fails an elaboration check. Of course this can only happen if a
24494 warning has been issued as described above. The use of pragma
24495 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24496 some of these checks, meaning that it may be possible (but is not
24497 guaranteed) for a program to be able to call a subprogram whose body
24498 is not yet elaborated, without raising a @code{Program_Error} exception.
24500 @node Controlling Elaboration in GNAT - External Calls
24501 @section Controlling Elaboration in GNAT - External Calls
24503 @noindent
24504 The previous section discussed the case in which the execution of a
24505 particular thread of elaboration code occurred entirely within a
24506 single unit. This is the easy case to handle, because a programmer
24507 has direct and total control over the order of elaboration, and
24508 furthermore, checks need only be generated in cases which are rare
24509 and which the compiler can easily detect.
24510 The situation is more complex when separate compilation is taken into account.
24511 Consider the following:
24513 @smallexample @c ada
24514 @cartouche
24515 @group
24516 package Math is
24517    function Sqrt (Arg : Float) return Float;
24518 end Math;
24520 package body Math is
24521    function Sqrt (Arg : Float) return Float is
24522    begin
24523          @dots{}
24524    end Sqrt;
24525 end Math;
24526 @end group
24527 @group
24528 with Math;
24529 package Stuff is
24530    X : Float := Math.Sqrt (0.5);
24531 end Stuff;
24533 with Stuff;
24534 procedure Main is
24535 begin
24536    @dots{}
24537 end Main;
24538 @end group
24539 @end cartouche
24540 @end smallexample
24542 @noindent
24543 where @code{Main} is the main program. When this program is executed, the
24544 elaboration code must first be executed, and one of the jobs of the
24545 binder is to determine the order in which the units of a program are
24546 to be elaborated. In this case we have four units: the spec and body
24547 of @code{Math},
24548 the spec of @code{Stuff} and the body of @code{Main}).
24549 In what order should the four separate sections of elaboration code
24550 be executed?
24552 There are some restrictions in the order of elaboration that the binder
24553 can choose. In particular, if unit U has a @code{with}
24554 for a package @code{X}, then you
24555 are assured that the spec of @code{X}
24556 is elaborated before U , but you are
24557 not assured that the body of @code{X}
24558 is elaborated before U.
24559 This means that in the above case, the binder is allowed to choose the
24560 order:
24562 @smallexample
24563 spec of Math
24564 spec of Stuff
24565 body of Math
24566 body of Main
24567 @end smallexample
24569 @noindent
24570 but that's not good, because now the call to @code{Math.Sqrt}
24571 that happens during
24572 the elaboration of the @code{Stuff}
24573 spec happens before the body of @code{Math.Sqrt} is
24574 elaborated, and hence causes @code{Program_Error} exception to be raised.
24575 At first glance, one might say that the binder is misbehaving, because
24576 obviously you want to elaborate the body of something you @code{with}
24577 first, but
24578 that is not a general rule that can be followed in all cases. Consider
24580 @smallexample @c ada
24581 @group
24582 @cartouche
24583 package X is @dots{}
24585 package Y is @dots{}
24587 with X;
24588 package body Y is @dots{}
24590 with Y;
24591 package body X is @dots{}
24592 @end cartouche
24593 @end group
24594 @end smallexample
24596 @noindent
24597 This is a common arrangement, and, apart from the order of elaboration
24598 problems that might arise in connection with elaboration code, this works fine.
24599 A rule that says that you must first elaborate the body of anything you
24600 @code{with} cannot work in this case:
24601 the body of @code{X} @code{with}'s @code{Y},
24602 which means you would have to
24603 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24604 which means
24605 you have to elaborate the body of @code{X} first, but @dots{} and we have a
24606 loop that cannot be broken.
24608 It is true that the binder can in many cases guess an order of elaboration
24609 that is unlikely to cause a @code{Program_Error}
24610 exception to be raised, and it tries to do so (in the
24611 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24612 by default
24613 elaborate the body of @code{Math} right after its spec, so all will be well).
24615 However, a program that blindly relies on the binder to be helpful can
24616 get into trouble, as we discussed in the previous sections, so
24617 GNAT
24618 provides a number of facilities for assisting the programmer in
24619 developing programs that are robust with respect to elaboration order.
24621 @node Default Behavior in GNAT - Ensuring Safety
24622 @section Default Behavior in GNAT - Ensuring Safety
24624 @noindent
24625 The default behavior in GNAT ensures elaboration safety. In its
24626 default mode GNAT implements the
24627 rule we previously described as the right approach. Let's restate it:
24629 @itemize
24630 @item
24631 @emph{If a unit has elaboration code that can directly or indirectly make a
24632 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24633 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24634 does not have pragma @code{Pure} or
24635 @code{Preelaborate}, then the client should have an
24636 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24638 @emph{In the case of instantiating a generic subprogram, it is always
24639 sufficient to have only an @code{Elaborate} pragma for the
24640 @code{with}'ed unit.}
24641 @end itemize
24643 @noindent
24644 By following this rule a client is assured that calls and instantiations
24645 can be made without risk of an exception.
24647 In this mode GNAT traces all calls that are potentially made from
24648 elaboration code, and puts in any missing implicit @code{Elaborate}
24649 and @code{Elaborate_All} pragmas.
24650 The advantage of this approach is that no elaboration problems
24651 are possible if the binder can find an elaboration order that is
24652 consistent with these implicit @code{Elaborate} and
24653 @code{Elaborate_All} pragmas. The
24654 disadvantage of this approach is that no such order may exist.
24656 If the binder does not generate any diagnostics, then it means that it has
24657 found an elaboration order that is guaranteed to be safe. However, the binder
24658 may still be relying on implicitly generated @code{Elaborate} and
24659 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24660 guaranteed.
24662 If it is important to guarantee portability, then the compilations should
24663 use the
24664 @option{-gnatwl}
24665 (warn on elaboration problems) switch. This will cause warning messages
24666 to be generated indicating the missing @code{Elaborate} and
24667 @code{Elaborate_All} pragmas.
24668 Consider the following source program:
24670 @smallexample @c ada
24671 @group
24672 @cartouche
24673 with k;
24674 package j is
24675   m : integer := k.r;
24676 end;
24677 @end cartouche
24678 @end group
24679 @end smallexample
24681 @noindent
24682 where it is clear that there
24683 should be a pragma @code{Elaborate_All}
24684 for unit @code{k}. An implicit pragma will be generated, and it is
24685 likely that the binder will be able to honor it. However, if you want
24686 to port this program to some other Ada compiler than GNAT.
24687 it is safer to include the pragma explicitly in the source. If this
24688 unit is compiled with the
24689 @option{-gnatwl}
24690 switch, then the compiler outputs a warning:
24692 @smallexample
24693 @group
24694 @cartouche
24695 1. with k;
24696 2. package j is
24697 3.   m : integer := k.r;
24698                      |
24699    >>> warning: call to "r" may raise Program_Error
24700    >>> warning: missing pragma Elaborate_All for "k"
24702 4. end;
24703 @end cartouche
24704 @end group
24705 @end smallexample
24707 @noindent
24708 and these warnings can be used as a guide for supplying manually
24709 the missing pragmas. It is usually a bad idea to use this warning
24710 option during development. That's because it will warn you when
24711 you need to put in a pragma, but cannot warn you when it is time
24712 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24713 unnecessary dependencies and even false circularities.
24715 This default mode is more restrictive than the Ada Reference
24716 Manual, and it is possible to construct programs which will compile
24717 using the dynamic model described there, but will run into a
24718 circularity using the safer static model we have described.
24720 Of course any Ada compiler must be able to operate in a mode
24721 consistent with the requirements of the Ada Reference Manual,
24722 and in particular must have the capability of implementing the
24723 standard dynamic model of elaboration with run-time checks.
24725 In GNAT, this standard mode can be achieved either by the use of
24726 the @option{-gnatE} switch on the compiler (@command{gcc} or
24727 @command{gnatmake}) command, or by the use of the configuration pragma:
24729 @smallexample @c ada
24730 pragma Elaboration_Checks (DYNAMIC);
24731 @end smallexample
24733 @noindent
24734 Either approach will cause the unit affected to be compiled using the
24735 standard dynamic run-time elaboration checks described in the Ada
24736 Reference Manual. The static model is generally preferable, since it
24737 is clearly safer to rely on compile and link time checks rather than
24738 run-time checks. However, in the case of legacy code, it may be
24739 difficult to meet the requirements of the static model. This
24740 issue is further discussed in
24741 @ref{What to Do If the Default Elaboration Behavior Fails}.
24743 Note that the static model provides a strict subset of the allowed
24744 behavior and programs of the Ada Reference Manual, so if you do
24745 adhere to the static model and no circularities exist,
24746 then you are assured that your program will
24747 work using the dynamic model, providing that you remove any
24748 pragma Elaborate statements from the source.
24750 @node Treatment of Pragma Elaborate
24751 @section Treatment of Pragma Elaborate
24752 @cindex Pragma Elaborate
24754 @noindent
24755 The use of @code{pragma Elaborate}
24756 should generally be avoided in Ada 95 and Ada 2005 programs,
24757 since there is no guarantee that transitive calls
24758 will be properly handled. Indeed at one point, this pragma was placed
24759 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24761 Now that's a bit restrictive. In practice, the case in which
24762 @code{pragma Elaborate} is useful is when the caller knows that there
24763 are no transitive calls, or that the called unit contains all necessary
24764 transitive @code{pragma Elaborate} statements, and legacy code often
24765 contains such uses.
24767 Strictly speaking the static mode in GNAT should ignore such pragmas,
24768 since there is no assurance at compile time that the necessary safety
24769 conditions are met. In practice, this would cause GNAT to be incompatible
24770 with correctly written Ada 83 code that had all necessary
24771 @code{pragma Elaborate} statements in place. Consequently, we made the
24772 decision that GNAT in its default mode will believe that if it encounters
24773 a @code{pragma Elaborate} then the programmer knows what they are doing,
24774 and it will trust that no elaboration errors can occur.
24776 The result of this decision is two-fold. First to be safe using the
24777 static mode, you should remove all @code{pragma Elaborate} statements.
24778 Second, when fixing circularities in existing code, you can selectively
24779 use @code{pragma Elaborate} statements to convince the static mode of
24780 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24781 statement.
24783 When using the static mode with @option{-gnatwl}, any use of
24784 @code{pragma Elaborate} will generate a warning about possible
24785 problems.
24787 @node Elaboration Issues for Library Tasks
24788 @section Elaboration Issues for Library Tasks
24789 @cindex Library tasks, elaboration issues
24790 @cindex Elaboration of library tasks
24792 @noindent
24793 In this section we examine special elaboration issues that arise for
24794 programs that declare library level tasks.
24796 Generally the model of execution of an Ada program is that all units are
24797 elaborated, and then execution of the program starts. However, the
24798 declaration of library tasks definitely does not fit this model. The
24799 reason for this is that library tasks start as soon as they are declared
24800 (more precisely, as soon as the statement part of the enclosing package
24801 body is reached), that is to say before elaboration
24802 of the program is complete. This means that if such a task calls a
24803 subprogram, or an entry in another task, the callee may or may not be
24804 elaborated yet, and in the standard
24805 Reference Manual model of dynamic elaboration checks, you can even
24806 get timing dependent Program_Error exceptions, since there can be
24807 a race between the elaboration code and the task code.
24809 The static model of elaboration in GNAT seeks to avoid all such
24810 dynamic behavior, by being conservative, and the conservative
24811 approach in this particular case is to assume that all the code
24812 in a task body is potentially executed at elaboration time if
24813 a task is declared at the library level.
24815 This can definitely result in unexpected circularities. Consider
24816 the following example
24818 @smallexample @c ada
24819 package Decls is
24820   task Lib_Task is
24821      entry Start;
24822   end Lib_Task;
24824   type My_Int is new Integer;
24826   function Ident (M : My_Int) return My_Int;
24827 end Decls;
24829 with Utils;
24830 package body Decls is
24831   task body Lib_Task is
24832   begin
24833      accept Start;
24834      Utils.Put_Val (2);
24835   end Lib_Task;
24837   function Ident (M : My_Int) return My_Int is
24838   begin
24839      return M;
24840   end Ident;
24841 end Decls;
24843 with Decls;
24844 package Utils is
24845   procedure Put_Val (Arg : Decls.My_Int);
24846 end Utils;
24848 with Text_IO;
24849 package body Utils is
24850   procedure Put_Val (Arg : Decls.My_Int) is
24851   begin
24852      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24853   end Put_Val;
24854 end Utils;
24856 with Decls;
24857 procedure Main is
24858 begin
24859    Decls.Lib_Task.Start;
24860 end;
24861 @end smallexample
24863 @noindent
24864 If the above example is compiled in the default static elaboration
24865 mode, then a circularity occurs. The circularity comes from the call
24866 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24867 this call occurs in elaboration code, we need an implicit pragma
24868 @code{Elaborate_All} for @code{Utils}. This means that not only must
24869 the spec and body of @code{Utils} be elaborated before the body
24870 of @code{Decls}, but also the spec and body of any unit that is
24871 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24872 the body of @code{Decls}. This is the transitive implication of
24873 pragma @code{Elaborate_All} and it makes sense, because in general
24874 the body of @code{Put_Val} might have a call to something in a
24875 @code{with'ed} unit.
24877 In this case, the body of Utils (actually its spec) @code{with's}
24878 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24879 must be elaborated before itself, in case there is a call from the
24880 body of @code{Utils}.
24882 Here is the exact chain of events we are worrying about:
24884 @enumerate
24885 @item
24886 In the body of @code{Decls} a call is made from within the body of a library
24887 task to a subprogram in the package @code{Utils}. Since this call may
24888 occur at elaboration time (given that the task is activated at elaboration
24889 time), we have to assume the worst, i.e., that the
24890 call does happen at elaboration time.
24892 @item
24893 This means that the body and spec of @code{Util} must be elaborated before
24894 the body of @code{Decls} so that this call does not cause an access before
24895 elaboration.
24897 @item
24898 Within the body of @code{Util}, specifically within the body of
24899 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24900 by this package.
24902 @item
24903 One such @code{with}'ed package is package @code{Decls}, so there
24904 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24905 In fact there is such a call in this example, but we would have to
24906 assume that there was such a call even if it were not there, since
24907 we are not supposed to write the body of @code{Decls} knowing what
24908 is in the body of @code{Utils}; certainly in the case of the
24909 static elaboration model, the compiler does not know what is in
24910 other bodies and must assume the worst.
24912 @item
24913 This means that the spec and body of @code{Decls} must also be
24914 elaborated before we elaborate the unit containing the call, but
24915 that unit is @code{Decls}! This means that the body of @code{Decls}
24916 must be elaborated before itself, and that's a circularity.
24917 @end enumerate
24919 @noindent
24920 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24921 the body of @code{Decls} you will get a true Ada Reference Manual
24922 circularity that makes the program illegal.
24924 In practice, we have found that problems with the static model of
24925 elaboration in existing code often arise from library tasks, so
24926 we must address this particular situation.
24928 Note that if we compile and run the program above, using the dynamic model of
24929 elaboration (that is to say use the @option{-gnatE} switch),
24930 then it compiles, binds,
24931 links, and runs, printing the expected result of 2. Therefore in some sense
24932 the circularity here is only apparent, and we need to capture
24933 the properties of this program that  distinguish it from other library-level
24934 tasks that have real elaboration problems.
24936 We have four possible answers to this question:
24938 @itemize @bullet
24940 @item
24941 Use the dynamic model of elaboration.
24943 If we use the @option{-gnatE} switch, then as noted above, the program works.
24944 Why is this? If we examine the task body, it is apparent that the task cannot
24945 proceed past the
24946 @code{accept} statement until after elaboration has been completed, because
24947 the corresponding entry call comes from the main program, not earlier.
24948 This is why the dynamic model works here. But that's really giving
24949 up on a precise analysis, and we prefer to take this approach only if we cannot
24950 solve the
24951 problem in any other manner. So let us examine two ways to reorganize
24952 the program to avoid the potential elaboration problem.
24954 @item
24955 Split library tasks into separate packages.
24957 Write separate packages, so that library tasks are isolated from
24958 other declarations as much as possible. Let us look at a variation on
24959 the above program.
24961 @smallexample @c ada
24962 package Decls1 is
24963   task Lib_Task is
24964      entry Start;
24965   end Lib_Task;
24966 end Decls1;
24968 with Utils;
24969 package body Decls1 is
24970   task body Lib_Task is
24971   begin
24972      accept Start;
24973      Utils.Put_Val (2);
24974   end Lib_Task;
24975 end Decls1;
24977 package Decls2 is
24978   type My_Int is new Integer;
24979   function Ident (M : My_Int) return My_Int;
24980 end Decls2;
24982 with Utils;
24983 package body Decls2 is
24984   function Ident (M : My_Int) return My_Int is
24985   begin
24986      return M;
24987   end Ident;
24988 end Decls2;
24990 with Decls2;
24991 package Utils is
24992   procedure Put_Val (Arg : Decls2.My_Int);
24993 end Utils;
24995 with Text_IO;
24996 package body Utils is
24997   procedure Put_Val (Arg : Decls2.My_Int) is
24998   begin
24999      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
25000   end Put_Val;
25001 end Utils;
25003 with Decls1;
25004 procedure Main is
25005 begin
25006    Decls1.Lib_Task.Start;
25007 end;
25008 @end smallexample
25010 @noindent
25011 All we have done is to split @code{Decls} into two packages, one
25012 containing the library task, and one containing everything else. Now
25013 there is no cycle, and the program compiles, binds, links and executes
25014 using the default static model of elaboration.
25016 @item
25017 Declare separate task types.
25019 A significant part of the problem arises because of the use of the
25020 single task declaration form. This means that the elaboration of
25021 the task type, and the elaboration of the task itself (i.e.@: the
25022 creation of the task) happen at the same time. A good rule
25023 of style in Ada is to always create explicit task types. By
25024 following the additional step of placing task objects in separate
25025 packages from the task type declaration, many elaboration problems
25026 are avoided. Here is another modified example of the example program:
25028 @smallexample @c ada
25029 package Decls is
25030   task type Lib_Task_Type is
25031      entry Start;
25032   end Lib_Task_Type;
25034   type My_Int is new Integer;
25036   function Ident (M : My_Int) return My_Int;
25037 end Decls;
25039 with Utils;
25040 package body Decls is
25041   task body Lib_Task_Type is
25042   begin
25043      accept Start;
25044      Utils.Put_Val (2);
25045   end Lib_Task_Type;
25047   function Ident (M : My_Int) return My_Int is
25048   begin
25049      return M;
25050   end Ident;
25051 end Decls;
25053 with Decls;
25054 package Utils is
25055   procedure Put_Val (Arg : Decls.My_Int);
25056 end Utils;
25058 with Text_IO;
25059 package body Utils is
25060   procedure Put_Val (Arg : Decls.My_Int) is
25061   begin
25062      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25063   end Put_Val;
25064 end Utils;
25066 with Decls;
25067 package Declst is
25068    Lib_Task : Decls.Lib_Task_Type;
25069 end Declst;
25071 with Declst;
25072 procedure Main is
25073 begin
25074    Declst.Lib_Task.Start;
25075 end;
25076 @end smallexample
25078 @noindent
25079 What we have done here is to replace the @code{task} declaration in
25080 package @code{Decls} with a @code{task type} declaration. Then we
25081 introduce a separate package @code{Declst} to contain the actual
25082 task object. This separates the elaboration issues for
25083 the @code{task type}
25084 declaration, which causes no trouble, from the elaboration issues
25085 of the task object, which is also unproblematic, since it is now independent
25086 of the elaboration of  @code{Utils}.
25087 This separation of concerns also corresponds to
25088 a generally sound engineering principle of separating declarations
25089 from instances. This version of the program also compiles, binds, links,
25090 and executes, generating the expected output.
25092 @item
25093 Use No_Entry_Calls_In_Elaboration_Code restriction.
25094 @cindex No_Entry_Calls_In_Elaboration_Code
25096 The previous two approaches described how a program can be restructured
25097 to avoid the special problems caused by library task bodies. in practice,
25098 however, such restructuring may be difficult to apply to existing legacy code,
25099 so we must consider solutions that do not require massive rewriting.
25101 Let us consider more carefully why our original sample program works
25102 under the dynamic model of elaboration. The reason is that the code
25103 in the task body blocks immediately on the @code{accept}
25104 statement. Now of course there is nothing to prohibit elaboration
25105 code from making entry calls (for example from another library level task),
25106 so we cannot tell in isolation that
25107 the task will not execute the accept statement  during elaboration.
25109 However, in practice it is very unusual to see elaboration code
25110 make any entry calls, and the pattern of tasks starting
25111 at elaboration time and then immediately blocking on @code{accept} or
25112 @code{select} statements is very common. What this means is that
25113 the compiler is being too pessimistic when it analyzes the
25114 whole package body as though it might be executed at elaboration
25115 time.
25117 If we know that the elaboration code contains no entry calls, (a very safe
25118 assumption most of the time, that could almost be made the default
25119 behavior), then we can compile all units of the program under control
25120 of the following configuration pragma:
25122 @smallexample
25123 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
25124 @end smallexample
25126 @noindent
25127 This pragma can be placed in the @file{gnat.adc} file in the usual
25128 manner. If we take our original unmodified program and compile it
25129 in the presence of a @file{gnat.adc} containing the above pragma,
25130 then once again, we can compile, bind, link, and execute, obtaining
25131 the expected result. In the presence of this pragma, the compiler does
25132 not trace calls in a task body, that appear after the first @code{accept}
25133 or @code{select} statement, and therefore does not report a potential
25134 circularity in the original program.
25136 The compiler will check to the extent it can that the above
25137 restriction is not violated, but it is not always possible to do a
25138 complete check at compile time, so it is important to use this
25139 pragma only if the stated restriction is in fact met, that is to say
25140 no task receives an entry call before elaboration of all units is completed.
25142 @end itemize
25144 @node Mixing Elaboration Models
25145 @section Mixing Elaboration Models
25146 @noindent
25147 So far, we have assumed that the entire program is either compiled
25148 using the dynamic model or static model, ensuring consistency. It
25149 is possible to mix the two models, but rules have to be followed
25150 if this mixing is done to ensure that elaboration checks are not
25151 omitted.
25153 The basic rule is that @emph{a unit compiled with the static model cannot
25154 be @code{with'ed} by a unit compiled with the dynamic model}. The
25155 reason for this is that in the static model, a unit assumes that
25156 its clients guarantee to use (the equivalent of) pragma
25157 @code{Elaborate_All} so that no elaboration checks are required
25158 in inner subprograms, and this assumption is violated if the
25159 client is compiled with dynamic checks.
25161 The precise rule is as follows. A unit that is compiled with dynamic
25162 checks can only @code{with} a unit that meets at least one of the
25163 following criteria:
25165 @itemize @bullet
25167 @item
25168 The @code{with'ed} unit is itself compiled with dynamic elaboration
25169 checks (that is with the @option{-gnatE} switch.
25171 @item
25172 The @code{with'ed} unit is an internal GNAT implementation unit from
25173 the System, Interfaces, Ada, or GNAT hierarchies.
25175 @item
25176 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25178 @item
25179 The @code{with'ing} unit (that is the client) has an explicit pragma
25180 @code{Elaborate_All} for the @code{with'ed} unit.
25182 @end itemize
25184 @noindent
25185 If this rule is violated, that is if a unit with dynamic elaboration
25186 checks @code{with's} a unit that does not meet one of the above four
25187 criteria, then the binder (@code{gnatbind}) will issue a warning
25188 similar to that in the following example:
25190 @smallexample
25191 warning: "x.ads" has dynamic elaboration checks and with's
25192 warning:   "y.ads" which has static elaboration checks
25193 @end smallexample
25195 @noindent
25196 These warnings indicate that the rule has been violated, and that as a result
25197 elaboration checks may be missed in the resulting executable file.
25198 This warning may be suppressed using the @option{-ws} binder switch
25199 in the usual manner.
25201 One useful application of this mixing rule is in the case of a subsystem
25202 which does not itself @code{with} units from the remainder of the
25203 application. In this case, the entire subsystem can be compiled with
25204 dynamic checks to resolve a circularity in the subsystem, while
25205 allowing the main application that uses this subsystem to be compiled
25206 using the more reliable default static model.
25208 @node What to Do If the Default Elaboration Behavior Fails
25209 @section What to Do If the Default Elaboration Behavior Fails
25211 @noindent
25212 If the binder cannot find an acceptable order, it outputs detailed
25213 diagnostics. For example:
25214 @smallexample
25215 @group
25216 @iftex
25217 @leftskip=0cm
25218 @end iftex
25219 error: elaboration circularity detected
25220 info:   "proc (body)" must be elaborated before "pack (body)"
25221 info:     reason: Elaborate_All probably needed in unit "pack (body)"
25222 info:     recompile "pack (body)" with -gnatwl
25223 info:                             for full details
25224 info:       "proc (body)"
25225 info:         is needed by its spec:
25226 info:       "proc (spec)"
25227 info:         which is withed by:
25228 info:       "pack (body)"
25229 info:  "pack (body)" must be elaborated before "proc (body)"
25230 info:     reason: pragma Elaborate in unit "proc (body)"
25231 @end group
25233 @end smallexample
25235 @noindent
25236 In this case we have a cycle that the binder cannot break. On the one
25237 hand, there is an explicit pragma Elaborate in @code{proc} for
25238 @code{pack}. This means that the body of @code{pack} must be elaborated
25239 before the body of @code{proc}. On the other hand, there is elaboration
25240 code in @code{pack} that calls a subprogram in @code{proc}. This means
25241 that for maximum safety, there should really be a pragma
25242 Elaborate_All in @code{pack} for @code{proc} which would require that
25243 the body of @code{proc} be elaborated before the body of
25244 @code{pack}. Clearly both requirements cannot be satisfied.
25245 Faced with a circularity of this kind, you have three different options.
25247 @table @asis
25248 @item Fix the program
25249 The most desirable option from the point of view of long-term maintenance
25250 is to rearrange the program so that the elaboration problems are avoided.
25251 One useful technique is to place the elaboration code into separate
25252 child packages. Another is to move some of the initialization code to
25253 explicitly called subprograms, where the program controls the order
25254 of initialization explicitly. Although this is the most desirable option,
25255 it may be impractical and involve too much modification, especially in
25256 the case of complex legacy code.
25258 @item Perform dynamic checks
25259 If the compilations are done using the
25260 @option{-gnatE}
25261 (dynamic elaboration check) switch, then GNAT behaves in a quite different
25262 manner. Dynamic checks are generated for all calls that could possibly result
25263 in raising an exception. With this switch, the compiler does not generate
25264 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
25265 exactly as specified in the @cite{Ada Reference Manual}.
25266 The binder will generate
25267 an executable program that may or may not raise @code{Program_Error}, and then
25268 it is the programmer's job to ensure that it does not raise an exception. Note
25269 that it is important to compile all units with the switch, it cannot be used
25270 selectively.
25272 @item Suppress checks
25273 The drawback of dynamic checks is that they generate a
25274 significant overhead at run time, both in space and time. If you
25275 are absolutely sure that your program cannot raise any elaboration
25276 exceptions, and you still want to use the dynamic elaboration model,
25277 then you can use the configuration pragma
25278 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
25279 example this pragma could be placed in the @file{gnat.adc} file.
25281 @item Suppress checks selectively
25282 When you know that certain calls or instantiations in elaboration code cannot
25283 possibly lead to an elaboration error, and the binder nevertheless complains
25284 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
25285 elaboration circularities, it is possible to remove those warnings locally and
25286 obtain a program that will bind. Clearly this can be unsafe, and it is the
25287 responsibility of the programmer to make sure that the resulting program has no
25288 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
25289 used with different granularity to suppress warnings and break elaboration
25290 circularities:
25292 @itemize @bullet
25293 @item
25294 Place the pragma that names the called subprogram in the declarative part
25295 that contains the call.
25297 @item
25298 Place the pragma in the declarative part, without naming an entity. This
25299 disables warnings on all calls in the corresponding  declarative region.
25301 @item
25302 Place the pragma in the package spec that declares the called subprogram,
25303 and name the subprogram. This disables warnings on all elaboration calls to
25304 that subprogram.
25306 @item
25307 Place the pragma in the package spec that declares the called subprogram,
25308 without naming any entity. This disables warnings on all elaboration calls to
25309 all subprograms declared in this spec.
25311 @item Use Pragma Elaborate
25312 As previously described in section @xref{Treatment of Pragma Elaborate},
25313 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
25314 that no elaboration checks are required on calls to the designated unit.
25315 There may be cases in which the caller knows that no transitive calls
25316 can occur, so that a @code{pragma Elaborate} will be sufficient in a
25317 case where @code{pragma Elaborate_All} would cause a circularity.
25318 @end itemize
25320 @noindent
25321 These five cases are listed in order of decreasing safety, and therefore
25322 require increasing programmer care in their application. Consider the
25323 following program:
25325 @smallexample @c adanocomment
25326 package Pack1 is
25327   function F1 return Integer;
25328   X1 : Integer;
25329 end Pack1;
25331 package Pack2 is
25332   function F2 return Integer;
25333   function Pure (x : integer) return integer;
25334   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
25335   --  pragma Suppress (Elaboration_Check);              -- (4)
25336 end Pack2;
25338 with Pack2;
25339 package body Pack1 is
25340   function F1 return Integer is
25341   begin
25342     return 100;
25343   end F1;
25344   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
25345 begin
25346   declare
25347     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
25348     --  pragma Suppress(Elaboration_Check);             -- (2)
25349   begin
25350     X1 := Pack2.F2 + 1;                --  Elab. call (2)
25351   end;
25352 end Pack1;
25354 with Pack1;
25355 package body Pack2 is
25356   function F2 return Integer is
25357   begin
25358      return Pack1.F1;
25359   end F2;
25360   function Pure (x : integer) return integer is
25361   begin
25362      return x ** 3 - 3 * x;
25363   end;
25364 end Pack2;
25366 with Pack1, Ada.Text_IO;
25367 procedure Proc3 is
25368 begin
25369   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25370 end Proc3;
25371 @end smallexample
25372 In the absence of any pragmas, an attempt to bind this program produces
25373 the following diagnostics:
25374 @smallexample
25375 @group
25376 @iftex
25377 @leftskip=.5cm
25378 @end iftex
25379 error: elaboration circularity detected
25380 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
25381 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
25382 info:       recompile "pack1 (body)" with -gnatwl for full details
25383 info:          "pack1 (body)"
25384 info:             must be elaborated along with its spec:
25385 info:          "pack1 (spec)"
25386 info:             which is withed by:
25387 info:          "pack2 (body)"
25388 info:             which must be elaborated along with its spec:
25389 info:          "pack2 (spec)"
25390 info:             which is withed by:
25391 info:          "pack1 (body)"
25392 @end group
25393 @end smallexample
25394 The sources of the circularity are the two calls to @code{Pack2.Pure} and
25395 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
25396 F2 is safe, even though F2 calls F1, because the call appears after the
25397 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
25398 remove the warning on the call. It is also possible to use pragma (2)
25399 because there are no other potentially unsafe calls in the block.
25401 @noindent
25402 The call to @code{Pure} is safe because this function does not depend on the
25403 state of @code{Pack2}. Therefore any call to this function is safe, and it
25404 is correct to place pragma (3) in the corresponding package spec.
25406 @noindent
25407 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
25408 warnings on all calls to functions declared therein. Note that this is not
25409 necessarily safe, and requires more detailed examination of the subprogram
25410 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
25411 be already elaborated.
25412 @end table
25414 @noindent
25415 It is hard to generalize on which of these four approaches should be
25416 taken. Obviously if it is possible to fix the program so that the default
25417 treatment works, this is preferable, but this may not always be practical.
25418 It is certainly simple enough to use
25419 @option{-gnatE}
25420 but the danger in this case is that, even if the GNAT binder
25421 finds a correct elaboration order, it may not always do so,
25422 and certainly a binder from another Ada compiler might not. A
25423 combination of testing and analysis (for which the warnings generated
25424 with the
25425 @option{-gnatwl}
25426 switch can be useful) must be used to ensure that the program is free
25427 of errors. One switch that is useful in this testing is the
25428 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
25429 switch for
25430 @code{gnatbind}.
25431 Normally the binder tries to find an order that has the best chance
25432 of avoiding elaboration problems. However, if this switch is used, the binder
25433 plays a devil's advocate role, and tries to choose the order that
25434 has the best chance of failing. If your program works even with this
25435 switch, then it has a better chance of being error free, but this is still
25436 not a guarantee.
25438 For an example of this approach in action, consider the C-tests (executable
25439 tests) from the ACVC suite. If these are compiled and run with the default
25440 treatment, then all but one of them succeed without generating any error
25441 diagnostics from the binder. However, there is one test that fails, and
25442 this is not surprising, because the whole point of this test is to ensure
25443 that the compiler can handle cases where it is impossible to determine
25444 a correct order statically, and it checks that an exception is indeed
25445 raised at run time.
25447 This one test must be compiled and run using the
25448 @option{-gnatE}
25449 switch, and then it passes. Alternatively, the entire suite can
25450 be run using this switch. It is never wrong to run with the dynamic
25451 elaboration switch if your code is correct, and we assume that the
25452 C-tests are indeed correct (it is less efficient, but efficiency is
25453 not a factor in running the ACVC tests.)
25455 @node Elaboration for Dispatching Calls
25456 @section Elaboration for Dispatching Calls
25457 @cindex Dispatching calls
25459 @noindent
25460 In rare cases, the static elaboration model fails to prevent
25461 dispatching calls to not-yet-elaborated subprograms. In such cases, we
25462 fall back to run-time checks; premature calls to any primitive
25463 operation of a tagged type before the body of the operation has been
25464 elaborated will raise @code{Program_Error}.
25466 Access-to-subprogram types, however, are handled conservatively, and
25467 do not require run-time checks. This was not true in earlier versions
25468 of the compiler; you can use the @option{-gnatd.U} debug switch to
25469 revert to the old behavior if the new conservative behavior causes
25470 elaboration cycles.
25472 @node Summary of Procedures for Elaboration Control
25473 @section Summary of Procedures for Elaboration Control
25474 @cindex Elaboration control
25476 @noindent
25477 First, compile your program with the default options, using none of
25478 the special elaboration control switches. If the binder successfully
25479 binds your program, then you can be confident that, apart from issues
25480 raised by the use of access-to-subprogram types and dynamic dispatching,
25481 the program is free of elaboration errors. If it is important that the
25482 program be portable, then use the
25483 @option{-gnatwl}
25484 switch to generate warnings about missing @code{Elaborate} or
25485 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25487 If the program fails to bind using the default static elaboration
25488 handling, then you can fix the program to eliminate the binder
25489 message, or recompile the entire program with the
25490 @option{-gnatE} switch to generate dynamic elaboration checks,
25491 and, if you are sure there really are no elaboration problems,
25492 use a global pragma @code{Suppress (Elaboration_Check)}.
25494 @node Other Elaboration Order Considerations
25495 @section Other Elaboration Order Considerations
25496 @noindent
25497 This section has been entirely concerned with the issue of finding a valid
25498 elaboration order, as defined by the Ada Reference Manual. In a case
25499 where several elaboration orders are valid, the task is to find one
25500 of the possible valid elaboration orders (and the static model in GNAT
25501 will ensure that this is achieved).
25503 The purpose of the elaboration rules in the Ada Reference Manual is to
25504 make sure that no entity is accessed before it has been elaborated. For
25505 a subprogram, this means that the spec and body must have been elaborated
25506 before the subprogram is called. For an object, this means that the object
25507 must have been elaborated before its value is read or written. A violation
25508 of either of these two requirements is an access before elaboration order,
25509 and this section has been all about avoiding such errors.
25511 In the case where more than one order of elaboration is possible, in the
25512 sense that access before elaboration errors are avoided, then any one of
25513 the orders is ``correct'' in the sense that it meets the requirements of
25514 the Ada Reference Manual, and no such error occurs.
25516 However, it may be the case for a given program, that there are
25517 constraints on the order of elaboration that come not from consideration
25518 of avoiding elaboration errors, but rather from extra-lingual logic
25519 requirements. Consider this example:
25521 @smallexample @c ada
25522 with Init_Constants;
25523 package Constants is
25524    X : Integer := 0;
25525    Y : Integer := 0;
25526 end Constants;
25528 package Init_Constants is
25529    procedure P; -- require a body
25530 end Init_Constants;
25532 with Constants;
25533 package body Init_Constants is
25534    procedure P is begin null; end;
25535 begin
25536    Constants.X := 3;
25537    Constants.Y := 4;
25538 end Init_Constants;
25540 with Constants;
25541 package Calc is
25542    Z : Integer := Constants.X + Constants.Y;
25543 end Calc;
25545 with Calc;
25546 with Text_IO; use Text_IO;
25547 procedure Main is
25548 begin
25549    Put_Line (Calc.Z'Img);
25550 end Main;
25551 @end smallexample
25553 @noindent
25554 In this example, there is more than one valid order of elaboration. For
25555 example both the following are correct orders:
25557 @smallexample
25558 Init_Constants spec
25559 Constants spec
25560 Calc spec
25561 Init_Constants body
25562 Main body
25564   and
25566 Init_Constants spec
25567 Init_Constants body
25568 Constants spec
25569 Calc spec
25570 Main body
25571 @end smallexample
25573 @noindent
25574 There is no language rule to prefer one or the other, both are correct
25575 from an order of elaboration point of view. But the programmatic effects
25576 of the two orders are very different. In the first, the elaboration routine
25577 of @code{Calc} initializes @code{Z} to zero, and then the main program
25578 runs with this value of zero. But in the second order, the elaboration
25579 routine of @code{Calc} runs after the body of Init_Constants has set
25580 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25581 runs.
25583 One could perhaps by applying pretty clever non-artificial intelligence
25584 to the situation guess that it is more likely that the second order of
25585 elaboration is the one desired, but there is no formal linguistic reason
25586 to prefer one over the other. In fact in this particular case, GNAT will
25587 prefer the second order, because of the rule that bodies are elaborated
25588 as soon as possible, but it's just luck that this is what was wanted
25589 (if indeed the second order was preferred).
25591 If the program cares about the order of elaboration routines in a case like
25592 this, it is important to specify the order required. In this particular
25593 case, that could have been achieved by adding to the spec of Calc:
25595 @smallexample @c ada
25596 pragma Elaborate_All (Constants);
25597 @end smallexample
25599 @noindent
25600 which requires that the body (if any) and spec of @code{Constants},
25601 as well as the body and spec of any unit @code{with}'ed by
25602 @code{Constants} be elaborated before @code{Calc} is elaborated.
25604 Clearly no automatic method can always guess which alternative you require,
25605 and if you are working with legacy code that had constraints of this kind
25606 which were not properly specified by adding @code{Elaborate} or
25607 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25608 compilers can choose different orders.
25610 However, GNAT does attempt to diagnose the common situation where there
25611 are uninitialized variables in the visible part of a package spec, and the
25612 corresponding package body has an elaboration block that directly or
25613 indirectly initialized one or more of these variables. This is the situation
25614 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25615 a warning that suggests this addition if it detects this situation.
25617 The @code{gnatbind}
25618 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25619 out problems. This switch causes bodies to be elaborated as late as possible
25620 instead of as early as possible. In the example above, it would have forced
25621 the choice of the first elaboration order. If you get different results
25622 when using this switch, and particularly if one set of results is right,
25623 and one is wrong as far as you are concerned, it shows that you have some
25624 missing @code{Elaborate} pragmas. For the example above, we have the
25625 following output:
25627 @smallexample
25628 gnatmake -f -q main
25629 main
25631 gnatmake -f -q main -bargs -p
25632 main
25634 @end smallexample
25636 @noindent
25637 It is of course quite unlikely that both these results are correct, so
25638 it is up to you in a case like this to investigate the source of the
25639 difference, by looking at the two elaboration orders that are chosen,
25640 and figuring out which is correct, and then adding the necessary
25641 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25644 @c **********************************
25645 @node Overflow Check Handling in GNAT
25646 @appendix Overflow Check Handling in GNAT
25647 @cindex Overflow checks
25648 @cindex Checks (overflow)
25649 @c **********************************
25651 @menu
25652 * Background::
25653 * Overflow Checking Modes in GNAT::
25654 * Specifying the Desired Mode::
25655 * Default Settings::
25656 * Implementation Notes::
25657 @end menu
25660 @node Background
25661 @section Background
25663 @noindent
25664 Overflow checks are checks that the compiler may make to ensure
25665 that intermediate results are not out of range. For example:
25667 @smallexample @c ada
25668    A : Integer;
25669    ...
25670    A := A + 1;
25671 @end smallexample
25673 @noindent
25674 if @code{A} has the value @code{Integer'Last}, then the addition may cause
25675 overflow since the result is out of range of the type @code{Integer}.
25676 In this case @code{Constraint_Error} will be raised if checks are
25677 enabled.
25679 A trickier situation arises in examples like the following:
25681 @smallexample @c ada
25682   A, C : Integer;
25683   ...
25684   A := (A + 1) + C;
25685 @end smallexample
25687 @noindent
25688 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
25689 Now the final result of the expression on the right hand side is
25690 @code{Integer'Last} which is in range, but the question arises whether the
25691 intermediate addition of @code{(A + 1)} raises an overflow error.
25693 The (perhaps surprising) answer is that the Ada language
25694 definition does not answer this question. Instead it leaves
25695 it up to the implementation to do one of two things if overflow
25696 checks are enabled.
25698 @itemize @bullet
25699 @item
25700 raise an exception (@code{Constraint_Error}), or
25702 @item
25703 yield the correct mathematical result which is then used in
25704 subsequent operations.
25705 @end itemize
25707 @noindent
25708 If the compiler chooses the first approach, then the assignment of this
25709 example will indeed raise @code{Constraint_Error} if overflow checking is
25710 enabled, or result in erroneous execution if overflow checks are suppressed.
25712 But if the compiler
25713 chooses the second approach, then it can perform both additions yielding
25714 the correct mathematical result, which is in range, so no exception
25715 will be raised, and the right result is obtained, regardless of whether
25716 overflow checks are suppressed.
25718 Note that in the first example an
25719 exception will be raised in either case, since if the compiler
25720 gives the correct mathematical result for the addition, it will
25721 be out of range of the target type of the assignment, and thus
25722 fails the range check.
25724 This lack of specified behavior in the handling of overflow for
25725 intermediate results is a source of non-portability, and can thus
25726 be problematic when programs are ported. Most typically this arises
25727 in a situation where the original compiler did not raise an exception,
25728 and then the application is moved to a compiler where the check is
25729 performed on the intermediate result and an unexpected exception is
25730 raised.
25732 Furthermore, when using Ada 2012's preconditions and other
25733 assertion forms, another issue arises. Consider:
25735 @smallexample @c ada
25736      procedure P (A, B : Integer) with
25737        Pre => A + B <= Integer'Last;
25738 @end smallexample
25740 @noindent
25741 One often wants to regard arithmetic in a context like this from
25742 a mathematical point of view. So for example, if the two actual parameters
25743 for a call to @code{P} are both @code{Integer'Last}, then
25744 the precondition should be regarded as False. If we are executing
25745 in a mode with run-time checks enabled for preconditions, then we would
25746 like this precondition to fail, rather than raising an exception
25747 because of the intermediate overflow.
25749 However, the language definition leaves the specification of
25750 whether the above condition fails (raising @code{Assert_Error}) or
25751 causes an intermediate overflow (raising @code{Constraint_Error})
25752 up to the implementation.
25754 The situation is worse in a case such as the following:
25756 @smallexample @c ada
25757      procedure Q (A, B, C : Integer) with
25758        Pre => A + B + C <= Integer'Last;
25759 @end smallexample
25761 @noindent
25762 Consider the call
25764 @smallexample @c ada
25765      Q (A => Integer'Last, B => 1, C => -1);
25766 @end smallexample
25768 @noindent
25769 From a mathematical point of view the precondition
25770 is True, but at run time we may (but are not guaranteed to) get an
25771 exception raised because of the intermediate overflow (and we really
25772 would prefer this precondition to be considered True at run time).
25774 @node Overflow Checking Modes in GNAT
25775 @section Overflow Checking Modes in GNAT
25777 @noindent
25778 To deal with the portability issue, and with the problem of
25779 mathematical versus run-time intepretation of the expressions in
25780 assertions, GNAT provides comprehensive control over the handling
25781 of intermediate overflow. GNAT can operate in three modes, and
25782 furthemore, permits separate selection of operating modes for
25783 the expressions within assertions (here the term ``assertions''
25784 is used in the technical sense, which includes preconditions and so forth)
25785 and for expressions appearing outside assertions.
25787 The three modes are:
25789 @itemize @bullet
25790 @item   @i{Use base type for intermediate operations} (@code{STRICT})
25792      In this mode, all intermediate results for predefined arithmetic
25793      operators are computed using the base type, and the result must
25794      be in range of the base type. If this is not the
25795      case then either an exception is raised (if overflow checks are
25796      enabled) or the execution is erroneous (if overflow checks are suppressed).
25797      This is the normal default mode.
25799 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
25801      In this mode, the compiler attempts to avoid intermediate overflows by
25802      using a larger integer type, typically @code{Long_Long_Integer},
25803      as the type in which arithmetic is
25804      performed for predefined arithmetic operators. This may be slightly more
25805      expensive at
25806      run time (compared to suppressing intermediate overflow checks), though
25807      the cost is negligible on modern 64-bit machines. For the examples given
25808      earlier, no intermediate overflows would have resulted in exceptions,
25809      since the intermediate results are all in the range of
25810      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
25811      of GNAT). In addition, if checks are enabled, this reduces the number of
25812      checks that must be made, so this choice may actually result in an
25813      improvement in space and time behavior.
25815      However, there are cases where @code{Long_Long_Integer} is not large
25816      enough, consider the following example:
25818 @smallexample @c ada
25819        procedure R (A, B, C, D : Integer) with
25820          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
25821 @end smallexample
25823      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25824      Now the intermediate results are
25825      out of the range of @code{Long_Long_Integer} even though the final result
25826      is in range and the precondition is True (from a mathematical point
25827      of view). In such a case, operating in this mode, an overflow occurs
25828      for the intermediate computation (which is why this mode
25829      says @i{most} intermediate overflows are avoided). In this case,
25830      an exception is raised if overflow checks are enabled, and the
25831      execution is erroneous if overflow checks are suppressed.
25833 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
25835      In this mode, the compiler  avoids all intermediate overflows
25836      by using arbitrary precision arithmetic as required. In this
25837      mode, the above example with @code{A**2 * B**2} would
25838      not cause intermediate overflow, because the intermediate result
25839      would be evaluated using sufficient precision, and the result
25840      of evaluating the precondition would be True.
25842      This mode has the advantage of avoiding any intermediate
25843      overflows, but at the expense of significant run-time overhead,
25844      including the use of a library (included automatically in this
25845      mode) for multiple-precision arithmetic.
25847      This mode provides cleaner semantics for assertions, since now
25848      the run-time behavior emulates true arithmetic behavior for the
25849      predefined arithmetic operators, meaning that there is never a
25850      conflict between the mathematical view of the assertion, and its
25851      run-time behavior.
25853      Note that in this mode, the behavior is unaffected by whether or
25854      not overflow checks are suppressed, since overflow does not occur.
25855      It is possible for gigantic intermediate expressions to raise
25856      @code{Storage_Error} as a result of attempting to compute the
25857      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
25858      but overflow is impossible.
25861 @end itemize
25863 @noindent
25864   Note that these modes apply only to the evaluation of predefined
25865   arithmetic, membership, and comparison operators for signed integer
25866   aritmetic.
25868   For fixed-point arithmetic, checks can be suppressed. But if checks
25869   are enabled
25870   then fixed-point values are always checked for overflow against the
25871   base type for intermediate expressions (that is such checks always
25872   operate in the equivalent of @code{STRICT} mode).
25874   For floating-point, on nearly all architectures, @code{Machine_Overflows}
25875   is False, and IEEE infinities are generated, so overflow exceptions
25876   are never raised. If you want to avoid infinities, and check that
25877   final results of expressions are in range, then you can declare a
25878   constrained floating-point type, and range checks will be carried
25879   out in the normal manner (with infinite values always failing all
25880   range checks).
25883 @c -------------------------
25884 @node Specifying the Desired Mode
25885 @section Specifying the Desired Mode
25887 @noindent
25888 The desired mode of for handling intermediate overflow can be specified using
25889 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
25890 The pragma has the form
25891 @cindex pragma @code{Overflow_Mode}
25893 @smallexample @c ada
25894     pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
25895 @end smallexample
25897 @noindent
25898 where @code{MODE} is one of
25900 @itemize @bullet
25901 @item   @code{STRICT}:  intermediate overflows checked (using base type)
25902 @item   @code{MINIMIZED}: minimize intermediate overflows
25903 @item   @code{ELIMINATED}: eliminate intermediate overflows
25904 @end itemize
25906 @noindent
25907 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25908 @code{minimized} all have the same effect.
25910 If only the @code{General} parameter is present, then the given @code{MODE}
25911 applies
25912 to expressions both within and outside assertions. If both arguments
25913 are present, then @code{General} applies to expressions outside assertions,
25914 and @code{Assertions} applies to expressions within assertions. For example:
25916 @smallexample @c ada
25917    pragma Overflow_Mode
25918      (General => Minimized, Assertions => Eliminated);
25919 @end smallexample
25921 @noindent
25922 specifies that general expressions outside assertions be evaluated
25923 in ``minimize intermediate overflows'' mode, and expressions within
25924 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25925 This is often a reasonable choice, avoiding excessive overhead
25926 outside assertions, but assuring a high degree of portability
25927 when importing code from another compiler, while incurring
25928 the extra overhead for assertion expressions to ensure that
25929 the behavior at run time matches the expected mathematical
25930 behavior.
25932 The @code{Overflow_Mode} pragma has the same scoping and placement
25933 rules as pragma @code{Suppress}, so it can occur either as a
25934 configuration pragma, specifying a default for the whole
25935 program, or in a declarative scope, where it applies to the
25936 remaining declarations and statements in that scope.
25938 Note that pragma @code{Overflow_Mode} does not affect whether
25939 overflow checks are enabled or suppressed. It only controls the
25940 method used to compute intermediate values. To control whether
25941 overflow checking is enabled or suppressed, use pragma @code{Suppress}
25942 or @code{Unsuppress} in the usual manner
25944 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25945 can be used to control the checking mode default (which can be subsequently
25946 overridden using pragmas).
25947 @cindex @option{-gnato?} (gcc)
25948 @cindex @option{-gnato??} (gcc)
25950 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
25952 @itemize @bullet
25953 @item   @code{1}:
25954 use base type for intermediate operations (@code{STRICT})
25955 @item   @code{2}:
25956 minimize intermediate overflows (@code{MINIMIZED})
25957 @item   @code{3}:
25958 eliminate intermediate overflows (@code{ELIMINATED})
25959 @end itemize
25961 @noindent
25962 As with the pragma, if only one digit appears then it applies to all
25963 cases; if two digits are given, then the first applies outside
25964 assertions, and the second within assertions. Thus the equivalent
25965 of the example pragma above would be @option{-gnato23}.
25967 If no digits follow the @option{-gnato}, then it is equivalent to
25968 @option{-gnato11},
25969 causing all intermediate operations to be computed using the base
25970 type (@code{STRICT} mode).
25972 In addition to setting the mode used for computation of intermediate
25973 results, the @code{-gnato} switch also enables overflow checking (which
25974 is suppressed by default). It thus combines the effect of using
25975 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
25978 @c -------------------------
25979 @node Default Settings
25980 @section Default Settings
25982 The default mode for overflow checks is
25984 @smallexample
25985    General => Strict
25986 @end smallexample
25988 @noindent
25989 which causes all computations both inside and outside assertions to use
25990 the base type. In addition overflow checks are suppressed.
25992 This retains compatibility with previous versions of
25993 GNAT which suppressed overflow checks by default and always
25994 used the base type for computation of intermediate results.
25996 The switch @option{-gnato} (with no digits following) is equivalent to
25997 @cindex @option{-gnato} (gcc)
25999 @smallexample
26000    General => Strict
26001 @end smallexample
26003 @noindent
26004 which causes overflow checking of all intermediate overflows
26005 both inside and outside assertions against the base type.
26006 This provides compatibility
26007 with this switch as implemented in previous versions of GNAT.
26009 The pragma @code{Suppress (Overflow_Check)} disables overflow
26010 checking, but it has no effect on the method used for computing
26011 intermediate results.
26013 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
26014 checking, but it has no effect on the method used for computing
26015 intermediate results.
26017 @c -------------------------
26018 @node Implementation Notes
26019 @section Implementation Notes
26021 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
26022 reasonably efficient, and can be generally used. It also helps
26023 to ensure compatibility with code imported from some other
26024 compiler to GNAT.
26026 Setting all intermediate overflows checking (@code{CHECKED} mode)
26027 makes sense if you want to
26028 make sure that your code is compatible with any other possible
26029 Ada implementation. This may be useful in ensuring portability
26030 for code that is to be exported to some other compiler than GNAT.
26033 The Ada standard allows the reassociation of expressions at
26034 the same precedence level if no parentheses are present. For
26035 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
26036 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
26037 introducing or eliminating an overflow exception. The GNAT
26038 compiler never takes advantage of this freedom, and the
26039 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
26040 If you need the other order, you can write the parentheses
26041 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
26043 The use of @code{ELIMINATED} mode will cause the compiler to
26044 automatically include an appropriate arbitrary precision
26045 integer arithmetic package. The compiler will make calls
26046 to this package, though only in cases where it cannot be
26047 sure that @code{Long_Long_Integer} is sufficient to guard against
26048 intermediate overflows. This package does not use dynamic
26049 alllocation, but it does use the secondary stack, so an
26050 appropriate secondary stack package must be present (this
26051 is always true for standard full Ada, but may require
26052 specific steps for restricted run times such as ZFP).
26054 Although @code{ELIMINATED} mode causes expressions to use arbitrary
26055 precision arithmetic, avoiding overflow, the final result
26056 must be in an appropriate range. This is true even if the
26057 final result is of type @code{[Long_[Long_]]Integer'Base}, which
26058 still has the same bounds as its associated constrained
26059 type at run-time.
26061 Currently, the @code{ELIMINATED} mode is only available on target
26062 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
26063 platforms).
26065 @c *******************************
26066 @node Conditional Compilation
26067 @appendix Conditional Compilation
26068 @c *******************************
26069 @cindex Conditional compilation
26071 @noindent
26072 It is often necessary to arrange for a single source program
26073 to serve multiple purposes, where it is compiled in different
26074 ways to achieve these different goals. Some examples of the
26075 need for this feature are
26077 @itemize @bullet
26078 @item  Adapting a program to a different hardware environment
26079 @item  Adapting a program to a different target architecture
26080 @item  Turning debugging features on and off
26081 @item  Arranging for a program to compile with different compilers
26082 @end itemize
26084 @noindent
26085 In C, or C++, the typical approach would be to use the preprocessor
26086 that is defined as part of the language. The Ada language does not
26087 contain such a feature. This is not an oversight, but rather a very
26088 deliberate design decision, based on the experience that overuse of
26089 the preprocessing features in C and C++ can result in programs that
26090 are extremely difficult to maintain. For example, if we have ten
26091 switches that can be on or off, this means that there are a thousand
26092 separate programs, any one of which might not even be syntactically
26093 correct, and even if syntactically correct, the resulting program
26094 might not work correctly. Testing all combinations can quickly become
26095 impossible.
26097 Nevertheless, the need to tailor programs certainly exists, and in
26098 this Appendix we will discuss how this can
26099 be achieved using Ada in general, and GNAT in particular.
26101 @menu
26102 * Use of Boolean Constants::
26103 * Debugging - A Special Case::
26104 * Conditionalizing Declarations::
26105 * Use of Alternative Implementations::
26106 * Preprocessing::
26107 @end menu
26109 @node Use of Boolean Constants
26110 @section Use of Boolean Constants
26112 @noindent
26113 In the case where the difference is simply which code
26114 sequence is executed, the cleanest solution is to use Boolean
26115 constants to control which code is executed.
26117 @smallexample @c ada
26118 @group
26119 FP_Initialize_Required : constant Boolean := True;
26120 @dots{}
26121 if FP_Initialize_Required then
26122 @dots{}
26123 end if;
26124 @end group
26125 @end smallexample
26127 @noindent
26128 Not only will the code inside the @code{if} statement not be executed if
26129 the constant Boolean is @code{False}, but it will also be completely
26130 deleted from the program.
26131 However, the code is only deleted after the @code{if} statement
26132 has been checked for syntactic and semantic correctness.
26133 (In contrast, with preprocessors the code is deleted before the
26134 compiler ever gets to see it, so it is not checked until the switch
26135 is turned on.)
26136 @cindex Preprocessors (contrasted with conditional compilation)
26138 Typically the Boolean constants will be in a separate package,
26139 something like:
26141 @smallexample @c ada
26142 @group
26143 package Config is
26144    FP_Initialize_Required : constant Boolean := True;
26145    Reset_Available        : constant Boolean := False;
26146    @dots{}
26147 end Config;
26148 @end group
26149 @end smallexample
26151 @noindent
26152 The @code{Config} package exists in multiple forms for the various targets,
26153 with an appropriate script selecting the version of @code{Config} needed.
26154 Then any other unit requiring conditional compilation can do a @code{with}
26155 of @code{Config} to make the constants visible.
26158 @node Debugging - A Special Case
26159 @section Debugging - A Special Case
26161 @noindent
26162 A common use of conditional code is to execute statements (for example
26163 dynamic checks, or output of intermediate results) under control of a
26164 debug switch, so that the debugging behavior can be turned on and off.
26165 This can be done using a Boolean constant to control whether the code
26166 is active:
26168 @smallexample @c ada
26169 @group
26170 if Debugging then
26171    Put_Line ("got to the first stage!");
26172 end if;
26173 @end group
26174 @end smallexample
26176 @noindent
26179 @smallexample @c ada
26180 @group
26181 if Debugging and then Temperature > 999.0 then
26182    raise Temperature_Crazy;
26183 end if;
26184 @end group
26185 @end smallexample
26187 @noindent
26188 Since this is a common case, there are special features to deal with
26189 this in a convenient manner. For the case of tests, Ada 2005 has added
26190 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
26191 @cindex pragma @code{Assert}
26192 on the @code{Assert} pragma that has always been available in GNAT, so this
26193 feature may be used with GNAT even if you are not using Ada 2005 features.
26194 The use of pragma @code{Assert} is described in
26195 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
26196 example, the last test could be written:
26198 @smallexample @c ada
26199 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
26200 @end smallexample
26202 @noindent
26203 or simply
26205 @smallexample @c ada
26206 pragma Assert (Temperature <= 999.0);
26207 @end smallexample
26209 @noindent
26210 In both cases, if assertions are active and the temperature is excessive,
26211 the exception @code{Assert_Failure} will be raised, with the given string in
26212 the first case or a string indicating the location of the pragma in the second
26213 case used as the exception message.
26215 You can turn assertions on and off by using the @code{Assertion_Policy}
26216 pragma.
26217 @cindex pragma @code{Assertion_Policy}
26218 This is an Ada 2005 pragma which is implemented in all modes by
26219 GNAT, but only in the latest versions of GNAT which include Ada 2005
26220 capability. Alternatively, you can use the @option{-gnata} switch
26221 @cindex @option{-gnata} switch
26222 to enable assertions from the command line (this is recognized by all versions
26223 of GNAT).
26225 For the example above with the @code{Put_Line}, the GNAT-specific pragma
26226 @code{Debug} can be used:
26227 @cindex pragma @code{Debug}
26229 @smallexample @c ada
26230 pragma Debug (Put_Line ("got to the first stage!"));
26231 @end smallexample
26233 @noindent
26234 If debug pragmas are enabled, the argument, which must be of the form of
26235 a procedure call, is executed (in this case, @code{Put_Line} will be called).
26236 Only one call can be present, but of course a special debugging procedure
26237 containing any code you like can be included in the program and then
26238 called in a pragma @code{Debug} argument as needed.
26240 One advantage of pragma @code{Debug} over the @code{if Debugging then}
26241 construct is that pragma @code{Debug} can appear in declarative contexts,
26242 such as at the very beginning of a procedure, before local declarations have
26243 been elaborated.
26245 Debug pragmas are enabled using either the @option{-gnata} switch that also
26246 controls assertions, or with a separate Debug_Policy pragma.
26247 @cindex pragma @code{Debug_Policy}
26248 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
26249 in Ada 95 and Ada 83 programs as well), and is analogous to
26250 pragma @code{Assertion_Policy} to control assertions.
26252 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
26253 and thus they can appear in @file{gnat.adc} if you are not using a
26254 project file, or in the file designated to contain configuration pragmas
26255 in a project file.
26256 They then apply to all subsequent compilations. In practice the use of
26257 the @option{-gnata} switch is often the most convenient method of controlling
26258 the status of these pragmas.
26260 Note that a pragma is not a statement, so in contexts where a statement
26261 sequence is required, you can't just write a pragma on its own. You have
26262 to add a @code{null} statement.
26264 @smallexample @c ada
26265 @group
26266 if @dots{} then
26267    @dots{} -- some statements
26268 else
26269    pragma Assert (Num_Cases < 10);
26270    null;
26271 end if;
26272 @end group
26273 @end smallexample
26276 @node Conditionalizing Declarations
26277 @section Conditionalizing Declarations
26279 @noindent
26280 In some cases, it may be necessary to conditionalize declarations to meet
26281 different requirements. For example we might want a bit string whose length
26282 is set to meet some hardware message requirement.
26284 In some cases, it may be possible to do this using declare blocks controlled
26285 by conditional constants:
26287 @smallexample @c ada
26288 @group
26289 if Small_Machine then
26290    declare
26291       X : Bit_String (1 .. 10);
26292    begin
26293       @dots{}
26294    end;
26295 else
26296    declare
26297       X : Large_Bit_String (1 .. 1000);
26298    begin
26299       @dots{}
26300    end;
26301 end if;
26302 @end group
26303 @end smallexample
26305 @noindent
26306 Note that in this approach, both declarations are analyzed by the
26307 compiler so this can only be used where both declarations are legal,
26308 even though one of them will not be used.
26310 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
26311 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
26312 that are parameterized by these constants. For example
26314 @smallexample @c ada
26315 @group
26316 for Rec use
26317   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
26318 end record;
26319 @end group
26320 @end smallexample
26322 @noindent
26323 If @code{Bits_Per_Word} is set to 32, this generates either
26325 @smallexample @c ada
26326 @group
26327 for Rec use
26328   Field1 at 0 range 0 .. 32;
26329 end record;
26330 @end group
26331 @end smallexample
26333 @noindent
26334 for the big endian case, or
26336 @smallexample @c ada
26337 @group
26338 for Rec use record
26339   Field1 at 0 range 10 .. 32;
26340 end record;
26341 @end group
26342 @end smallexample
26344 @noindent
26345 for the little endian case. Since a powerful subset of Ada expression
26346 notation is usable for creating static constants, clever use of this
26347 feature can often solve quite difficult problems in conditionalizing
26348 compilation (note incidentally that in Ada 95, the little endian
26349 constant was introduced as @code{System.Default_Bit_Order}, so you do not
26350 need to define this one yourself).
26353 @node Use of Alternative Implementations
26354 @section Use of Alternative Implementations
26356 @noindent
26357 In some cases, none of the approaches described above are adequate. This
26358 can occur for example if the set of declarations required is radically
26359 different for two different configurations.
26361 In this situation, the official Ada way of dealing with conditionalizing
26362 such code is to write separate units for the different cases. As long as
26363 this does not result in excessive duplication of code, this can be done
26364 without creating maintenance problems. The approach is to share common
26365 code as far as possible, and then isolate the code and declarations
26366 that are different. Subunits are often a convenient method for breaking
26367 out a piece of a unit that is to be conditionalized, with separate files
26368 for different versions of the subunit for different targets, where the
26369 build script selects the right one to give to the compiler.
26370 @cindex Subunits (and conditional compilation)
26372 As an example, consider a situation where a new feature in Ada 2005
26373 allows something to be done in a really nice way. But your code must be able
26374 to compile with an Ada 95 compiler. Conceptually you want to say:
26376 @smallexample @c ada
26377 @group
26378 if Ada_2005 then
26379    @dots{} neat Ada 2005 code
26380 else
26381    @dots{} not quite as neat Ada 95 code
26382 end if;
26383 @end group
26384 @end smallexample
26386 @noindent
26387 where @code{Ada_2005} is a Boolean constant.
26389 But this won't work when @code{Ada_2005} is set to @code{False},
26390 since the @code{then} clause will be illegal for an Ada 95 compiler.
26391 (Recall that although such unreachable code would eventually be deleted
26392 by the compiler, it still needs to be legal.  If it uses features
26393 introduced in Ada 2005, it will be illegal in Ada 95.)
26395 So instead we write
26397 @smallexample @c ada
26398 procedure Insert is separate;
26399 @end smallexample
26401 @noindent
26402 Then we have two files for the subunit @code{Insert}, with the two sets of
26403 code.
26404 If the package containing this is called @code{File_Queries}, then we might
26405 have two files
26407 @itemize @bullet
26408 @item    @file{file_queries-insert-2005.adb}
26409 @item    @file{file_queries-insert-95.adb}
26410 @end itemize
26412 @noindent
26413 and the build script renames the appropriate file to
26415 @smallexample
26416 file_queries-insert.adb
26417 @end smallexample
26419 @noindent
26420 and then carries out the compilation.
26422 This can also be done with project files' naming schemes. For example:
26424 @smallexample @c project
26425 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
26426 @end smallexample
26428 @noindent
26429 Note also that with project files it is desirable to use a different extension
26430 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
26431 conflict may arise through another commonly used feature: to declare as part
26432 of the project a set of directories containing all the sources obeying the
26433 default naming scheme.
26435 The use of alternative units is certainly feasible in all situations,
26436 and for example the Ada part of the GNAT run-time is conditionalized
26437 based on the target architecture using this approach. As a specific example,
26438 consider the implementation of the AST feature in VMS. There is one
26439 spec:
26441 @smallexample
26442 s-asthan.ads
26443 @end smallexample
26445 @noindent
26446 which is the same for all architectures, and three bodies:
26448 @table @file
26449 @item    s-asthan.adb
26450 used for all non-VMS operating systems
26451 @item    s-asthan-vms-alpha.adb
26452 used for VMS on the Alpha
26453 @item    s-asthan-vms-ia64.adb
26454 used for VMS on the ia64
26455 @end table
26457 @noindent
26458 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
26459 this operating system feature is not available, and the two remaining
26460 versions interface with the corresponding versions of VMS to provide
26461 VMS-compatible AST handling. The GNAT build script knows the architecture
26462 and operating system, and automatically selects the right version,
26463 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
26465 Another style for arranging alternative implementations is through Ada's
26466 access-to-subprogram facility.
26467 In case some functionality is to be conditionally included,
26468 you can declare an access-to-procedure variable @code{Ref} that is initialized
26469 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
26470 when appropriate.
26471 In some library package, set @code{Ref} to @code{Proc'Access} for some
26472 procedure @code{Proc} that performs the relevant processing.
26473 The initialization only occurs if the library package is included in the
26474 program.
26475 The same idea can also be implemented using tagged types and dispatching
26476 calls.
26479 @node Preprocessing
26480 @section Preprocessing
26481 @cindex Preprocessing
26483 @noindent
26484 Although it is quite possible to conditionalize code without the use of
26485 C-style preprocessing, as described earlier in this section, it is
26486 nevertheless convenient in some cases to use the C approach. Moreover,
26487 older Ada compilers have often provided some preprocessing capability,
26488 so legacy code may depend on this approach, even though it is not
26489 standard.
26491 To accommodate such use, GNAT provides a preprocessor (modeled to a large
26492 extent on the various preprocessors that have been used
26493 with legacy code on other compilers, to enable easier transition).
26495 The preprocessor may be used in two separate modes. It can be used quite
26496 separately from the compiler, to generate a separate output source file
26497 that is then fed to the compiler as a separate step. This is the
26498 @code{gnatprep} utility, whose use is fully described in
26499 @ref{Preprocessing Using gnatprep}.
26500 @cindex @code{gnatprep}
26502 The preprocessing language allows such constructs as
26504 @smallexample
26505 @group
26506 #if DEBUG or PRIORITY > 4 then
26507    bunch of declarations
26508 #else
26509    completely different bunch of declarations
26510 #end if;
26511 @end group
26512 @end smallexample
26514 @noindent
26515 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
26516 defined either on the command line or in a separate file.
26518 The other way of running the preprocessor is even closer to the C style and
26519 often more convenient. In this approach the preprocessing is integrated into
26520 the compilation process. The compiler is fed the preprocessor input which
26521 includes @code{#if} lines etc, and then the compiler carries out the
26522 preprocessing internally and processes the resulting output.
26523 For more details on this approach, see @ref{Integrated Preprocessing}.
26526 @c *******************************
26527 @node Inline Assembler
26528 @appendix Inline Assembler
26529 @c *******************************
26531 @noindent
26532 If you need to write low-level software that interacts directly
26533 with the hardware, Ada provides two ways to incorporate assembly
26534 language code into your program.  First, you can import and invoke
26535 external routines written in assembly language, an Ada feature fully
26536 supported by GNAT@.  However, for small sections of code it may be simpler
26537 or more efficient to include assembly language statements directly
26538 in your Ada source program, using the facilities of the implementation-defined
26539 package @code{System.Machine_Code}, which incorporates the gcc
26540 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
26541 including the following:
26543 @itemize @bullet
26544 @item No need to use non-Ada tools
26545 @item Consistent interface over different targets
26546 @item Automatic usage of the proper calling conventions
26547 @item Access to Ada constants and variables
26548 @item Definition of intrinsic routines
26549 @item Possibility of inlining a subprogram comprising assembler code
26550 @item Code optimizer can take Inline Assembler code into account
26551 @end itemize
26553 This chapter presents a series of examples to show you how to use
26554 the Inline Assembler.  Although it focuses on the Intel x86,
26555 the general approach applies also to other processors.
26556 It is assumed that you are familiar with Ada
26557 and with assembly language programming.
26559 @menu
26560 * Basic Assembler Syntax::
26561 * A Simple Example of Inline Assembler::
26562 * Output Variables in Inline Assembler::
26563 * Input Variables in Inline Assembler::
26564 * Inlining Inline Assembler Code::
26565 * Other Asm Functionality::
26566 @end menu
26568 @c ---------------------------------------------------------------------------
26569 @node Basic Assembler Syntax
26570 @section Basic Assembler Syntax
26572 @noindent
26573 The assembler used by GNAT and gcc is based not on the Intel assembly
26574 language, but rather on a language that descends from the AT&T Unix
26575 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
26576 The following table summarizes the main features of @emph{as} syntax
26577 and points out the differences from the Intel conventions.
26578 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
26579 pre-processor) documentation for further information.
26581 @table @asis
26582 @item Register names
26583 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
26585 Intel: No extra punctuation; for example @code{eax}
26587 @item Immediate operand
26588 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
26590 Intel: No extra punctuation; for example @code{4}
26592 @item Address
26593 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
26595 Intel: No extra punctuation; for example @code{loc}
26597 @item Memory contents
26598 gcc / @emph{as}: No extra punctuation; for example @code{loc}
26600 Intel: Square brackets; for example @code{[loc]}
26602 @item Register contents
26603 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
26605 Intel: Square brackets; for example @code{[eax]}
26607 @item Hexadecimal numbers
26608 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
26610 Intel: Trailing ``h''; for example @code{A0h}
26612 @item Operand size
26613 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
26614 a 16-bit word
26616 Intel: Implicit, deduced by assembler; for example @code{mov}
26618 @item Instruction repetition
26619 gcc / @emph{as}: Split into two lines; for example
26621 @code{rep}
26623 @code{stosl}
26625 Intel: Keep on one line; for example @code{rep stosl}
26627 @item Order of operands
26628 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
26630 Intel: Destination first; for example @code{mov eax, 4}
26631 @end table
26633 @c ---------------------------------------------------------------------------
26634 @node A Simple Example of Inline Assembler
26635 @section A Simple Example of Inline Assembler
26637 @noindent
26638 The following example will generate a single assembly language statement,
26639 @code{nop}, which does nothing.  Despite its lack of run-time effect,
26640 the example will be useful in illustrating the basics of
26641 the Inline Assembler facility.
26643 @smallexample @c ada
26644 @group
26645 with System.Machine_Code; use System.Machine_Code;
26646 procedure Nothing is
26647 begin
26648    Asm ("nop");
26649 end Nothing;
26650 @end group
26651 @end smallexample
26653 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
26654 here it takes one parameter, a @emph{template string} that must be a static
26655 expression and that will form the generated instruction.
26656 @code{Asm} may be regarded as a compile-time procedure that parses
26657 the template string and additional parameters (none here),
26658 from which it generates a sequence of assembly language instructions.
26660 The examples in this chapter will illustrate several of the forms
26661 for invoking @code{Asm}; a complete specification of the syntax
26662 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
26663 Manual}.
26665 Under the standard GNAT conventions, the @code{Nothing} procedure
26666 should be in a file named @file{nothing.adb}.
26667 You can build the executable in the usual way:
26668 @smallexample
26669 gnatmake nothing
26670 @end smallexample
26671 However, the interesting aspect of this example is not its run-time behavior
26672 but rather the generated assembly code.
26673 To see this output, invoke the compiler as follows:
26674 @smallexample
26675    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
26676 @end smallexample
26677 where the options are:
26679 @table @code
26680 @item -c
26681 compile only (no bind or link)
26682 @item -S
26683 generate assembler listing
26684 @item -fomit-frame-pointer
26685 do not set up separate stack frames
26686 @item -gnatp
26687 do not add runtime checks
26688 @end table
26690 This gives a human-readable assembler version of the code. The resulting
26691 file will have the same name as the Ada source file, but with a @code{.s}
26692 extension. In our example, the file @file{nothing.s} has the following
26693 contents:
26695 @smallexample
26696 @group
26697 .file "nothing.adb"
26698 gcc2_compiled.:
26699 ___gnu_compiled_ada:
26700 .text
26701    .align 4
26702 .globl __ada_nothing
26703 __ada_nothing:
26704 #APP
26705    nop
26706 #NO_APP
26707    jmp L1
26708    .align 2,0x90
26710    ret
26711 @end group
26712 @end smallexample
26714 The assembly code you included is clearly indicated by
26715 the compiler, between the @code{#APP} and @code{#NO_APP}
26716 delimiters. The character before the 'APP' and 'NOAPP'
26717 can differ on different targets. For example, GNU/Linux uses '#APP' while
26718 on NT you will see '/APP'.
26720 If you make a mistake in your assembler code (such as using the
26721 wrong size modifier, or using a wrong operand for the instruction) GNAT
26722 will report this error in a temporary file, which will be deleted when
26723 the compilation is finished.  Generating an assembler file will help
26724 in such cases, since you can assemble this file separately using the
26725 @emph{as} assembler that comes with gcc.
26727 Assembling the file using the command
26729 @smallexample
26730 as @file{nothing.s}
26731 @end smallexample
26732 @noindent
26733 will give you error messages whose lines correspond to the assembler
26734 input file, so you can easily find and correct any mistakes you made.
26735 If there are no errors, @emph{as} will generate an object file
26736 @file{nothing.out}.
26738 @c ---------------------------------------------------------------------------
26739 @node Output Variables in Inline Assembler
26740 @section Output Variables in Inline Assembler
26742 @noindent
26743 The examples in this section, showing how to access the processor flags,
26744 illustrate how to specify the destination operands for assembly language
26745 statements.
26747 @smallexample @c ada
26748 @group
26749 with Interfaces; use Interfaces;
26750 with Ada.Text_IO; use Ada.Text_IO;
26751 with System.Machine_Code; use System.Machine_Code;
26752 procedure Get_Flags is
26753    Flags : Unsigned_32;
26754    use ASCII;
26755 begin
26756    Asm ("pushfl"          & LF & HT & -- push flags on stack
26757         "popl %%eax"      & LF & HT & -- load eax with flags
26758         "movl %%eax, %0",             -- store flags in variable
26759         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26760    Put_Line ("Flags register:" & Flags'Img);
26761 end Get_Flags;
26762 @end group
26763 @end smallexample
26765 In order to have a nicely aligned assembly listing, we have separated
26766 multiple assembler statements in the Asm template string with linefeed
26767 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
26768 The resulting section of the assembly output file is:
26770 @smallexample
26771 @group
26772 #APP
26773    pushfl
26774    popl %eax
26775    movl %eax, -40(%ebp)
26776 #NO_APP
26777 @end group
26778 @end smallexample
26780 It would have been legal to write the Asm invocation as:
26782 @smallexample
26783 Asm ("pushfl popl %%eax movl %%eax, %0")
26784 @end smallexample
26786 but in the generated assembler file, this would come out as:
26788 @smallexample
26789 #APP
26790    pushfl popl %eax movl %eax, -40(%ebp)
26791 #NO_APP
26792 @end smallexample
26794 which is not so convenient for the human reader.
26796 We use Ada comments
26797 at the end of each line to explain what the assembler instructions
26798 actually do.  This is a useful convention.
26800 When writing Inline Assembler instructions, you need to precede each register
26801 and variable name with a percent sign.  Since the assembler already requires
26802 a percent sign at the beginning of a register name, you need two consecutive
26803 percent signs for such names in the Asm template string, thus @code{%%eax}.
26804 In the generated assembly code, one of the percent signs will be stripped off.
26806 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
26807 variables: operands you later define using @code{Input} or @code{Output}
26808 parameters to @code{Asm}.
26809 An output variable is illustrated in
26810 the third statement in the Asm template string:
26811 @smallexample
26812 movl %%eax, %0
26813 @end smallexample
26814 The intent is to store the contents of the eax register in a variable that can
26815 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
26816 necessarily work, since the compiler might optimize by using a register
26817 to hold Flags, and the expansion of the @code{movl} instruction would not be
26818 aware of this optimization.  The solution is not to store the result directly
26819 but rather to advise the compiler to choose the correct operand form;
26820 that is the purpose of the @code{%0} output variable.
26822 Information about the output variable is supplied in the @code{Outputs}
26823 parameter to @code{Asm}:
26824 @smallexample
26825 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26826 @end smallexample
26828 The output is defined by the @code{Asm_Output} attribute of the target type;
26829 the general format is
26830 @smallexample
26831 Type'Asm_Output (constraint_string, variable_name)
26832 @end smallexample
26834 The constraint string directs the compiler how
26835 to store/access the associated variable.  In the example
26836 @smallexample
26837 Unsigned_32'Asm_Output ("=m", Flags);
26838 @end smallexample
26839 the @code{"m"} (memory) constraint tells the compiler that the variable
26840 @code{Flags} should be stored in a memory variable, thus preventing
26841 the optimizer from keeping it in a register.  In contrast,
26842 @smallexample
26843 Unsigned_32'Asm_Output ("=r", Flags);
26844 @end smallexample
26845 uses the @code{"r"} (register) constraint, telling the compiler to
26846 store the variable in a register.
26848 If the constraint is preceded by the equal character (@strong{=}), it tells
26849 the compiler that the variable will be used to store data into it.
26851 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26852 allowing the optimizer to choose whatever it deems best.
26854 There are a fairly large number of constraints, but the ones that are
26855 most useful (for the Intel x86 processor) are the following:
26857 @table @code
26858 @item =
26859 output constraint
26860 @item g
26861 global (i.e.@: can be stored anywhere)
26862 @item m
26863 in memory
26864 @item I
26865 a constant
26866 @item a
26867 use eax
26868 @item b
26869 use ebx
26870 @item c
26871 use ecx
26872 @item d
26873 use edx
26874 @item S
26875 use esi
26876 @item D
26877 use edi
26878 @item r
26879 use one of eax, ebx, ecx or edx
26880 @item q
26881 use one of eax, ebx, ecx, edx, esi or edi
26882 @end table
26884 The full set of constraints is described in the gcc and @emph{as}
26885 documentation; note that it is possible to combine certain constraints
26886 in one constraint string.
26888 You specify the association of an output variable with an assembler operand
26889 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26890 integer.  Thus in
26891 @smallexample @c ada
26892 @group
26893 Asm ("pushfl"          & LF & HT & -- push flags on stack
26894      "popl %%eax"      & LF & HT & -- load eax with flags
26895      "movl %%eax, %0",             -- store flags in variable
26896      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26897 @end group
26898 @end smallexample
26899 @noindent
26900 @code{%0} will be replaced in the expanded code by the appropriate operand,
26901 whatever
26902 the compiler decided for the @code{Flags} variable.
26904 In general, you may have any number of output variables:
26905 @itemize @bullet
26906 @item
26907 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26908 @item
26909 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26910 of @code{Asm_Output} attributes
26911 @end itemize
26913 For example:
26914 @smallexample @c ada
26915 @group
26916 Asm ("movl %%eax, %0" & LF & HT &
26917      "movl %%ebx, %1" & LF & HT &
26918      "movl %%ecx, %2",
26919      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
26920                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
26921                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
26922 @end group
26923 @end smallexample
26924 @noindent
26925 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26926 in the Ada program.
26928 As a variation on the @code{Get_Flags} example, we can use the constraints
26929 string to direct the compiler to store the eax register into the @code{Flags}
26930 variable, instead of including the store instruction explicitly in the
26931 @code{Asm} template string:
26933 @smallexample @c ada
26934 @group
26935 with Interfaces; use Interfaces;
26936 with Ada.Text_IO; use Ada.Text_IO;
26937 with System.Machine_Code; use System.Machine_Code;
26938 procedure Get_Flags_2 is
26939    Flags : Unsigned_32;
26940    use ASCII;
26941 begin
26942    Asm ("pushfl"      & LF & HT & -- push flags on stack
26943         "popl %%eax",             -- save flags in eax
26944         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26945    Put_Line ("Flags register:" & Flags'Img);
26946 end Get_Flags_2;
26947 @end group
26948 @end smallexample
26950 @noindent
26951 The @code{"a"} constraint tells the compiler that the @code{Flags}
26952 variable will come from the eax register. Here is the resulting code:
26954 @smallexample
26955 @group
26956 #APP
26957    pushfl
26958    popl %eax
26959 #NO_APP
26960    movl %eax,-40(%ebp)
26961 @end group
26962 @end smallexample
26964 @noindent
26965 The compiler generated the store of eax into Flags after
26966 expanding the assembler code.
26968 Actually, there was no need to pop the flags into the eax register;
26969 more simply, we could just pop the flags directly into the program variable:
26971 @smallexample @c ada
26972 @group
26973 with Interfaces; use Interfaces;
26974 with Ada.Text_IO; use Ada.Text_IO;
26975 with System.Machine_Code; use System.Machine_Code;
26976 procedure Get_Flags_3 is
26977    Flags : Unsigned_32;
26978    use ASCII;
26979 begin
26980    Asm ("pushfl"  & LF & HT & -- push flags on stack
26981         "pop %0",             -- save flags in Flags
26982         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26983    Put_Line ("Flags register:" & Flags'Img);
26984 end Get_Flags_3;
26985 @end group
26986 @end smallexample
26988 @c ---------------------------------------------------------------------------
26989 @node Input Variables in Inline Assembler
26990 @section Input Variables in Inline Assembler
26992 @noindent
26993 The example in this section illustrates how to specify the source operands
26994 for assembly language statements.
26995 The program simply increments its input value by 1:
26997 @smallexample @c ada
26998 @group
26999 with Interfaces; use Interfaces;
27000 with Ada.Text_IO; use Ada.Text_IO;
27001 with System.Machine_Code; use System.Machine_Code;
27002 procedure Increment is
27004    function Incr (Value : Unsigned_32) return Unsigned_32 is
27005       Result : Unsigned_32;
27006    begin
27007       Asm ("incl %0",
27008            Outputs => Unsigned_32'Asm_Output ("=a", Result),
27009            Inputs  => Unsigned_32'Asm_Input ("a", Value));
27010       return Result;
27011    end Incr;
27013    Value : Unsigned_32;
27015 begin
27016    Value := 5;
27017    Put_Line ("Value before is" & Value'Img);
27018    Value := Incr (Value);
27019    Put_Line ("Value after is" & Value'Img);
27020 end Increment;
27021 @end group
27022 @end smallexample
27024 The @code{Outputs} parameter to @code{Asm} specifies
27025 that the result will be in the eax register and that it is to be stored
27026 in the @code{Result} variable.
27028 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
27029 but with an @code{Asm_Input} attribute.
27030 The @code{"="} constraint, indicating an output value, is not present.
27032 You can have multiple input variables, in the same way that you can have more
27033 than one output variable.
27035 The parameter count (%0, %1) etc, still starts at the first output statement,
27036 and continues with the input statements.
27038 Just as the @code{Outputs} parameter causes the register to be stored into the
27039 target variable after execution of the assembler statements, so does the
27040 @code{Inputs} parameter cause its variable to be loaded into the register
27041 before execution of the assembler statements.
27043 Thus the effect of the @code{Asm} invocation is:
27044 @enumerate
27045 @item load the 32-bit value of @code{Value} into eax
27046 @item execute the @code{incl %eax} instruction
27047 @item store the contents of eax into the @code{Result} variable
27048 @end enumerate
27050 The resulting assembler file (with @option{-O2} optimization) contains:
27051 @smallexample
27052 @group
27053 _increment__incr.1:
27054    subl $4,%esp
27055    movl 8(%esp),%eax
27056 #APP
27057    incl %eax
27058 #NO_APP
27059    movl %eax,%edx
27060    movl %ecx,(%esp)
27061    addl $4,%esp
27062    ret
27063 @end group
27064 @end smallexample
27066 @c ---------------------------------------------------------------------------
27067 @node Inlining Inline Assembler Code
27068 @section Inlining Inline Assembler Code
27070 @noindent
27071 For a short subprogram such as the @code{Incr} function in the previous
27072 section, the overhead of the call and return (creating / deleting the stack
27073 frame) can be significant, compared to the amount of code in the subprogram
27074 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
27075 which directs the compiler to expand invocations of the subprogram at the
27076 point(s) of call, instead of setting up a stack frame for out-of-line calls.
27077 Here is the resulting program:
27079 @smallexample @c ada
27080 @group
27081 with Interfaces; use Interfaces;
27082 with Ada.Text_IO; use Ada.Text_IO;
27083 with System.Machine_Code; use System.Machine_Code;
27084 procedure Increment_2 is
27086    function Incr (Value : Unsigned_32) return Unsigned_32 is
27087       Result : Unsigned_32;
27088    begin
27089       Asm ("incl %0",
27090            Outputs => Unsigned_32'Asm_Output ("=a", Result),
27091            Inputs  => Unsigned_32'Asm_Input ("a", Value));
27092       return Result;
27093    end Incr;
27094    pragma Inline (Increment);
27096    Value : Unsigned_32;
27098 begin
27099    Value := 5;
27100    Put_Line ("Value before is" & Value'Img);
27101    Value := Increment (Value);
27102    Put_Line ("Value after is" & Value'Img);
27103 end Increment_2;
27104 @end group
27105 @end smallexample
27107 Compile the program with both optimization (@option{-O2}) and inlining
27108 (@option{-gnatn}) enabled.
27110 The @code{Incr} function is still compiled as usual, but at the
27111 point in @code{Increment} where our function used to be called:
27113 @smallexample
27114 @group
27115 pushl %edi
27116 call _increment__incr.1
27117 @end group
27118 @end smallexample
27120 @noindent
27121 the code for the function body directly appears:
27123 @smallexample
27124 @group
27125 movl %esi,%eax
27126 #APP
27127    incl %eax
27128 #NO_APP
27129    movl %eax,%edx
27130 @end group
27131 @end smallexample
27133 @noindent
27134 thus saving the overhead of stack frame setup and an out-of-line call.
27136 @c ---------------------------------------------------------------------------
27137 @node Other Asm Functionality
27138 @section Other @code{Asm} Functionality
27140 @noindent
27141 This section describes two important parameters to the @code{Asm}
27142 procedure: @code{Clobber}, which identifies register usage;
27143 and @code{Volatile}, which inhibits unwanted optimizations.
27145 @menu
27146 * The Clobber Parameter::
27147 * The Volatile Parameter::
27148 @end menu
27150 @c ---------------------------------------------------------------------------
27151 @node The Clobber Parameter
27152 @subsection The @code{Clobber} Parameter
27154 @noindent
27155 One of the dangers of intermixing assembly language and a compiled language
27156 such as Ada is that the compiler needs to be aware of which registers are
27157 being used by the assembly code.  In some cases, such as the earlier examples,
27158 the constraint string is sufficient to indicate register usage (e.g.,
27159 @code{"a"} for
27160 the eax register).  But more generally, the compiler needs an explicit
27161 identification of the registers that are used by the Inline Assembly
27162 statements.
27164 Using a register that the compiler doesn't know about
27165 could be a side effect of an instruction (like @code{mull}
27166 storing its result in both eax and edx).
27167 It can also arise from explicit register usage in your
27168 assembly code; for example:
27169 @smallexample
27170 @group
27171 Asm ("movl %0, %%ebx" & LF & HT &
27172      "movl %%ebx, %1",
27173      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27174      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
27175 @end group
27176 @end smallexample
27177 @noindent
27178 where the compiler (since it does not analyze the @code{Asm} template string)
27179 does not know you are using the ebx register.
27181 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
27182 to identify the registers that will be used by your assembly code:
27184 @smallexample
27185 @group
27186 Asm ("movl %0, %%ebx" & LF & HT &
27187      "movl %%ebx, %1",
27188      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27189      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
27190      Clobber => "ebx");
27191 @end group
27192 @end smallexample
27194 The Clobber parameter is a static string expression specifying the
27195 register(s) you are using.  Note that register names are @emph{not} prefixed
27196 by a percent sign. Also, if more than one register is used then their names
27197 are separated by commas; e.g., @code{"eax, ebx"}
27199 The @code{Clobber} parameter has several additional uses:
27200 @enumerate
27201 @item Use ``register'' name @code{cc} to indicate that flags might have changed
27202 @item Use ``register'' name @code{memory} if you changed a memory location
27203 @end enumerate
27205 @c ---------------------------------------------------------------------------
27206 @node The Volatile Parameter
27207 @subsection The @code{Volatile} Parameter
27208 @cindex Volatile parameter
27210 @noindent
27211 Compiler optimizations in the presence of Inline Assembler may sometimes have
27212 unwanted effects.  For example, when an @code{Asm} invocation with an input
27213 variable is inside a loop, the compiler might move the loading of the input
27214 variable outside the loop, regarding it as a one-time initialization.
27216 If this effect is not desired, you can disable such optimizations by setting
27217 the @code{Volatile} parameter to @code{True}; for example:
27219 @smallexample @c ada
27220 @group
27221 Asm ("movl %0, %%ebx" & LF & HT &
27222      "movl %%ebx, %1",
27223      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
27224      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
27225      Clobber  => "ebx",
27226      Volatile => True);
27227 @end group
27228 @end smallexample
27230 By default, @code{Volatile} is set to @code{False} unless there is no
27231 @code{Outputs} parameter.
27233 Although setting @code{Volatile} to @code{True} prevents unwanted
27234 optimizations, it will also disable other optimizations that might be
27235 important for efficiency. In general, you should set @code{Volatile}
27236 to @code{True} only if the compiler's optimizations have created
27237 problems.
27238 @c END OF INLINE ASSEMBLER CHAPTER
27239 @c ===============================
27241 @c ***********************************
27242 @c * Compatibility and Porting Guide *
27243 @c ***********************************
27244 @node Compatibility and Porting Guide
27245 @appendix Compatibility and Porting Guide
27247 @noindent
27248 This chapter describes the compatibility issues that may arise between
27249 GNAT and other Ada compilation systems (including those for Ada 83),
27250 and shows how GNAT can expedite porting
27251 applications developed in other Ada environments.
27253 @menu
27254 * Compatibility with Ada 83::
27255 * Compatibility between Ada 95 and Ada 2005::
27256 * Implementation-dependent characteristics::
27257 * Compatibility with Other Ada Systems::
27258 * Representation Clauses::
27259 @ifclear vms
27260 @c Brief section is only in non-VMS version
27261 @c Full chapter is in VMS version
27262 * Compatibility with HP Ada 83::
27263 @end ifclear
27264 @ifset vms
27265 * Transitioning to 64-Bit GNAT for OpenVMS::
27266 @end ifset
27267 @end menu
27269 @node Compatibility with Ada 83
27270 @section Compatibility with Ada 83
27271 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
27273 @noindent
27274 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
27275 particular, the design intention was that the difficulties associated
27276 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
27277 that occur when moving from one Ada 83 system to another.
27279 However, there are a number of points at which there are minor
27280 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
27281 full details of these issues,
27282 and should be consulted for a complete treatment.
27283 In practice the
27284 following subsections treat the most likely issues to be encountered.
27286 @menu
27287 * Legal Ada 83 programs that are illegal in Ada 95::
27288 * More deterministic semantics::
27289 * Changed semantics::
27290 * Other language compatibility issues::
27291 @end menu
27293 @node Legal Ada 83 programs that are illegal in Ada 95
27294 @subsection Legal Ada 83 programs that are illegal in Ada 95
27296 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
27297 Ada 95 and thus also in Ada 2005:
27299 @table @emph
27300 @item Character literals
27301 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
27302 @code{Wide_Character} as a new predefined character type, some uses of
27303 character literals that were legal in Ada 83 are illegal in Ada 95.
27304 For example:
27305 @smallexample @c ada
27306    for Char in 'A' .. 'Z' loop @dots{} end loop;
27307 @end smallexample
27309 @noindent
27310 The problem is that @code{'A'} and @code{'Z'} could be from either
27311 @code{Character} or @code{Wide_Character}.  The simplest correction
27312 is to make the type explicit; e.g.:
27313 @smallexample @c ada
27314    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
27315 @end smallexample
27317 @item New reserved words
27318 The identifiers @code{abstract}, @code{aliased}, @code{protected},
27319 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
27320 Existing Ada 83 code using any of these identifiers must be edited to
27321 use some alternative name.
27323 @item Freezing rules
27324 The rules in Ada 95 are slightly different with regard to the point at
27325 which entities are frozen, and representation pragmas and clauses are
27326 not permitted past the freeze point.  This shows up most typically in
27327 the form of an error message complaining that a representation item
27328 appears too late, and the appropriate corrective action is to move
27329 the item nearer to the declaration of the entity to which it refers.
27331 A particular case is that representation pragmas
27332 @ifset vms
27333 (including the
27334 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
27335 @end ifset
27336 cannot be applied to a subprogram body.  If necessary, a separate subprogram
27337 declaration must be introduced to which the pragma can be applied.
27339 @item Optional bodies for library packages
27340 In Ada 83, a package that did not require a package body was nevertheless
27341 allowed to have one.  This lead to certain surprises in compiling large
27342 systems (situations in which the body could be unexpectedly ignored by the
27343 binder).  In Ada 95, if a package does not require a body then it is not
27344 permitted to have a body.  To fix this problem, simply remove a redundant
27345 body if it is empty, or, if it is non-empty, introduce a dummy declaration
27346 into the spec that makes the body required.  One approach is to add a private
27347 part to the package declaration (if necessary), and define a parameterless
27348 procedure called @code{Requires_Body}, which must then be given a dummy
27349 procedure body in the package body, which then becomes required.
27350 Another approach (assuming that this does not introduce elaboration
27351 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
27352 since one effect of this pragma is to require the presence of a package body.
27354 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
27355 In Ada 95, the exception @code{Numeric_Error} is a renaming of
27356 @code{Constraint_Error}.
27357 This means that it is illegal to have separate exception handlers for
27358 the two exceptions.  The fix is simply to remove the handler for the
27359 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
27360 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
27362 @item Indefinite subtypes in generics
27363 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
27364 as the actual for a generic formal private type, but then the instantiation
27365 would be illegal if there were any instances of declarations of variables
27366 of this type in the generic body.  In Ada 95, to avoid this clear violation
27367 of the methodological principle known as the ``contract model'',
27368 the generic declaration explicitly indicates whether
27369 or not such instantiations are permitted.  If a generic formal parameter
27370 has explicit unknown discriminants, indicated by using @code{(<>)} after the
27371 subtype name, then it can be instantiated with indefinite types, but no
27372 stand-alone variables can be declared of this type.  Any attempt to declare
27373 such a variable will result in an illegality at the time the generic is
27374 declared.  If the @code{(<>)} notation is not used, then it is illegal
27375 to instantiate the generic with an indefinite type.
27376 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
27377 It will show up as a compile time error, and
27378 the fix is usually simply to add the @code{(<>)} to the generic declaration.
27379 @end table
27381 @node More deterministic semantics
27382 @subsection More deterministic semantics
27384 @table @emph
27385 @item Conversions
27386 Conversions from real types to integer types round away from 0.  In Ada 83
27387 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
27388 implementation freedom was intended to support unbiased rounding in
27389 statistical applications, but in practice it interfered with portability.
27390 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
27391 is required.  Numeric code may be affected by this change in semantics.
27392 Note, though, that this issue is no worse than already existed in Ada 83
27393 when porting code from one vendor to another.
27395 @item Tasking
27396 The Real-Time Annex introduces a set of policies that define the behavior of
27397 features that were implementation dependent in Ada 83, such as the order in
27398 which open select branches are executed.
27399 @end table
27401 @node Changed semantics
27402 @subsection Changed semantics
27404 @noindent
27405 The worst kind of incompatibility is one where a program that is legal in
27406 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
27407 possible in Ada 83.  Fortunately this is extremely rare, but the one
27408 situation that you should be alert to is the change in the predefined type
27409 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
27411 @table @emph
27412 @item Range of type @code{Character}
27413 The range of @code{Standard.Character} is now the full 256 characters
27414 of Latin-1, whereas in most Ada 83 implementations it was restricted
27415 to 128 characters. Although some of the effects of
27416 this change will be manifest in compile-time rejection of legal
27417 Ada 83 programs it is possible for a working Ada 83 program to have
27418 a different effect in Ada 95, one that was not permitted in Ada 83.
27419 As an example, the expression
27420 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
27421 delivers @code{255} as its value.
27422 In general, you should look at the logic of any
27423 character-processing Ada 83 program and see whether it needs to be adapted
27424 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
27425 character handling package that may be relevant if code needs to be adapted
27426 to account for the additional Latin-1 elements.
27427 The desirable fix is to
27428 modify the program to accommodate the full character set, but in some cases
27429 it may be convenient to define a subtype or derived type of Character that
27430 covers only the restricted range.
27431 @cindex Latin-1
27432 @end table
27434 @node Other language compatibility issues
27435 @subsection Other language compatibility issues
27437 @table @emph
27438 @item @option{-gnat83} switch
27439 All implementations of GNAT provide a switch that causes GNAT to operate
27440 in Ada 83 mode.  In this mode, some but not all compatibility problems
27441 of the type described above are handled automatically.  For example, the
27442 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
27443 as identifiers as in Ada 83.
27444 However,
27445 in practice, it is usually advisable to make the necessary modifications
27446 to the program to remove the need for using this switch.
27447 See @ref{Compiling Different Versions of Ada}.
27449 @item Support for removed Ada 83 pragmas and attributes
27450 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
27451 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
27452 compilers are allowed, but not required, to implement these missing
27453 elements.  In contrast with some other compilers, GNAT implements all
27454 such pragmas and attributes, eliminating this compatibility concern.  These
27455 include @code{pragma Interface} and the floating point type attributes
27456 (@code{Emax}, @code{Mantissa}, etc.), among other items.
27457 @end table
27460 @node Compatibility between Ada 95 and Ada 2005
27461 @section Compatibility between Ada 95 and Ada 2005
27462 @cindex Compatibility between Ada 95 and Ada 2005
27464 @noindent
27465 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
27466 a number of incompatibilities. Several are enumerated below;
27467 for a complete description please see the
27468 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
27469 @cite{Rationale for Ada 2005}.
27471 @table @emph
27472 @item New reserved words.
27473 The words @code{interface}, @code{overriding} and @code{synchronized} are
27474 reserved in Ada 2005.
27475 A pre-Ada 2005 program that uses any of these as an identifier will be
27476 illegal.
27478 @item New declarations in predefined packages.
27479 A number of packages in the predefined environment contain new declarations:
27480 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
27481 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
27482 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
27483 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
27484 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
27485 If an Ada 95 program does a @code{with} and @code{use} of any of these
27486 packages, the new declarations may cause name clashes.
27488 @item Access parameters.
27489 A nondispatching subprogram with an access parameter cannot be renamed
27490 as a dispatching operation.  This was permitted in Ada 95.
27492 @item Access types, discriminants, and constraints.
27493 Rule changes in this area have led to some incompatibilities; for example,
27494 constrained subtypes of some access types are not permitted in Ada 2005.
27496 @item Aggregates for limited types.
27497 The allowance of aggregates for limited types in Ada 2005 raises the
27498 possibility of ambiguities in legal Ada 95 programs, since additional types
27499 now need to be considered in expression resolution.
27501 @item Fixed-point multiplication and division.
27502 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
27503 were legal in Ada 95 and invoked the predefined versions of these operations,
27504 are now ambiguous.
27505 The ambiguity may be resolved either by applying a type conversion to the
27506 expression, or by explicitly invoking the operation from package
27507 @code{Standard}.
27509 @item Return-by-reference types.
27510 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
27511 can declare a function returning a value from an anonymous access type.
27512 @end table
27515 @node Implementation-dependent characteristics
27516 @section Implementation-dependent characteristics
27517 @noindent
27518 Although the Ada language defines the semantics of each construct as
27519 precisely as practical, in some situations (for example for reasons of
27520 efficiency, or where the effect is heavily dependent on the host or target
27521 platform) the implementation is allowed some freedom.  In porting Ada 83
27522 code to GNAT, you need to be aware of whether / how the existing code
27523 exercised such implementation dependencies.  Such characteristics fall into
27524 several categories, and GNAT offers specific support in assisting the
27525 transition from certain Ada 83 compilers.
27527 @menu
27528 * Implementation-defined pragmas::
27529 * Implementation-defined attributes::
27530 * Libraries::
27531 * Elaboration order::
27532 * Target-specific aspects::
27533 @end menu
27535 @node Implementation-defined pragmas
27536 @subsection Implementation-defined pragmas
27538 @noindent
27539 Ada compilers are allowed to supplement the language-defined pragmas, and
27540 these are a potential source of non-portability.  All GNAT-defined pragmas
27541 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
27542 Reference Manual}, and these include several that are specifically
27543 intended to correspond to other vendors' Ada 83 pragmas.
27544 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
27545 For compatibility with HP Ada 83, GNAT supplies the pragmas
27546 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
27547 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
27548 and @code{Volatile}.
27549 Other relevant pragmas include @code{External} and @code{Link_With}.
27550 Some vendor-specific
27551 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
27552 recognized, thus
27553 avoiding compiler rejection of units that contain such pragmas; they are not
27554 relevant in a GNAT context and hence are not otherwise implemented.
27556 @node Implementation-defined attributes
27557 @subsection Implementation-defined attributes
27559 Analogous to pragmas, the set of attributes may be extended by an
27560 implementation.  All GNAT-defined attributes are described in
27561 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
27562 Manual}, and these include several that are specifically intended
27563 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
27564 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
27565 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
27566 @code{Type_Class}.
27568 @node Libraries
27569 @subsection Libraries
27570 @noindent
27571 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
27572 code uses vendor-specific libraries then there are several ways to manage
27573 this in Ada 95 or Ada 2005:
27574 @enumerate
27575 @item
27576 If the source code for the libraries (specs and bodies) are
27577 available, then the libraries can be migrated in the same way as the
27578 application.
27579 @item
27580 If the source code for the specs but not the bodies are
27581 available, then you can reimplement the bodies.
27582 @item
27583 Some features introduced by Ada 95 obviate the need for library support.  For
27584 example most Ada 83 vendors supplied a package for unsigned integers.  The
27585 Ada 95 modular type feature is the preferred way to handle this need, so
27586 instead of migrating or reimplementing the unsigned integer package it may
27587 be preferable to retrofit the application using modular types.
27588 @end enumerate
27590 @node Elaboration order
27591 @subsection Elaboration order
27592 @noindent
27593 The implementation can choose any elaboration order consistent with the unit
27594 dependency relationship.  This freedom means that some orders can result in
27595 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
27596 to invoke a subprogram its body has been elaborated, or to instantiate a
27597 generic before the generic body has been elaborated.  By default GNAT
27598 attempts to choose a safe order (one that will not encounter access before
27599 elaboration problems) by implicitly inserting @code{Elaborate} or
27600 @code{Elaborate_All} pragmas where
27601 needed.  However, this can lead to the creation of elaboration circularities
27602 and a resulting rejection of the program by gnatbind.  This issue is
27603 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
27604 In brief, there are several
27605 ways to deal with this situation:
27607 @itemize @bullet
27608 @item
27609 Modify the program to eliminate the circularities, e.g.@: by moving
27610 elaboration-time code into explicitly-invoked procedures
27611 @item
27612 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
27613 @code{Elaborate} pragmas, and then inhibit the generation of implicit
27614 @code{Elaborate_All}
27615 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
27616 (by selectively suppressing elaboration checks via pragma
27617 @code{Suppress(Elaboration_Check)} when it is safe to do so).
27618 @end itemize
27620 @node Target-specific aspects
27621 @subsection Target-specific aspects
27622 @noindent
27623 Low-level applications need to deal with machine addresses, data
27624 representations, interfacing with assembler code, and similar issues.  If
27625 such an Ada 83 application is being ported to different target hardware (for
27626 example where the byte endianness has changed) then you will need to
27627 carefully examine the program logic; the porting effort will heavily depend
27628 on the robustness of the original design.  Moreover, Ada 95 (and thus
27629 Ada 2005) are sometimes
27630 incompatible with typical Ada 83 compiler practices regarding implicit
27631 packing, the meaning of the Size attribute, and the size of access values.
27632 GNAT's approach to these issues is described in @ref{Representation Clauses}.
27634 @node Compatibility with Other Ada Systems
27635 @section Compatibility with Other Ada Systems
27637 @noindent
27638 If programs avoid the use of implementation dependent and
27639 implementation defined features, as documented in the @cite{Ada
27640 Reference Manual}, there should be a high degree of portability between
27641 GNAT and other Ada systems.  The following are specific items which
27642 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
27643 compilers, but do not affect porting code to GNAT@.
27644 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
27645 the following issues may or may not arise for Ada 2005 programs
27646 when other compilers appear.)
27648 @table @emph
27649 @item Ada 83 Pragmas and Attributes
27650 Ada 95 compilers are allowed, but not required, to implement the missing
27651 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
27652 GNAT implements all such pragmas and attributes, eliminating this as
27653 a compatibility concern, but some other Ada 95 compilers reject these
27654 pragmas and attributes.
27656 @item Specialized Needs Annexes
27657 GNAT implements the full set of special needs annexes.  At the
27658 current time, it is the only Ada 95 compiler to do so.  This means that
27659 programs making use of these features may not be portable to other Ada
27660 95 compilation systems.
27662 @item Representation Clauses
27663 Some other Ada 95 compilers implement only the minimal set of
27664 representation clauses required by the Ada 95 reference manual.  GNAT goes
27665 far beyond this minimal set, as described in the next section.
27666 @end table
27668 @node Representation Clauses
27669 @section Representation Clauses
27671 @noindent
27672 The Ada 83 reference manual was quite vague in describing both the minimal
27673 required implementation of representation clauses, and also their precise
27674 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
27675 minimal set of capabilities required is still quite limited.
27677 GNAT implements the full required set of capabilities in
27678 Ada 95 and Ada 2005, but also goes much further, and in particular
27679 an effort has been made to be compatible with existing Ada 83 usage to the
27680 greatest extent possible.
27682 A few cases exist in which Ada 83 compiler behavior is incompatible with
27683 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
27684 intentional or accidental dependence on specific implementation dependent
27685 characteristics of these Ada 83 compilers.  The following is a list of
27686 the cases most likely to arise in existing Ada 83 code.
27688 @table @emph
27689 @item Implicit Packing
27690 Some Ada 83 compilers allowed a Size specification to cause implicit
27691 packing of an array or record.  This could cause expensive implicit
27692 conversions for change of representation in the presence of derived
27693 types, and the Ada design intends to avoid this possibility.
27694 Subsequent AI's were issued to make it clear that such implicit
27695 change of representation in response to a Size clause is inadvisable,
27696 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27697 Reference Manuals as implementation advice that is followed by GNAT@.
27698 The problem will show up as an error
27699 message rejecting the size clause.  The fix is simply to provide
27700 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27701 a Component_Size clause.
27703 @item Meaning of Size Attribute
27704 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27705 the minimal number of bits required to hold values of the type.  For example,
27706 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27707 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
27708 some 32 in this situation.  This problem will usually show up as a compile
27709 time error, but not always.  It is a good idea to check all uses of the
27710 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
27711 Object_Size can provide a useful way of duplicating the behavior of
27712 some Ada 83 compiler systems.
27714 @item Size of Access Types
27715 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27716 and that therefore it will be the same size as a System.Address value.  This
27717 assumption is true for GNAT in most cases with one exception.  For the case of
27718 a pointer to an unconstrained array type (where the bounds may vary from one
27719 value of the access type to another), the default is to use a ``fat pointer'',
27720 which is represented as two separate pointers, one to the bounds, and one to
27721 the array.  This representation has a number of advantages, including improved
27722 efficiency.  However, it may cause some difficulties in porting existing Ada 83
27723 code which makes the assumption that, for example, pointers fit in 32 bits on
27724 a machine with 32-bit addressing.
27726 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27727 access types in this case (where the designated type is an unconstrained array
27728 type).  These thin pointers are indeed the same size as a System.Address value.
27729 To specify a thin pointer, use a size clause for the type, for example:
27731 @smallexample @c ada
27732 type X is access all String;
27733 for X'Size use Standard'Address_Size;
27734 @end smallexample
27736 @noindent
27737 which will cause the type X to be represented using a single pointer.
27738 When using this representation, the bounds are right behind the array.
27739 This representation is slightly less efficient, and does not allow quite
27740 such flexibility in the use of foreign pointers or in using the
27741 Unrestricted_Access attribute to create pointers to non-aliased objects.
27742 But for any standard portable use of the access type it will work in
27743 a functionally correct manner and allow porting of existing code.
27744 Note that another way of forcing a thin pointer representation
27745 is to use a component size clause for the element size in an array,
27746 or a record representation clause for an access field in a record.
27747 @end table
27749 @ifclear vms
27750 @c This brief section is only in the non-VMS version
27751 @c The complete chapter on HP Ada is in the VMS version
27752 @node Compatibility with HP Ada 83
27753 @section Compatibility with HP Ada 83
27755 @noindent
27756 The VMS version of GNAT fully implements all the pragmas and attributes
27757 provided by HP Ada 83, as well as providing the standard HP Ada 83
27758 libraries, including Starlet.  In addition, data layouts and parameter
27759 passing conventions are highly compatible.  This means that porting
27760 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27761 most other porting efforts.  The following are some of the most
27762 significant differences between GNAT and HP Ada 83.
27764 @table @emph
27765 @item Default floating-point representation
27766 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27767 it is VMS format.  GNAT does implement the necessary pragmas
27768 (Long_Float, Float_Representation) for changing this default.
27770 @item System
27771 The package System in GNAT exactly corresponds to the definition in the
27772 Ada 95 reference manual, which means that it excludes many of the
27773 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
27774 that contains the additional definitions, and a special pragma,
27775 Extend_System allows this package to be treated transparently as an
27776 extension of package System.
27778 @item To_Address
27779 The definitions provided by Aux_DEC are exactly compatible with those
27780 in the HP Ada 83 version of System, with one exception.
27781 HP Ada provides the following declarations:
27783 @smallexample @c ada
27784 TO_ADDRESS (INTEGER)
27785 TO_ADDRESS (UNSIGNED_LONGWORD)
27786 TO_ADDRESS (@i{universal_integer})
27787 @end smallexample
27789 @noindent
27790 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27791 an extension to Ada 83 not strictly compatible with the reference manual.
27792 In GNAT, we are constrained to be exactly compatible with the standard,
27793 and this means we cannot provide this capability.  In HP Ada 83, the
27794 point of this definition is to deal with a call like:
27796 @smallexample @c ada
27797 TO_ADDRESS (16#12777#);
27798 @end smallexample
27800 @noindent
27801 Normally, according to the Ada 83 standard, one would expect this to be
27802 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27803 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
27804 definition using @i{universal_integer} takes precedence.
27806 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27807 is not possible to be 100% compatible.  Since there are many programs using
27808 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27809 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27810 declarations provided in the GNAT version of AUX_Dec are:
27812 @smallexample @c ada
27813 function To_Address (X : Integer) return Address;
27814 pragma Pure_Function (To_Address);
27816 function To_Address_Long (X : Unsigned_Longword)
27817  return Address;
27818 pragma Pure_Function (To_Address_Long);
27819 @end smallexample
27821 @noindent
27822 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27823 change the name to TO_ADDRESS_LONG@.
27825 @item Task_Id values
27826 The Task_Id values assigned will be different in the two systems, and GNAT
27827 does not provide a specified value for the Task_Id of the environment task,
27828 which in GNAT is treated like any other declared task.
27829 @end table
27831 @noindent
27832 For full details on these and other less significant compatibility issues,
27833 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27834 Overview and Comparison on HP Platforms}.
27836 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27837 attributes are recognized, although only a subset of them can sensibly
27838 be implemented.  The description of pragmas in @ref{Implementation
27839 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27840 indicates whether or not they are applicable to non-VMS systems.
27841 @end ifclear
27843 @ifset vms
27844 @node Transitioning to 64-Bit GNAT for OpenVMS
27845 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
27847 @noindent
27848 This section is meant to assist users of pre-2006 @value{EDITION}
27849 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
27850 the version of the GNAT technology supplied in 2006 and later for
27851 OpenVMS on both Alpha and I64.
27853 @menu
27854 * Introduction to transitioning::
27855 * Migration of 32 bit code::
27856 * Taking advantage of 64 bit addressing::
27857 * Technical details::
27858 @end menu
27860 @node Introduction to transitioning
27861 @subsection Introduction
27863 @noindent
27864 64-bit @value{EDITION} for Open VMS has been designed to meet
27865 three main goals:
27867 @enumerate
27868 @item
27869 Providing a full conforming implementation of Ada 95 and Ada 2005
27871 @item
27872 Allowing maximum backward compatibility, thus easing migration of existing
27873 Ada source code
27875 @item
27876 Supplying a path for exploiting the full 64-bit address range
27877 @end enumerate
27879 @noindent
27880 Ada's strong typing semantics has made it
27881 impractical to have different 32-bit and 64-bit modes. As soon as
27882 one object could possibly be outside the 32-bit address space, this
27883 would make it necessary for the @code{System.Address} type to be 64 bits.
27884 In particular, this would cause inconsistencies if 32-bit code is
27885 called from 64-bit code that raises an exception.
27887 This issue has been resolved by always using 64-bit addressing
27888 at the system level, but allowing for automatic conversions between
27889 32-bit and 64-bit addresses where required. Thus users who
27890 do not currently require 64-bit addressing capabilities, can
27891 recompile their code with only minimal changes (and indeed
27892 if the code is written in portable Ada, with no assumptions about
27893 the size of the @code{Address} type, then no changes at all are necessary).
27894 At the same time,
27895 this approach provides a simple, gradual upgrade path to future
27896 use of larger memories than available for 32-bit systems.
27897 Also, newly written applications or libraries will by default
27898 be fully compatible with future systems exploiting 64-bit
27899 addressing capabilities.
27901 @ref{Migration of 32 bit code}, will focus on porting applications
27902 that do not require more than 2 GB of
27903 addressable memory. This code will be referred to as
27904 @emph{32-bit code}.
27905 For applications intending to exploit the full 64-bit address space,
27906 @ref{Taking advantage of 64 bit addressing},
27907 will consider further changes that may be required.
27908 Such code will be referred to below as @emph{64-bit code}.
27910 @node Migration of 32 bit code
27911 @subsection Migration of 32-bit code
27913 @menu
27914 * Address types::
27915 * Access types and 32/64-bit allocation::
27916 * Unchecked conversions::
27917 * Predefined constants::
27918 * Interfacing with C::
27919 * 32/64-bit descriptors::
27920 * Experience with source compatibility::
27921 @end menu
27923 @node Address types
27924 @subsubsection Address types
27926 @noindent
27927 To solve the problem of mixing 64-bit and 32-bit addressing,
27928 while maintaining maximum backward compatibility, the following
27929 approach has been taken:
27931 @itemize @bullet
27932 @item
27933 @code{System.Address} always has a size of 64 bits
27934 @cindex @code{System.Address} size
27935 @cindex @code{Address} size
27937 @item
27938 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
27939 @cindex @code{System.Short_Address} size
27940 @cindex @code{Short_Address} size
27941 @end itemize
27943 @noindent
27944 Since @code{System.Short_Address} is a subtype of @code{System.Address},
27945 a @code{Short_Address}
27946 may be used where an @code{Address} is required, and vice versa, without
27947 needing explicit type conversions.
27948 By virtue of the Open VMS parameter passing conventions,
27949 even imported
27950 and exported subprograms that have 32-bit address parameters are
27951 compatible with those that have 64-bit address parameters.
27952 (See @ref{Making code 64 bit clean} for details.)
27954 The areas that may need attention are those where record types have
27955 been defined that contain components of the type @code{System.Address}, and
27956 where objects of this type are passed to code expecting a record layout with
27957 32-bit addresses.
27959 Different compilers on different platforms cannot be
27960 expected to represent the same type in the same way,
27961 since alignment constraints
27962 and other system-dependent properties affect the compiler's decision.
27963 For that reason, Ada code
27964 generally uses representation clauses to specify the expected
27965 layout where required.
27967 If such a representation clause uses 32 bits for a component having
27968 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
27969 will detect that error and produce a specific diagnostic message.
27970 The developer should then determine whether the representation
27971 should be 64 bits or not and make either of two changes:
27972 change the size to 64 bits and leave the type as @code{System.Address}, or
27973 leave the size as 32 bits and change the type to @code{System.Short_Address}.
27974 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
27975 required in any code setting or accessing the field; the compiler will
27976 automatically perform any needed conversions between address
27977 formats.
27979 @node Access types and 32/64-bit allocation
27980 @subsubsection Access types and 32/64-bit allocation
27981 @cindex 32-bit allocation
27982 @cindex 64-bit allocation
27984 @noindent
27985 By default, objects designated by access values are always allocated in
27986 the 64-bit address space, and access values themselves are represented
27987 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
27988 is required (for example if the address of an allocated object is assigned
27989 to a @code{Short_Address} variable), then several alternatives are available:
27991 @itemize @bullet
27992 @item
27993 A pool-specific access type (ie, an @w{Ada 83} access type, whose
27994 definition is @code{access T} versus @code{access all T} or
27995 @code{access constant T}), may be declared with a @code{'Size} representation
27996 clause that establishes the size as 32 bits.
27997 In such circumstances allocations for that type will
27998 be from the 32-bit heap.  Such a clause is not permitted
27999 for a general access type (declared with @code{access all} or
28000 @code{access constant}) as values of such types must be able to refer
28001 to any object of the designated type, including objects residing outside
28002 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
28003 type definitions, however, since general access types were introduced
28004 in @w{Ada 95}.
28006 @item
28007 Switches for @command{GNAT BIND} control whether the internal GNAT
28008 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
28009 @cindex @code{__gnat_malloc}
28010 The switches are respectively @option{-H64} (the default) and
28011 @option{-H32}.
28012 @cindex @option{-H32} (@command{gnatbind})
28013 @cindex @option{-H64} (@command{gnatbind})
28015 @item
28016 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
28017 @cindex @code{GNAT$NO_MALLOC_64} environment variable
28018 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
28019 If this variable is left
28020 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
28021 then the default (64-bit) allocation is used.
28022 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
28023 then 32-bit allocation is used.  The gnatbind qualifiers described above
28024 override this logical name.
28026 @item
28027 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
28028 @cindex @option{-mno-malloc64} (^gcc^gcc^)
28029 at a low level to convert explicit calls to @code{malloc} and related
28030 functions from the C run-time library so that they perform allocations
28031 in the 32-bit heap.
28032 Since all internal allocations from GNAT use @code{__gnat_malloc},
28033 this switch is not required unless the program makes explicit calls on
28034 @code{malloc} (or related functions) from interfaced C code.
28035 @end itemize
28038 @node Unchecked conversions
28039 @subsubsection Unchecked conversions
28041 @noindent
28042 In the case of an @code{Unchecked_Conversion} where the source type is a
28043 64-bit access type or the type @code{System.Address}, and the target
28044 type is a 32-bit type, the compiler will generate a warning.
28045 Even though the generated code will still perform the required
28046 conversions, it is highly recommended in these cases to use
28047 respectively a 32-bit access type or @code{System.Short_Address}
28048 as the source type.
28050 @node Predefined constants
28051 @subsubsection Predefined constants
28053 @noindent
28054 The following table shows the correspondence between pre-2006 versions of
28055 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
28056 (``New''):
28058 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
28059 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
28060 @item   @code{System.Word_Size}          @tab 32      @tab 64
28061 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
28062 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
28063 @item   @code{System.Address_Size}       @tab 32      @tab 64
28064 @end multitable
28066 @noindent
28067 If you need to refer to the specific
28068 memory size of a 32-bit implementation, instead of the
28069 actual memory size, use @code{System.Short_Memory_Size}
28070 rather than @code{System.Memory_Size}.
28071 Similarly, references to @code{System.Address_Size} may need
28072 to be replaced by @code{System.Short_Address'Size}.
28073 The program @command{gnatfind} may be useful for locating
28074 references to the above constants, so that you can verify that they
28075 are still correct.
28077 @node Interfacing with C
28078 @subsubsection Interfacing with C
28080 @noindent
28081 In order to minimize the impact of the transition to 64-bit addresses on
28082 legacy programs, some fundamental types in the @code{Interfaces.C}
28083 package hierarchy continue to be represented in 32 bits.
28084 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
28085 This eases integration with the default HP C layout choices, for example
28086 as found in the system routines in @code{DECC$SHR.EXE}.
28087 Because of this implementation choice, the type fully compatible with
28088 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
28089 Depending on the context the compiler will issue a
28090 warning or an error when type @code{Address} is used, alerting the user to a
28091 potential problem. Otherwise 32-bit programs that use
28092 @code{Interfaces.C} should normally not require code modifications
28094 The other issue arising with C interfacing concerns pragma @code{Convention}.
28095 For VMS 64-bit systems, there is an issue of the appropriate default size
28096 of C convention pointers in the absence of an explicit size clause. The HP
28097 C compiler can choose either 32 or 64 bits depending on compiler options.
28098 GNAT chooses 32-bits rather than 64-bits in the default case where no size
28099 clause is given. This proves a better choice for porting 32-bit legacy
28100 applications. In order to have a 64-bit representation, it is necessary to
28101 specify a size representation clause. For example:
28103 @smallexample @c ada
28104 type int_star is access Interfaces.C.int;
28105 pragma Convention(C, int_star);
28106 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
28107 @end smallexample
28109 @node 32/64-bit descriptors
28110 @subsubsection 32/64-bit descriptors
28112 @noindent
28113 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
28114 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
28115 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
28116 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
28117 @cindex @code{Short_Descriptor} mechanism for imported subprograms
28119 If the configuration pragma @code{Short_Descriptors} is supplied, then
28120 all descriptors will be 32 bits.
28121 @cindex pragma @code{Short_Descriptors}
28123 @node Experience with source compatibility
28124 @subsubsection Experience with source compatibility
28126 @noindent
28127 The Security Server and STARLET on I64 provide an interesting ``test case''
28128 for source compatibility issues, since it is in such system code
28129 where assumptions about @code{Address} size might be expected to occur.
28130 Indeed, there were a small number of occasions in the Security Server
28131 file @file{jibdef.ads}
28132 where a representation clause for a record type specified
28133 32 bits for a component of type @code{Address}.
28134 All of these errors were detected by the compiler.
28135 The repair was obvious and immediate; to simply replace @code{Address} by
28136 @code{Short_Address}.
28138 In the case of STARLET, there were several record types that should
28139 have had representation clauses but did not.  In these record types
28140 there was an implicit assumption that an @code{Address} value occupied
28141 32 bits.
28142 These compiled without error, but their usage resulted in run-time error
28143 returns from STARLET system calls.
28144 Future GNAT technology enhancements may include a tool that detects and flags
28145 these sorts of potential source code porting problems.
28147 @c ****************************************
28148 @node Taking advantage of 64 bit addressing
28149 @subsection Taking advantage of 64-bit addressing
28151 @menu
28152 * Making code 64 bit clean::
28153 * Allocating memory from the 64 bit storage pool::
28154 * Restrictions on use of 64 bit objects::
28155 * STARLET and other predefined libraries::
28156 @end menu
28158 @node Making code 64 bit clean
28159 @subsubsection Making code 64-bit clean
28161 @noindent
28162 In order to prevent problems that may occur when (parts of) a
28163 system start using memory outside the 32-bit address range,
28164 we recommend some additional guidelines:
28166 @itemize @bullet
28167 @item
28168 For imported subprograms that take parameters of the
28169 type @code{System.Address}, ensure that these subprograms can
28170 indeed handle 64-bit addresses. If not, or when in doubt,
28171 change the subprogram declaration to specify
28172 @code{System.Short_Address} instead.
28174 @item
28175 Resolve all warnings related to size mismatches in
28176 unchecked conversions. Failing to do so causes
28177 erroneous execution if the source object is outside
28178 the 32-bit address space.
28180 @item
28181 (optional) Explicitly use the 32-bit storage pool
28182 for access types used in a 32-bit context, or use
28183 generic access types where possible
28184 (@pxref{Restrictions on use of 64 bit objects}).
28185 @end itemize
28187 @noindent
28188 If these rules are followed, the compiler will automatically insert
28189 any necessary checks to ensure that no addresses or access values
28190 passed to 32-bit code ever refer to objects outside the 32-bit
28191 address range.
28192 Any attempt to do this will raise @code{Constraint_Error}.
28194 @node Allocating memory from the 64 bit storage pool
28195 @subsubsection Allocating memory from the 64-bit storage pool
28197 @noindent
28198 By default, all allocations -- for both pool-specific and general
28199 access types -- use the 64-bit storage pool.  To override
28200 this default, for an individual access type or globally, see
28201 @ref{Access types and 32/64-bit allocation}.
28203 @node Restrictions on use of 64 bit objects
28204 @subsubsection Restrictions on use of 64-bit objects
28206 @noindent
28207 Taking the address of an object allocated from a 64-bit storage pool,
28208 and then passing this address to a subprogram expecting
28209 @code{System.Short_Address},
28210 or assigning it to a variable of type @code{Short_Address}, will cause
28211 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
28212 (@pxref{Making code 64 bit clean}), or checks are suppressed,
28213 no exception is raised and execution
28214 will become erroneous.
28216 @node STARLET and other predefined libraries
28217 @subsubsection STARLET and other predefined libraries
28219 @noindent
28220 All code that comes as part of GNAT is 64-bit clean, but the
28221 restrictions given in @ref{Restrictions on use of 64 bit objects},
28222 still apply. Look at the package
28223 specs to see in which contexts objects allocated
28224 in 64-bit address space are acceptable.
28226 @node Technical details
28227 @subsection Technical details
28229 @noindent
28230 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
28231 Ada standard with respect to the type of @code{System.Address}. Previous
28232 versions of @value{EDITION} have defined this type as private and implemented it as a
28233 modular type.
28235 In order to allow defining @code{System.Short_Address} as a proper subtype,
28236 and to match the implicit sign extension in parameter passing,
28237 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
28238 visible (i.e., non-private) integer type.
28239 Standard operations on the type, such as the binary operators ``+'', ``-'',
28240 etc., that take @code{Address} operands and return an @code{Address} result,
28241 have been hidden by declaring these
28242 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
28243 ambiguities that would otherwise result from overloading.
28244 (Note that, although @code{Address} is a visible integer type,
28245 good programming practice dictates against exploiting the type's
28246 integer properties such as literals, since this will compromise
28247 code portability.)
28249 Defining @code{Address} as a visible integer type helps achieve
28250 maximum compatibility for existing Ada code,
28251 without sacrificing the capabilities of the 64-bit architecture.
28252 @end ifset
28254 @c ************************************************
28255 @ifset unw
28256 @node Microsoft Windows Topics
28257 @appendix Microsoft Windows Topics
28258 @cindex Windows NT
28259 @cindex Windows 95
28260 @cindex Windows 98
28262 @noindent
28263 This chapter describes topics that are specific to the Microsoft Windows
28264 platforms (NT, 2000, and XP Professional).
28266 @menu
28267 * Using GNAT on Windows::
28268 * Using a network installation of GNAT::
28269 * CONSOLE and WINDOWS subsystems::
28270 * Temporary Files::
28271 * Mixed-Language Programming on Windows::
28272 * Windows Calling Conventions::
28273 * Introduction to Dynamic Link Libraries (DLLs)::
28274 * Using DLLs with GNAT::
28275 * Building DLLs with GNAT Project files::
28276 * Building DLLs with GNAT::
28277 * Building DLLs with gnatdll::
28278 * GNAT and Windows Resources::
28279 * Debugging a DLL::
28280 * Setting Stack Size from gnatlink::
28281 * Setting Heap Size from gnatlink::
28282 @end menu
28284 @node Using GNAT on Windows
28285 @section Using GNAT on Windows
28287 @noindent
28288 One of the strengths of the GNAT technology is that its tool set
28289 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
28290 @code{gdb} debugger, etc.) is used in the same way regardless of the
28291 platform.
28293 On Windows this tool set is complemented by a number of Microsoft-specific
28294 tools that have been provided to facilitate interoperability with Windows
28295 when this is required. With these tools:
28297 @itemize @bullet
28299 @item
28300 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
28301 subsystems.
28303 @item
28304 You can use any Dynamically Linked Library (DLL) in your Ada code (both
28305 relocatable and non-relocatable DLLs are supported).
28307 @item
28308 You can build Ada DLLs for use in other applications. These applications
28309 can be written in a language other than Ada (e.g., C, C++, etc). Again both
28310 relocatable and non-relocatable Ada DLLs are supported.
28312 @item
28313 You can include Windows resources in your Ada application.
28315 @item
28316 You can use or create COM/DCOM objects.
28317 @end itemize
28319 @noindent
28320 Immediately below are listed all known general GNAT-for-Windows restrictions.
28321 Other restrictions about specific features like Windows Resources and DLLs
28322 are listed in separate sections below.
28324 @itemize @bullet
28326 @item
28327 It is not possible to use @code{GetLastError} and @code{SetLastError}
28328 when tasking, protected records, or exceptions are used. In these
28329 cases, in order to implement Ada semantics, the GNAT run-time system
28330 calls certain Win32 routines that set the last error variable to 0 upon
28331 success. It should be possible to use @code{GetLastError} and
28332 @code{SetLastError} when tasking, protected record, and exception
28333 features are not used, but it is not guaranteed to work.
28335 @item
28336 It is not possible to link against Microsoft C++ libraries except for
28337 import libraries. Interfacing must be done by the mean of DLLs.
28339 @item
28340 It is possible to link against Microsoft C libraries. Yet the preferred
28341 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
28342 doesn't require having two different development environments and makes the
28343 inter-language debugging experience smoother.
28345 @item
28346 When the compilation environment is located on FAT32 drives, users may
28347 experience recompilations of the source files that have not changed if
28348 Daylight Saving Time (DST) state has changed since the last time files
28349 were compiled. NTFS drives do not have this problem.
28351 @item
28352 No components of the GNAT toolset use any entries in the Windows
28353 registry. The only entries that can be created are file associations and
28354 PATH settings, provided the user has chosen to create them at installation
28355 time, as well as some minimal book-keeping information needed to correctly
28356 uninstall or integrate different GNAT products.
28357 @end itemize
28359 @node Using a network installation of GNAT
28360 @section Using a network installation of GNAT
28362 @noindent
28363 Make sure the system on which GNAT is installed is accessible from the
28364 current machine, i.e., the install location is shared over the network.
28365 Shared resources are accessed on Windows by means of UNC paths, which
28366 have the format @code{\\server\sharename\path}
28368 In order to use such a network installation, simply add the UNC path of the
28369 @file{bin} directory of your GNAT installation in front of your PATH. For
28370 example, if GNAT is installed in @file{\GNAT} directory of a share location
28371 called @file{c-drive} on a machine @file{LOKI}, the following command will
28372 make it available:
28374 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
28376 Be aware that every compilation using the network installation results in the
28377 transfer of large amounts of data across the network and will likely cause
28378 serious performance penalty.
28380 @node CONSOLE and WINDOWS subsystems
28381 @section CONSOLE and WINDOWS subsystems
28382 @cindex CONSOLE Subsystem
28383 @cindex WINDOWS Subsystem
28384 @cindex -mwindows
28386 @noindent
28387 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
28388 (which is the default subsystem) will always create a console when
28389 launching the application. This is not something desirable when the
28390 application has a Windows GUI. To get rid of this console the
28391 application must be using the @code{WINDOWS} subsystem. To do so
28392 the @option{-mwindows} linker option must be specified.
28394 @smallexample
28395 $ gnatmake winprog -largs -mwindows
28396 @end smallexample
28398 @node Temporary Files
28399 @section Temporary Files
28400 @cindex Temporary files
28402 @noindent
28403 It is possible to control where temporary files gets created by setting
28404 the @env{TMP} environment variable. The file will be created:
28406 @itemize
28407 @item Under the directory pointed to by the @env{TMP} environment variable if
28408 this directory exists.
28410 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
28411 set (or not pointing to a directory) and if this directory exists.
28413 @item Under the current working directory otherwise.
28414 @end itemize
28416 @noindent
28417 This allows you to determine exactly where the temporary
28418 file will be created. This is particularly useful in networked
28419 environments where you may not have write access to some
28420 directories.
28422 @node Mixed-Language Programming on Windows
28423 @section Mixed-Language Programming on Windows
28425 @noindent
28426 Developing pure Ada applications on Windows is no different than on
28427 other GNAT-supported platforms. However, when developing or porting an
28428 application that contains a mix of Ada and C/C++, the choice of your
28429 Windows C/C++ development environment conditions your overall
28430 interoperability strategy.
28432 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
28433 your application, there are no Windows-specific restrictions that
28434 affect the overall interoperability with your Ada code. If you do want
28435 to use the Microsoft tools for your C++ code, you have two choices:
28437 @enumerate
28438 @item
28439 Encapsulate your C++ code in a DLL to be linked with your Ada
28440 application. In this case, use the Microsoft or whatever environment to
28441 build the DLL and use GNAT to build your executable
28442 (@pxref{Using DLLs with GNAT}).
28444 @item
28445 Or you can encapsulate your Ada code in a DLL to be linked with the
28446 other part of your application. In this case, use GNAT to build the DLL
28447 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
28448 or whatever environment to build your executable.
28449 @end enumerate
28451 In addition to the description about C main in
28452 @pxref{Mixed Language Programming} section, if the C main uses a
28453 stand-alone library it is required on x86-windows to
28454 setup the SEH context. For this the C main must looks like this:
28456 @smallexample
28457 /* main.c */
28458 extern void adainit (void);
28459 extern void adafinal (void);
28460 extern void __gnat_initialize(void*);
28461 extern void call_to_ada (void);
28463 int main (int argc, char *argv[])
28465   int SEH [2];
28467   /* Initialize the SEH context */
28468   __gnat_initialize (&SEH);
28470   adainit();
28472   /* Then call Ada services in the stand-alone library */
28474   call_to_ada();
28476   adafinal();
28478 @end smallexample
28480 Note that this is not needed on x86_64-windows where the Windows
28481 native SEH support is used.
28483 @node Windows Calling Conventions
28484 @section Windows Calling Conventions
28485 @findex Stdcall
28486 @findex APIENTRY
28488 This section pertain only to Win32. On Win64 there is a single native
28489 calling convention. All convention specifiers are ignored on this
28490 platform.
28492 @menu
28493 * C Calling Convention::
28494 * Stdcall Calling Convention::
28495 * Win32 Calling Convention::
28496 * DLL Calling Convention::
28497 @end menu
28499 @noindent
28500 When a subprogram @code{F} (caller) calls a subprogram @code{G}
28501 (callee), there are several ways to push @code{G}'s parameters on the
28502 stack and there are several possible scenarios to clean up the stack
28503 upon @code{G}'s return. A calling convention is an agreed upon software
28504 protocol whereby the responsibilities between the caller (@code{F}) and
28505 the callee (@code{G}) are clearly defined. Several calling conventions
28506 are available for Windows:
28508 @itemize @bullet
28509 @item
28510 @code{C} (Microsoft defined)
28512 @item
28513 @code{Stdcall} (Microsoft defined)
28515 @item
28516 @code{Win32} (GNAT specific)
28518 @item
28519 @code{DLL} (GNAT specific)
28520 @end itemize
28522 @node C Calling Convention
28523 @subsection @code{C} Calling Convention
28525 @noindent
28526 This is the default calling convention used when interfacing to C/C++
28527 routines compiled with either @command{gcc} or Microsoft Visual C++.
28529 In the @code{C} calling convention subprogram parameters are pushed on the
28530 stack by the caller from right to left. The caller itself is in charge of
28531 cleaning up the stack after the call. In addition, the name of a routine
28532 with @code{C} calling convention is mangled by adding a leading underscore.
28534 The name to use on the Ada side when importing (or exporting) a routine
28535 with @code{C} calling convention is the name of the routine. For
28536 instance the C function:
28538 @smallexample
28539 int get_val (long);
28540 @end smallexample
28542 @noindent
28543 should be imported from Ada as follows:
28545 @smallexample @c ada
28546 @group
28547 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28548 pragma Import (C, Get_Val, External_Name => "get_val");
28549 @end group
28550 @end smallexample
28552 @noindent
28553 Note that in this particular case the @code{External_Name} parameter could
28554 have been omitted since, when missing, this parameter is taken to be the
28555 name of the Ada entity in lower case. When the @code{Link_Name} parameter
28556 is missing, as in the above example, this parameter is set to be the
28557 @code{External_Name} with a leading underscore.
28559 When importing a variable defined in C, you should always use the @code{C}
28560 calling convention unless the object containing the variable is part of a
28561 DLL (in which case you should use the @code{Stdcall} calling
28562 convention, @pxref{Stdcall Calling Convention}).
28564 @node Stdcall Calling Convention
28565 @subsection @code{Stdcall} Calling Convention
28567 @noindent
28568 This convention, which was the calling convention used for Pascal
28569 programs, is used by Microsoft for all the routines in the Win32 API for
28570 efficiency reasons. It must be used to import any routine for which this
28571 convention was specified.
28573 In the @code{Stdcall} calling convention subprogram parameters are pushed
28574 on the stack by the caller from right to left. The callee (and not the
28575 caller) is in charge of cleaning the stack on routine exit. In addition,
28576 the name of a routine with @code{Stdcall} calling convention is mangled by
28577 adding a leading underscore (as for the @code{C} calling convention) and a
28578 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
28579 bytes) of the parameters passed to the routine.
28581 The name to use on the Ada side when importing a C routine with a
28582 @code{Stdcall} calling convention is the name of the C routine. The leading
28583 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
28584 the compiler. For instance the Win32 function:
28586 @smallexample
28587 @b{APIENTRY} int get_val (long);
28588 @end smallexample
28590 @noindent
28591 should be imported from Ada as follows:
28593 @smallexample @c ada
28594 @group
28595 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28596 pragma Import (Stdcall, Get_Val);
28597 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
28598 @end group
28599 @end smallexample
28601 @noindent
28602 As for the @code{C} calling convention, when the @code{External_Name}
28603 parameter is missing, it is taken to be the name of the Ada entity in lower
28604 case. If instead of writing the above import pragma you write:
28606 @smallexample @c ada
28607 @group
28608 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28609 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
28610 @end group
28611 @end smallexample
28613 @noindent
28614 then the imported routine is @code{_retrieve_val@@4}. However, if instead
28615 of specifying the @code{External_Name} parameter you specify the
28616 @code{Link_Name} as in the following example:
28618 @smallexample @c ada
28619 @group
28620 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28621 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
28622 @end group
28623 @end smallexample
28625 @noindent
28626 then the imported routine is @code{retrieve_val}, that is, there is no
28627 decoration at all. No leading underscore and no Stdcall suffix
28628 @code{@@}@code{@var{nn}}.
28630 @noindent
28631 This is especially important as in some special cases a DLL's entry
28632 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
28633 name generated for a call has it.
28635 @noindent
28636 It is also possible to import variables defined in a DLL by using an
28637 import pragma for a variable. As an example, if a DLL contains a
28638 variable defined as:
28640 @smallexample
28641 int my_var;
28642 @end smallexample
28644 @noindent
28645 then, to access this variable from Ada you should write:
28647 @smallexample @c ada
28648 @group
28649 My_Var : Interfaces.C.int;
28650 pragma Import (Stdcall, My_Var);
28651 @end group
28652 @end smallexample
28654 @noindent
28655 Note that to ease building cross-platform bindings this convention
28656 will be handled as a @code{C} calling convention on non-Windows platforms.
28658 @node Win32 Calling Convention
28659 @subsection @code{Win32} Calling Convention
28661 @noindent
28662 This convention, which is GNAT-specific is fully equivalent to the
28663 @code{Stdcall} calling convention described above.
28665 @node DLL Calling Convention
28666 @subsection @code{DLL} Calling Convention
28668 @noindent
28669 This convention, which is GNAT-specific is fully equivalent to the
28670 @code{Stdcall} calling convention described above.
28672 @node Introduction to Dynamic Link Libraries (DLLs)
28673 @section Introduction to Dynamic Link Libraries (DLLs)
28674 @findex DLL
28676 @noindent
28677 A Dynamically Linked Library (DLL) is a library that can be shared by
28678 several applications running under Windows. A DLL can contain any number of
28679 routines and variables.
28681 One advantage of DLLs is that you can change and enhance them without
28682 forcing all the applications that depend on them to be relinked or
28683 recompiled. However, you should be aware than all calls to DLL routines are
28684 slower since, as you will understand below, such calls are indirect.
28686 To illustrate the remainder of this section, suppose that an application
28687 wants to use the services of a DLL @file{API.dll}. To use the services
28688 provided by @file{API.dll} you must statically link against the DLL or
28689 an import library which contains a jump table with an entry for each
28690 routine and variable exported by the DLL. In the Microsoft world this
28691 import library is called @file{API.lib}. When using GNAT this import
28692 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
28693 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
28695 After you have linked your application with the DLL or the import library
28696 and you run your application, here is what happens:
28698 @enumerate
28699 @item
28700 Your application is loaded into memory.
28702 @item
28703 The DLL @file{API.dll} is mapped into the address space of your
28704 application. This means that:
28706 @itemize @bullet
28707 @item
28708 The DLL will use the stack of the calling thread.
28710 @item
28711 The DLL will use the virtual address space of the calling process.
28713 @item
28714 The DLL will allocate memory from the virtual address space of the calling
28715 process.
28717 @item
28718 Handles (pointers) can be safely exchanged between routines in the DLL
28719 routines and routines in the application using the DLL.
28720 @end itemize
28722 @item
28723 The entries in the jump table (from the import library @file{libAPI.dll.a}
28724 or @file{API.lib} or automatically created when linking against a DLL)
28725 which is part of your application are initialized with the addresses
28726 of the routines and variables in @file{API.dll}.
28728 @item
28729 If present in @file{API.dll}, routines @code{DllMain} or
28730 @code{DllMainCRTStartup} are invoked. These routines typically contain
28731 the initialization code needed for the well-being of the routines and
28732 variables exported by the DLL.
28733 @end enumerate
28735 @noindent
28736 There is an additional point which is worth mentioning. In the Windows
28737 world there are two kind of DLLs: relocatable and non-relocatable
28738 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
28739 in the target application address space. If the addresses of two
28740 non-relocatable DLLs overlap and these happen to be used by the same
28741 application, a conflict will occur and the application will run
28742 incorrectly. Hence, when possible, it is always preferable to use and
28743 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
28744 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
28745 User's Guide) removes the debugging symbols from the DLL but the DLL can
28746 still be relocated.
28748 As a side note, an interesting difference between Microsoft DLLs and
28749 Unix shared libraries, is the fact that on most Unix systems all public
28750 routines are exported by default in a Unix shared library, while under
28751 Windows it is possible (but not required) to list exported routines in
28752 a definition file (@pxref{The Definition File}).
28754 @node Using DLLs with GNAT
28755 @section Using DLLs with GNAT
28757 @menu
28758 * Creating an Ada Spec for the DLL Services::
28759 * Creating an Import Library::
28760 @end menu
28762 @noindent
28763 To use the services of a DLL, say @file{API.dll}, in your Ada application
28764 you must have:
28766 @enumerate
28767 @item
28768 The Ada spec for the routines and/or variables you want to access in
28769 @file{API.dll}. If not available this Ada spec must be built from the C/C++
28770 header files provided with the DLL.
28772 @item
28773 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
28774 mentioned an import library is a statically linked library containing the
28775 import table which will be filled at load time to point to the actual
28776 @file{API.dll} routines. Sometimes you don't have an import library for the
28777 DLL you want to use. The following sections will explain how to build
28778 one. Note that this is optional.
28780 @item
28781 The actual DLL, @file{API.dll}.
28782 @end enumerate
28784 @noindent
28785 Once you have all the above, to compile an Ada application that uses the
28786 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
28787 you simply issue the command
28789 @smallexample
28790 $ gnatmake my_ada_app -largs -lAPI
28791 @end smallexample
28793 @noindent
28794 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
28795 tells the GNAT linker to look for an import library. The linker will
28796 look for a library name in this specific order:
28798 @enumerate
28799 @item @file{libAPI.dll.a}
28800 @item @file{API.dll.a}
28801 @item @file{libAPI.a}
28802 @item @file{API.lib}
28803 @item @file{libAPI.dll}
28804 @item @file{API.dll}
28805 @end enumerate
28807 The first three are the GNU style import libraries. The third is the
28808 Microsoft style import libraries. The last two are the actual DLL names.
28810 Note that if the Ada package spec for @file{API.dll} contains the
28811 following pragma
28813 @smallexample @c ada
28814 pragma Linker_Options ("-lAPI");
28815 @end smallexample
28817 @noindent
28818 you do not have to add @option{-largs -lAPI} at the end of the
28819 @command{gnatmake} command.
28821 If any one of the items above is missing you will have to create it
28822 yourself. The following sections explain how to do so using as an
28823 example a fictitious DLL called @file{API.dll}.
28825 @node Creating an Ada Spec for the DLL Services
28826 @subsection Creating an Ada Spec for the DLL Services
28828 @noindent
28829 A DLL typically comes with a C/C++ header file which provides the
28830 definitions of the routines and variables exported by the DLL. The Ada
28831 equivalent of this header file is a package spec that contains definitions
28832 for the imported entities. If the DLL you intend to use does not come with
28833 an Ada spec you have to generate one such spec yourself. For example if
28834 the header file of @file{API.dll} is a file @file{api.h} containing the
28835 following two definitions:
28837 @smallexample
28838 @group
28839 @cartouche
28840 int some_var;
28841 int get (char *);
28842 @end cartouche
28843 @end group
28844 @end smallexample
28846 @noindent
28847 then the equivalent Ada spec could be:
28849 @smallexample @c ada
28850 @group
28851 @cartouche
28852 with Interfaces.C.Strings;
28853 package API is
28854    use Interfaces;
28856    Some_Var : C.int;
28857    function Get (Str : C.Strings.Chars_Ptr) return C.int;
28859 private
28860    pragma Import (C, Get);
28861    pragma Import (DLL, Some_Var);
28862 end API;
28863 @end cartouche
28864 @end group
28865 @end smallexample
28867 @noindent
28868 Note that a variable is
28869 @strong{always imported with a DLL convention}. A function
28870 can have @code{C} or @code{Stdcall} convention.
28871 (@pxref{Windows Calling Conventions}).
28873 @node Creating an Import Library
28874 @subsection Creating an Import Library
28875 @cindex Import library
28877 @menu
28878 * The Definition File::
28879 * GNAT-Style Import Library::
28880 * Microsoft-Style Import Library::
28881 @end menu
28883 @noindent
28884 If a Microsoft-style import library @file{API.lib} or a GNAT-style
28885 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
28886 with @file{API.dll} you can skip this section. You can also skip this
28887 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
28888 as in this case it is possible to link directly against the
28889 DLL. Otherwise read on.
28891 @node The Definition File
28892 @subsubsection The Definition File
28893 @cindex Definition file
28894 @findex .def
28896 @noindent
28897 As previously mentioned, and unlike Unix systems, the list of symbols
28898 that are exported from a DLL must be provided explicitly in Windows.
28899 The main goal of a definition file is precisely that: list the symbols
28900 exported by a DLL. A definition file (usually a file with a @code{.def}
28901 suffix) has the following structure:
28903 @smallexample
28904 @group
28905 @cartouche
28906 @r{[}LIBRARY @var{name}@r{]}
28907 @r{[}DESCRIPTION @var{string}@r{]}
28908 EXPORTS
28909    @var{symbol1}
28910    @var{symbol2}
28911    @dots{}
28912 @end cartouche
28913 @end group
28914 @end smallexample
28916 @table @code
28917 @item LIBRARY @var{name}
28918 This section, which is optional, gives the name of the DLL.
28920 @item DESCRIPTION @var{string}
28921 This section, which is optional, gives a description string that will be
28922 embedded in the import library.
28924 @item EXPORTS
28925 This section gives the list of exported symbols (procedures, functions or
28926 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
28927 section of @file{API.def} looks like:
28929 @smallexample
28930 @group
28931 @cartouche
28932 EXPORTS
28933    some_var
28934    get
28935 @end cartouche
28936 @end group
28937 @end smallexample
28938 @end table
28940 @noindent
28941 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28942 (@pxref{Windows Calling Conventions}) for a Stdcall
28943 calling convention function in the exported symbols list.
28945 @noindent
28946 There can actually be other sections in a definition file, but these
28947 sections are not relevant to the discussion at hand.
28949 @node GNAT-Style Import Library
28950 @subsubsection GNAT-Style Import Library
28952 @noindent
28953 To create a static import library from @file{API.dll} with the GNAT tools
28954 you should proceed as follows:
28956 @enumerate
28957 @item
28958 Create the definition file @file{API.def} (@pxref{The Definition File}).
28959 For that use the @code{dll2def} tool as follows:
28961 @smallexample
28962 $ dll2def API.dll > API.def
28963 @end smallexample
28965 @noindent
28966 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28967 to standard output the list of entry points in the DLL. Note that if
28968 some routines in the DLL have the @code{Stdcall} convention
28969 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28970 suffix then you'll have to edit @file{api.def} to add it, and specify
28971 @option{-k} to @command{gnatdll} when creating the import library.
28973 @noindent
28974 Here are some hints to find the right @code{@@}@var{nn} suffix.
28976 @enumerate
28977 @item
28978 If you have the Microsoft import library (.lib), it is possible to get
28979 the right symbols by using Microsoft @code{dumpbin} tool (see the
28980 corresponding Microsoft documentation for further details).
28982 @smallexample
28983 $ dumpbin /exports api.lib
28984 @end smallexample
28986 @item
28987 If you have a message about a missing symbol at link time the compiler
28988 tells you what symbol is expected. You just have to go back to the
28989 definition file and add the right suffix.
28990 @end enumerate
28992 @item
28993 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28994 (@pxref{Using gnatdll}) as follows:
28996 @smallexample
28997 $ gnatdll -e API.def -d API.dll
28998 @end smallexample
29000 @noindent
29001 @code{gnatdll} takes as input a definition file @file{API.def} and the
29002 name of the DLL containing the services listed in the definition file
29003 @file{API.dll}. The name of the static import library generated is
29004 computed from the name of the definition file as follows: if the
29005 definition file name is @var{xyz}@code{.def}, the import library name will
29006 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
29007 @option{-e} could have been removed because the name of the definition
29008 file (before the ``@code{.def}'' suffix) is the same as the name of the
29009 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
29010 @end enumerate
29012 @node Microsoft-Style Import Library
29013 @subsubsection Microsoft-Style Import Library
29015 @noindent
29016 With GNAT you can either use a GNAT-style or Microsoft-style import
29017 library. A Microsoft import library is needed only if you plan to make an
29018 Ada DLL available to applications developed with Microsoft
29019 tools (@pxref{Mixed-Language Programming on Windows}).
29021 To create a Microsoft-style import library for @file{API.dll} you
29022 should proceed as follows:
29024 @enumerate
29025 @item
29026 Create the definition file @file{API.def} from the DLL. For this use either
29027 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
29028 tool (see the corresponding Microsoft documentation for further details).
29030 @item
29031 Build the actual import library using Microsoft's @code{lib} utility:
29033 @smallexample
29034 $ lib -machine:IX86 -def:API.def -out:API.lib
29035 @end smallexample
29037 @noindent
29038 If you use the above command the definition file @file{API.def} must
29039 contain a line giving the name of the DLL:
29041 @smallexample
29042 LIBRARY      "API"
29043 @end smallexample
29045 @noindent
29046 See the Microsoft documentation for further details about the usage of
29047 @code{lib}.
29048 @end enumerate
29050 @node Building DLLs with GNAT Project files
29051 @section Building DLLs with GNAT Project files
29052 @cindex DLLs, building
29054 @noindent
29055 There is nothing specific to Windows in the build process.
29056 @pxref{Library Projects}.
29058 @noindent
29059 Due to a system limitation, it is not possible under Windows to create threads
29060 when inside the @code{DllMain} routine which is used for auto-initialization
29061 of shared libraries, so it is not possible to have library level tasks in SALs.
29063 @node Building DLLs with GNAT
29064 @section Building DLLs with GNAT
29065 @cindex DLLs, building
29067 @noindent
29068 This section explain how to build DLLs using the GNAT built-in DLL
29069 support. With the following procedure it is straight forward to build
29070 and use DLLs with GNAT.
29072 @enumerate
29074 @item building object files
29076 The first step is to build all objects files that are to be included
29077 into the DLL. This is done by using the standard @command{gnatmake} tool.
29079 @item building the DLL
29081 To build the DLL you must use @command{gcc}'s @option{-shared} and
29082 @option{-shared-libgcc} options. It is quite simple to use this method:
29084 @smallexample
29085 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
29086 @end smallexample
29088 It is important to note that in this case all symbols found in the
29089 object files are automatically exported. It is possible to restrict
29090 the set of symbols to export by passing to @command{gcc} a definition
29091 file, @pxref{The Definition File}. For example:
29093 @smallexample
29094 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
29095 @end smallexample
29097 If you use a definition file you must export the elaboration procedures
29098 for every package that required one. Elaboration procedures are named
29099 using the package name followed by "_E".
29101 @item preparing DLL to be used
29103 For the DLL to be used by client programs the bodies must be hidden
29104 from it and the .ali set with read-only attribute. This is very important
29105 otherwise GNAT will recompile all packages and will not actually use
29106 the code in the DLL. For example:
29108 @smallexample
29109 $ mkdir apilib
29110 $ copy *.ads *.ali api.dll apilib
29111 $ attrib +R apilib\*.ali
29112 @end smallexample
29114 @end enumerate
29116 At this point it is possible to use the DLL by directly linking
29117 against it. Note that you must use the GNAT shared runtime when using
29118 GNAT shared libraries. This is achieved by using @option{-shared} binder's
29119 option.
29121 @smallexample
29122 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
29123 @end smallexample
29125 @node Building DLLs with gnatdll
29126 @section Building DLLs with gnatdll
29127 @cindex DLLs, building
29129 @menu
29130 * Limitations When Using Ada DLLs from Ada::
29131 * Exporting Ada Entities::
29132 * Ada DLLs and Elaboration::
29133 * Ada DLLs and Finalization::
29134 * Creating a Spec for Ada DLLs::
29135 * Creating the Definition File::
29136 * Using gnatdll::
29137 @end menu
29139 @noindent
29140 Note that it is preferred to use GNAT Project files
29141 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
29142 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
29144 This section explains how to build DLLs containing Ada code using
29145 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
29146 remainder of this section.
29148 The steps required to build an Ada DLL that is to be used by Ada as well as
29149 non-Ada applications are as follows:
29151 @enumerate
29152 @item
29153 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
29154 @code{Stdcall} calling convention to avoid any Ada name mangling for the
29155 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
29156 skip this step if you plan to use the Ada DLL only from Ada applications.
29158 @item
29159 Your Ada code must export an initialization routine which calls the routine
29160 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
29161 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
29162 routine exported by the Ada DLL must be invoked by the clients of the DLL
29163 to initialize the DLL.
29165 @item
29166 When useful, the DLL should also export a finalization routine which calls
29167 routine @code{adafinal} generated by @command{gnatbind} to perform the
29168 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
29169 The finalization routine exported by the Ada DLL must be invoked by the
29170 clients of the DLL when the DLL services are no further needed.
29172 @item
29173 You must provide a spec for the services exported by the Ada DLL in each
29174 of the programming languages to which you plan to make the DLL available.
29176 @item
29177 You must provide a definition file listing the exported entities
29178 (@pxref{The Definition File}).
29180 @item
29181 Finally you must use @code{gnatdll} to produce the DLL and the import
29182 library (@pxref{Using gnatdll}).
29183 @end enumerate
29185 @noindent
29186 Note that a relocatable DLL stripped using the @code{strip}
29187 binutils tool will not be relocatable anymore. To build a DLL without
29188 debug information pass @code{-largs -s} to @code{gnatdll}. This
29189 restriction does not apply to a DLL built using a Library Project.
29190 @pxref{Library Projects}.
29192 @node Limitations When Using Ada DLLs from Ada
29193 @subsection Limitations When Using Ada DLLs from Ada
29195 @noindent
29196 When using Ada DLLs from Ada applications there is a limitation users
29197 should be aware of. Because on Windows the GNAT run time is not in a DLL of
29198 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
29199 each Ada DLL includes the services of the GNAT run time that are necessary
29200 to the Ada code inside the DLL. As a result, when an Ada program uses an
29201 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
29202 one in the main program.
29204 It is therefore not possible to exchange GNAT run-time objects between the
29205 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
29206 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
29207 types, etc.
29209 It is completely safe to exchange plain elementary, array or record types,
29210 Windows object handles, etc.
29212 @node Exporting Ada Entities
29213 @subsection Exporting Ada Entities
29214 @cindex Export table
29216 @noindent
29217 Building a DLL is a way to encapsulate a set of services usable from any
29218 application. As a result, the Ada entities exported by a DLL should be
29219 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
29220 any Ada name mangling. As an example here is an Ada package
29221 @code{API}, spec and body, exporting two procedures, a function, and a
29222 variable:
29224 @smallexample @c ada
29225 @group
29226 @cartouche
29227 with Interfaces.C; use Interfaces;
29228 package API is
29229    Count : C.int := 0;
29230    function Factorial (Val : C.int) return C.int;
29232    procedure Initialize_API;
29233    procedure Finalize_API;
29234    --  Initialization & Finalization routines. More in the next section.
29235 private
29236    pragma Export (C, Initialize_API);
29237    pragma Export (C, Finalize_API);
29238    pragma Export (C, Count);
29239    pragma Export (C, Factorial);
29240 end API;
29241 @end cartouche
29242 @end group
29243 @end smallexample
29245 @smallexample @c ada
29246 @group
29247 @cartouche
29248 package body API is
29249    function Factorial (Val : C.int) return C.int is
29250       Fact : C.int := 1;
29251    begin
29252       Count := Count + 1;
29253       for K in 1 .. Val loop
29254          Fact := Fact * K;
29255       end loop;
29256       return Fact;
29257    end Factorial;
29259    procedure Initialize_API is
29260       procedure Adainit;
29261       pragma Import (C, Adainit);
29262    begin
29263       Adainit;
29264    end Initialize_API;
29266    procedure Finalize_API is
29267       procedure Adafinal;
29268       pragma Import (C, Adafinal);
29269    begin
29270       Adafinal;
29271    end Finalize_API;
29272 end API;
29273 @end cartouche
29274 @end group
29275 @end smallexample
29277 @noindent
29278 If the Ada DLL you are building will only be used by Ada applications
29279 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
29280 convention. As an example, the previous package could be written as
29281 follows:
29283 @smallexample @c ada
29284 @group
29285 @cartouche
29286 package API is
29287    Count : Integer := 0;
29288    function Factorial (Val : Integer) return Integer;
29290    procedure Initialize_API;
29291    procedure Finalize_API;
29292    --  Initialization and Finalization routines.
29293 end API;
29294 @end cartouche
29295 @end group
29296 @end smallexample
29298 @smallexample @c ada
29299 @group
29300 @cartouche
29301 package body API is
29302    function Factorial (Val : Integer) return Integer is
29303       Fact : Integer := 1;
29304    begin
29305       Count := Count + 1;
29306       for K in 1 .. Val loop
29307          Fact := Fact * K;
29308       end loop;
29309       return Fact;
29310    end Factorial;
29312    @dots{}
29313    --  The remainder of this package body is unchanged.
29314 end API;
29315 @end cartouche
29316 @end group
29317 @end smallexample
29319 @noindent
29320 Note that if you do not export the Ada entities with a @code{C} or
29321 @code{Stdcall} convention you will have to provide the mangled Ada names
29322 in the definition file of the Ada DLL
29323 (@pxref{Creating the Definition File}).
29325 @node Ada DLLs and Elaboration
29326 @subsection Ada DLLs and Elaboration
29327 @cindex DLLs and elaboration
29329 @noindent
29330 The DLL that you are building contains your Ada code as well as all the
29331 routines in the Ada library that are needed by it. The first thing a
29332 user of your DLL must do is elaborate the Ada code
29333 (@pxref{Elaboration Order Handling in GNAT}).
29335 To achieve this you must export an initialization routine
29336 (@code{Initialize_API} in the previous example), which must be invoked
29337 before using any of the DLL services. This elaboration routine must call
29338 the Ada elaboration routine @code{adainit} generated by the GNAT binder
29339 (@pxref{Binding with Non-Ada Main Programs}). See the body of
29340 @code{Initialize_Api} for an example. Note that the GNAT binder is
29341 automatically invoked during the DLL build process by the @code{gnatdll}
29342 tool (@pxref{Using gnatdll}).
29344 When a DLL is loaded, Windows systematically invokes a routine called
29345 @code{DllMain}. It would therefore be possible to call @code{adainit}
29346 directly from @code{DllMain} without having to provide an explicit
29347 initialization routine. Unfortunately, it is not possible to call
29348 @code{adainit} from the @code{DllMain} if your program has library level
29349 tasks because access to the @code{DllMain} entry point is serialized by
29350 the system (that is, only a single thread can execute ``through'' it at a
29351 time), which means that the GNAT run time will deadlock waiting for the
29352 newly created task to complete its initialization.
29354 @node Ada DLLs and Finalization
29355 @subsection Ada DLLs and Finalization
29356 @cindex DLLs and finalization
29358 @noindent
29359 When the services of an Ada DLL are no longer needed, the client code should
29360 invoke the DLL finalization routine, if available. The DLL finalization
29361 routine is in charge of releasing all resources acquired by the DLL. In the
29362 case of the Ada code contained in the DLL, this is achieved by calling
29363 routine @code{adafinal} generated by the GNAT binder
29364 (@pxref{Binding with Non-Ada Main Programs}).
29365 See the body of @code{Finalize_Api} for an
29366 example. As already pointed out the GNAT binder is automatically invoked
29367 during the DLL build process by the @code{gnatdll} tool
29368 (@pxref{Using gnatdll}).
29370 @node Creating a Spec for Ada DLLs
29371 @subsection Creating a Spec for Ada DLLs
29373 @noindent
29374 To use the services exported by the Ada DLL from another programming
29375 language (e.g.@: C), you have to translate the specs of the exported Ada
29376 entities in that language. For instance in the case of @code{API.dll},
29377 the corresponding C header file could look like:
29379 @smallexample
29380 @group
29381 @cartouche
29382 extern int *_imp__count;
29383 #define count (*_imp__count)
29384 int factorial (int);
29385 @end cartouche
29386 @end group
29387 @end smallexample
29389 @noindent
29390 It is important to understand that when building an Ada DLL to be used by
29391 other Ada applications, you need two different specs for the packages
29392 contained in the DLL: one for building the DLL and the other for using
29393 the DLL. This is because the @code{DLL} calling convention is needed to
29394 use a variable defined in a DLL, but when building the DLL, the variable
29395 must have either the @code{Ada} or @code{C} calling convention. As an
29396 example consider a DLL comprising the following package @code{API}:
29398 @smallexample @c ada
29399 @group
29400 @cartouche
29401 package API is
29402    Count : Integer := 0;
29403    @dots{}
29404    --  Remainder of the package omitted.
29405 end API;
29406 @end cartouche
29407 @end group
29408 @end smallexample
29410 @noindent
29411 After producing a DLL containing package @code{API}, the spec that
29412 must be used to import @code{API.Count} from Ada code outside of the
29413 DLL is:
29415 @smallexample @c ada
29416 @group
29417 @cartouche
29418 package API is
29419    Count : Integer;
29420    pragma Import (DLL, Count);
29421 end API;
29422 @end cartouche
29423 @end group
29424 @end smallexample
29426 @node Creating the Definition File
29427 @subsection Creating the Definition File
29429 @noindent
29430 The definition file is the last file needed to build the DLL. It lists
29431 the exported symbols. As an example, the definition file for a DLL
29432 containing only package @code{API} (where all the entities are exported
29433 with a @code{C} calling convention) is:
29435 @smallexample
29436 @group
29437 @cartouche
29438 EXPORTS
29439     count
29440     factorial
29441     finalize_api
29442     initialize_api
29443 @end cartouche
29444 @end group
29445 @end smallexample
29447 @noindent
29448 If the @code{C} calling convention is missing from package @code{API},
29449 then the definition file contains the mangled Ada names of the above
29450 entities, which in this case are:
29452 @smallexample
29453 @group
29454 @cartouche
29455 EXPORTS
29456     api__count
29457     api__factorial
29458     api__finalize_api
29459     api__initialize_api
29460 @end cartouche
29461 @end group
29462 @end smallexample
29464 @node Using gnatdll
29465 @subsection Using @code{gnatdll}
29466 @findex gnatdll
29468 @menu
29469 * gnatdll Example::
29470 * gnatdll behind the Scenes::
29471 * Using dlltool::
29472 @end menu
29474 @noindent
29475 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
29476 and non-Ada sources that make up your DLL have been compiled.
29477 @code{gnatdll} is actually in charge of two distinct tasks: build the
29478 static import library for the DLL and the actual DLL. The form of the
29479 @code{gnatdll} command is
29481 @smallexample
29482 @cartouche
29483 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29484 @c Expanding @ovar macro inline (explanation in macro def comments)
29485 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29486 @end cartouche
29487 @end smallexample
29489 @noindent
29490 where @var{list-of-files} is a list of ALI and object files. The object
29491 file list must be the exact list of objects corresponding to the non-Ada
29492 sources whose services are to be included in the DLL. The ALI file list
29493 must be the exact list of ALI files for the corresponding Ada sources
29494 whose services are to be included in the DLL. If @var{list-of-files} is
29495 missing, only the static import library is generated.
29497 @noindent
29498 You may specify any of the following switches to @code{gnatdll}:
29500 @table @code
29501 @c @item -a@ovar{address}
29502 @c Expanding @ovar macro inline (explanation in macro def comments)
29503 @item -a@r{[}@var{address}@r{]}
29504 @cindex @option{-a} (@code{gnatdll})
29505 Build a non-relocatable DLL at @var{address}. If @var{address} is not
29506 specified the default address @var{0x11000000} will be used. By default,
29507 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
29508 advise the reader to build relocatable DLL.
29510 @item -b @var{address}
29511 @cindex @option{-b} (@code{gnatdll})
29512 Set the relocatable DLL base address. By default the address is
29513 @code{0x11000000}.
29515 @item -bargs @var{opts}
29516 @cindex @option{-bargs} (@code{gnatdll})
29517 Binder options. Pass @var{opts} to the binder.
29519 @item -d @var{dllfile}
29520 @cindex @option{-d} (@code{gnatdll})
29521 @var{dllfile} is the name of the DLL. This switch must be present for
29522 @code{gnatdll} to do anything. The name of the generated import library is
29523 obtained algorithmically from @var{dllfile} as shown in the following
29524 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
29525 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
29526 by option @option{-e}) is obtained algorithmically from @var{dllfile}
29527 as shown in the following example:
29528 if @var{dllfile} is @code{xyz.dll}, the definition
29529 file used is @code{xyz.def}.
29531 @item -e @var{deffile}
29532 @cindex @option{-e} (@code{gnatdll})
29533 @var{deffile} is the name of the definition file.
29535 @item -g
29536 @cindex @option{-g} (@code{gnatdll})
29537 Generate debugging information. This information is stored in the object
29538 file and copied from there to the final DLL file by the linker,
29539 where it can be read by the debugger. You must use the
29540 @option{-g} switch if you plan on using the debugger or the symbolic
29541 stack traceback.
29543 @item -h
29544 @cindex @option{-h} (@code{gnatdll})
29545 Help mode. Displays @code{gnatdll} switch usage information.
29547 @item -Idir
29548 @cindex @option{-I} (@code{gnatdll})
29549 Direct @code{gnatdll} to search the @var{dir} directory for source and
29550 object files needed to build the DLL.
29551 (@pxref{Search Paths and the Run-Time Library (RTL)}).
29553 @item -k
29554 @cindex @option{-k} (@code{gnatdll})
29555 Removes the @code{@@}@var{nn} suffix from the import library's exported
29556 names, but keeps them for the link names. You must specify this
29557 option if you want to use a @code{Stdcall} function in a DLL for which
29558 the @code{@@}@var{nn} suffix has been removed. This is the case for most
29559 of the Windows NT DLL for example. This option has no effect when
29560 @option{-n} option is specified.
29562 @item -l @var{file}
29563 @cindex @option{-l} (@code{gnatdll})
29564 The list of ALI and object files used to build the DLL are listed in
29565 @var{file}, instead of being given in the command line. Each line in
29566 @var{file} contains the name of an ALI or object file.
29568 @item -n
29569 @cindex @option{-n} (@code{gnatdll})
29570 No Import. Do not create the import library.
29572 @item -q
29573 @cindex @option{-q} (@code{gnatdll})
29574 Quiet mode. Do not display unnecessary messages.
29576 @item -v
29577 @cindex @option{-v} (@code{gnatdll})
29578 Verbose mode. Display extra information.
29580 @item -largs @var{opts}
29581 @cindex @option{-largs} (@code{gnatdll})
29582 Linker options. Pass @var{opts} to the linker.
29583 @end table
29585 @node gnatdll Example
29586 @subsubsection @code{gnatdll} Example
29588 @noindent
29589 As an example the command to build a relocatable DLL from @file{api.adb}
29590 once @file{api.adb} has been compiled and @file{api.def} created is
29592 @smallexample
29593 $ gnatdll -d api.dll api.ali
29594 @end smallexample
29596 @noindent
29597 The above command creates two files: @file{libapi.dll.a} (the import
29598 library) and @file{api.dll} (the actual DLL). If you want to create
29599 only the DLL, just type:
29601 @smallexample
29602 $ gnatdll -d api.dll -n api.ali
29603 @end smallexample
29605 @noindent
29606 Alternatively if you want to create just the import library, type:
29608 @smallexample
29609 $ gnatdll -d api.dll
29610 @end smallexample
29612 @node gnatdll behind the Scenes
29613 @subsubsection @code{gnatdll} behind the Scenes
29615 @noindent
29616 This section details the steps involved in creating a DLL. @code{gnatdll}
29617 does these steps for you. Unless you are interested in understanding what
29618 goes on behind the scenes, you should skip this section.
29620 We use the previous example of a DLL containing the Ada package @code{API},
29621 to illustrate the steps necessary to build a DLL. The starting point is a
29622 set of objects that will make up the DLL and the corresponding ALI
29623 files. In the case of this example this means that @file{api.o} and
29624 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
29625 the following:
29627 @enumerate
29628 @item
29629 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
29630 the information necessary to generate relocation information for the
29631 DLL.
29633 @smallexample
29634 @group
29635 $ gnatbind -n api
29636 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
29637 @end group
29638 @end smallexample
29640 @noindent
29641 In addition to the base file, the @command{gnatlink} command generates an
29642 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
29643 asks @command{gnatlink} to generate the routines @code{DllMain} and
29644 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
29645 is loaded into memory.
29647 @item
29648 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
29649 export table (@file{api.exp}). The export table contains the relocation
29650 information in a form which can be used during the final link to ensure
29651 that the Windows loader is able to place the DLL anywhere in memory.
29653 @smallexample
29654 @group
29655 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29656           --output-exp api.exp
29657 @end group
29658 @end smallexample
29660 @item
29661 @code{gnatdll} builds the base file using the new export table. Note that
29662 @command{gnatbind} must be called once again since the binder generated file
29663 has been deleted during the previous call to @command{gnatlink}.
29665 @smallexample
29666 @group
29667 $ gnatbind -n api
29668 $ gnatlink api -o api.jnk api.exp -mdll
29669       -Wl,--base-file,api.base
29670 @end group
29671 @end smallexample
29673 @item
29674 @code{gnatdll} builds the new export table using the new base file and
29675 generates the DLL import library @file{libAPI.dll.a}.
29677 @smallexample
29678 @group
29679 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29680           --output-exp api.exp --output-lib libAPI.a
29681 @end group
29682 @end smallexample
29684 @item
29685 Finally @code{gnatdll} builds the relocatable DLL using the final export
29686 table.
29688 @smallexample
29689 @group
29690 $ gnatbind -n api
29691 $ gnatlink api api.exp -o api.dll -mdll
29692 @end group
29693 @end smallexample
29694 @end enumerate
29696 @node Using dlltool
29697 @subsubsection Using @code{dlltool}
29699 @noindent
29700 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
29701 DLLs and static import libraries. This section summarizes the most
29702 common @code{dlltool} switches. The form of the @code{dlltool} command
29705 @smallexample
29706 @c $ dlltool @ovar{switches}
29707 @c Expanding @ovar macro inline (explanation in macro def comments)
29708 $ dlltool @r{[}@var{switches}@r{]}
29709 @end smallexample
29711 @noindent
29712 @code{dlltool} switches include:
29714 @table @option
29715 @item --base-file @var{basefile}
29716 @cindex @option{--base-file} (@command{dlltool})
29717 Read the base file @var{basefile} generated by the linker. This switch
29718 is used to create a relocatable DLL.
29720 @item --def @var{deffile}
29721 @cindex @option{--def} (@command{dlltool})
29722 Read the definition file.
29724 @item --dllname @var{name}
29725 @cindex @option{--dllname} (@command{dlltool})
29726 Gives the name of the DLL. This switch is used to embed the name of the
29727 DLL in the static import library generated by @code{dlltool} with switch
29728 @option{--output-lib}.
29730 @item -k
29731 @cindex @option{-k} (@command{dlltool})
29732 Kill @code{@@}@var{nn} from exported names
29733 (@pxref{Windows Calling Conventions}
29734 for a discussion about @code{Stdcall}-style symbols.
29736 @item --help
29737 @cindex @option{--help} (@command{dlltool})
29738 Prints the @code{dlltool} switches with a concise description.
29740 @item --output-exp @var{exportfile}
29741 @cindex @option{--output-exp} (@command{dlltool})
29742 Generate an export file @var{exportfile}. The export file contains the
29743 export table (list of symbols in the DLL) and is used to create the DLL.
29745 @item --output-lib @var{libfile}
29746 @cindex @option{--output-lib} (@command{dlltool})
29747 Generate a static import library @var{libfile}.
29749 @item -v
29750 @cindex @option{-v} (@command{dlltool})
29751 Verbose mode.
29753 @item --as @var{assembler-name}
29754 @cindex @option{--as} (@command{dlltool})
29755 Use @var{assembler-name} as the assembler. The default is @code{as}.
29756 @end table
29758 @node GNAT and Windows Resources
29759 @section GNAT and Windows Resources
29760 @cindex Resources, windows
29762 @menu
29763 * Building Resources::
29764 * Compiling Resources::
29765 * Using Resources::
29766 @end menu
29768 @noindent
29769 Resources are an easy way to add Windows specific objects to your
29770 application. The objects that can be added as resources include:
29772 @itemize @bullet
29773 @item menus
29775 @item accelerators
29777 @item dialog boxes
29779 @item string tables
29781 @item bitmaps
29783 @item cursors
29785 @item icons
29787 @item fonts
29789 @item version information
29790 @end itemize
29792 For example, a version information resource can be defined as follow and
29793 embedded into an executable or DLL:
29795 A version information resource can be used to embed information into an
29796 executable or a DLL. These information can be viewed using the file properties
29797 from the Windows Explorer. Here is an example of a version information
29798 resource:
29800 @smallexample
29801 @group
29802 1 VERSIONINFO
29803 FILEVERSION     1,0,0,0
29804 PRODUCTVERSION  1,0,0,0
29805 BEGIN
29806   BLOCK "StringFileInfo"
29807   BEGIN
29808     BLOCK "080904E4"
29809     BEGIN
29810       VALUE "CompanyName", "My Company Name"
29811       VALUE "FileDescription", "My application"
29812       VALUE "FileVersion", "1.0"
29813       VALUE "InternalName", "my_app"
29814       VALUE "LegalCopyright", "My Name"
29815       VALUE "OriginalFilename", "my_app.exe"
29816       VALUE "ProductName", "My App"
29817       VALUE "ProductVersion", "1.0"
29818     END
29819   END
29821   BLOCK "VarFileInfo"
29822   BEGIN
29823     VALUE "Translation", 0x809, 1252
29824   END
29826 @end group
29827 @end smallexample
29829 The value @code{0809} (langID) is for the U.K English language and
29830 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
29831 multilingual.
29833 @noindent
29834 This section explains how to build, compile and use resources. Note that this
29835 section does not cover all resource objects, for a complete description see
29836 the corresponding Microsoft documentation.
29838 @node Building Resources
29839 @subsection Building Resources
29840 @cindex Resources, building
29842 @noindent
29843 A resource file is an ASCII file. By convention resource files have an
29844 @file{.rc} extension.
29845 The easiest way to build a resource file is to use Microsoft tools
29846 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
29847 @code{dlgedit.exe} to build dialogs.
29848 It is always possible to build an @file{.rc} file yourself by writing a
29849 resource script.
29851 It is not our objective to explain how to write a resource file. A
29852 complete description of the resource script language can be found in the
29853 Microsoft documentation.
29855 @node Compiling Resources
29856 @subsection Compiling Resources
29857 @findex rc
29858 @findex windres
29859 @cindex Resources, compiling
29861 @noindent
29862 This section describes how to build a GNAT-compatible (COFF) object file
29863 containing the resources. This is done using the Resource Compiler
29864 @code{windres} as follows:
29866 @smallexample
29867 $ windres -i myres.rc -o myres.o
29868 @end smallexample
29870 @noindent
29871 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
29872 file. You can specify an alternate preprocessor (usually named
29873 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
29874 parameter. A list of all possible options may be obtained by entering
29875 the command @code{windres} @option{--help}.
29877 It is also possible to use the Microsoft resource compiler @code{rc.exe}
29878 to produce a @file{.res} file (binary resource file). See the
29879 corresponding Microsoft documentation for further details. In this case
29880 you need to use @code{windres} to translate the @file{.res} file to a
29881 GNAT-compatible object file as follows:
29883 @smallexample
29884 $ windres -i myres.res -o myres.o
29885 @end smallexample
29887 @node Using Resources
29888 @subsection Using Resources
29889 @cindex Resources, using
29891 @noindent
29892 To include the resource file in your program just add the
29893 GNAT-compatible object file for the resource(s) to the linker
29894 arguments. With @command{gnatmake} this is done by using the @option{-largs}
29895 option:
29897 @smallexample
29898 $ gnatmake myprog -largs myres.o
29899 @end smallexample
29901 @node Debugging a DLL
29902 @section Debugging a DLL
29903 @cindex DLL debugging
29905 @menu
29906 * Program and DLL Both Built with GCC/GNAT::
29907 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
29908 @end menu
29910 @noindent
29911 Debugging a DLL is similar to debugging a standard program. But
29912 we have to deal with two different executable parts: the DLL and the
29913 program that uses it. We have the following four possibilities:
29915 @enumerate 1
29916 @item
29917 The program and the DLL are built with @code{GCC/GNAT}.
29918 @item
29919 The program is built with foreign tools and the DLL is built with
29920 @code{GCC/GNAT}.
29921 @item
29922 The program is built with @code{GCC/GNAT} and the DLL is built with
29923 foreign tools.
29924 @end enumerate
29926 @noindent
29927 In this section we address only cases one and two above.
29928 There is no point in trying to debug
29929 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
29930 information in it. To do so you must use a debugger compatible with the
29931 tools suite used to build the DLL.
29933 @node Program and DLL Both Built with GCC/GNAT
29934 @subsection Program and DLL Both Built with GCC/GNAT
29936 @noindent
29937 This is the simplest case. Both the DLL and the program have @code{GDB}
29938 compatible debugging information. It is then possible to break anywhere in
29939 the process. Let's suppose here that the main procedure is named
29940 @code{ada_main} and that in the DLL there is an entry point named
29941 @code{ada_dll}.
29943 @noindent
29944 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29945 program must have been built with the debugging information (see GNAT -g
29946 switch). Here are the step-by-step instructions for debugging it:
29948 @enumerate 1
29949 @item Launch @code{GDB} on the main program.
29951 @smallexample
29952 $ gdb -nw ada_main
29953 @end smallexample
29955 @item Start the program and stop at the beginning of the main procedure
29957 @smallexample
29958 (gdb) start
29959 @end smallexample
29961 @noindent
29962 This step is required to be able to set a breakpoint inside the DLL. As long
29963 as the program is not run, the DLL is not loaded. This has the
29964 consequence that the DLL debugging information is also not loaded, so it is not
29965 possible to set a breakpoint in the DLL.
29967 @item Set a breakpoint inside the DLL
29969 @smallexample
29970 (gdb) break ada_dll
29971 (gdb) cont
29972 @end smallexample
29974 @end enumerate
29976 @noindent
29977 At this stage a breakpoint is set inside the DLL. From there on
29978 you can use the standard approach to debug the whole program
29979 (@pxref{Running and Debugging Ada Programs}).
29981 @ignore
29982 @c This used to work, probably because the DLLs were non-relocatable
29983 @c keep this section around until the problem is sorted out.
29985 To break on the @code{DllMain} routine it is not possible to follow
29986 the procedure above. At the time the program stop on @code{ada_main}
29987 the @code{DllMain} routine as already been called. Either you can use
29988 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29990 @enumerate 1
29991 @item Launch @code{GDB} on the main program.
29993 @smallexample
29994 $ gdb ada_main
29995 @end smallexample
29997 @item Load DLL symbols
29999 @smallexample
30000 (gdb) add-sym api.dll
30001 @end smallexample
30003 @item Set a breakpoint inside the DLL
30005 @smallexample
30006 (gdb) break ada_dll.adb:45
30007 @end smallexample
30009 Note that at this point it is not possible to break using the routine symbol
30010 directly as the program is not yet running. The solution is to break
30011 on the proper line (break in @file{ada_dll.adb} line 45).
30013 @item Start the program
30015 @smallexample
30016 (gdb) run
30017 @end smallexample
30019 @end enumerate
30020 @end ignore
30022 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
30023 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
30025 @menu
30026 * Debugging the DLL Directly::
30027 * Attaching to a Running Process::
30028 @end menu
30030 @noindent
30031 In this case things are slightly more complex because it is not possible to
30032 start the main program and then break at the beginning to load the DLL and the
30033 associated DLL debugging information. It is not possible to break at the
30034 beginning of the program because there is no @code{GDB} debugging information,
30035 and therefore there is no direct way of getting initial control. This
30036 section addresses this issue by describing some methods that can be used
30037 to break somewhere in the DLL to debug it.
30039 @noindent
30040 First suppose that the main procedure is named @code{main} (this is for
30041 example some C code built with Microsoft Visual C) and that there is a
30042 DLL named @code{test.dll} containing an Ada entry point named
30043 @code{ada_dll}.
30045 @noindent
30046 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
30047 been built with debugging information (see GNAT -g option).
30049 @node Debugging the DLL Directly
30050 @subsubsection Debugging the DLL Directly
30052 @enumerate 1
30053 @item
30054 Find out the executable starting address
30056 @smallexample
30057 $ objdump --file-header main.exe
30058 @end smallexample
30060 The starting address is reported on the last line. For example:
30062 @smallexample
30063 main.exe:     file format pei-i386
30064 architecture: i386, flags 0x0000010a:
30065 EXEC_P, HAS_DEBUG, D_PAGED
30066 start address 0x00401010
30067 @end smallexample
30069 @item
30070 Launch the debugger on the executable.
30072 @smallexample
30073 $ gdb main.exe
30074 @end smallexample
30076 @item
30077 Set a breakpoint at the starting address, and launch the program.
30079 @smallexample
30080 $ (gdb) break *0x00401010
30081 $ (gdb) run
30082 @end smallexample
30084 The program will stop at the given address.
30086 @item
30087 Set a breakpoint on a DLL subroutine.
30089 @smallexample
30090 (gdb) break ada_dll.adb:45
30091 @end smallexample
30093 Or if you want to break using a symbol on the DLL, you need first to
30094 select the Ada language (language used by the DLL).
30096 @smallexample
30097 (gdb) set language ada
30098 (gdb) break ada_dll
30099 @end smallexample
30101 @item
30102 Continue the program.
30104 @smallexample
30105 (gdb) cont
30106 @end smallexample
30108 @noindent
30109 This will run the program until it reaches the breakpoint that has been
30110 set. From that point you can use the standard way to debug a program
30111 as described in (@pxref{Running and Debugging Ada Programs}).
30113 @end enumerate
30115 @noindent
30116 It is also possible to debug the DLL by attaching to a running process.
30118 @node Attaching to a Running Process
30119 @subsubsection Attaching to a Running Process
30120 @cindex DLL debugging, attach to process
30122 @noindent
30123 With @code{GDB} it is always possible to debug a running process by
30124 attaching to it. It is possible to debug a DLL this way. The limitation
30125 of this approach is that the DLL must run long enough to perform the
30126 attach operation. It may be useful for instance to insert a time wasting
30127 loop in the code of the DLL to meet this criterion.
30129 @enumerate 1
30131 @item Launch the main program @file{main.exe}.
30133 @smallexample
30134 $ main
30135 @end smallexample
30137 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
30138 that the process PID for @file{main.exe} is 208.
30140 @item Launch gdb.
30142 @smallexample
30143 $ gdb
30144 @end smallexample
30146 @item Attach to the running process to be debugged.
30148 @smallexample
30149 (gdb) attach 208
30150 @end smallexample
30152 @item Load the process debugging information.
30154 @smallexample
30155 (gdb) symbol-file main.exe
30156 @end smallexample
30158 @item Break somewhere in the DLL.
30160 @smallexample
30161 (gdb) break ada_dll
30162 @end smallexample
30164 @item Continue process execution.
30166 @smallexample
30167 (gdb) cont
30168 @end smallexample
30170 @end enumerate
30172 @noindent
30173 This last step will resume the process execution, and stop at
30174 the breakpoint we have set. From there you can use the standard
30175 approach to debug a program as described in
30176 (@pxref{Running and Debugging Ada Programs}).
30178 @node Setting Stack Size from gnatlink
30179 @section Setting Stack Size from @command{gnatlink}
30181 @noindent
30182 It is possible to specify the program stack size at link time. On modern
30183 versions of Windows, starting with XP, this is mostly useful to set the size of
30184 the main stack (environment task). The other task stacks are set with pragma
30185 Storage_Size or with the @command{gnatbind -d} command.
30187 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
30188 reserve size of individual tasks, the link-time stack size applies to all
30189 tasks, and pragma Storage_Size has no effect.
30190 In particular, Stack Overflow checks are made against this
30191 link-time specified size.
30193 This setting can be done with
30194 @command{gnatlink} using either:
30196 @itemize @bullet
30198 @item using @option{-Xlinker} linker option
30200 @smallexample
30201 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
30202 @end smallexample
30204 This sets the stack reserve size to 0x10000 bytes and the stack commit
30205 size to 0x1000 bytes.
30207 @item using @option{-Wl} linker option
30209 @smallexample
30210 $ gnatlink hello -Wl,--stack=0x1000000
30211 @end smallexample
30213 This sets the stack reserve size to 0x1000000 bytes. Note that with
30214 @option{-Wl} option it is not possible to set the stack commit size
30215 because the coma is a separator for this option.
30217 @end itemize
30219 @node Setting Heap Size from gnatlink
30220 @section Setting Heap Size from @command{gnatlink}
30222 @noindent
30223 Under Windows systems, it is possible to specify the program heap size from
30224 @command{gnatlink} using either:
30226 @itemize @bullet
30228 @item using @option{-Xlinker} linker option
30230 @smallexample
30231 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
30232 @end smallexample
30234 This sets the heap reserve size to 0x10000 bytes and the heap commit
30235 size to 0x1000 bytes.
30237 @item using @option{-Wl} linker option
30239 @smallexample
30240 $ gnatlink hello -Wl,--heap=0x1000000
30241 @end smallexample
30243 This sets the heap reserve size to 0x1000000 bytes. Note that with
30244 @option{-Wl} option it is not possible to set the heap commit size
30245 because the coma is a separator for this option.
30247 @end itemize
30249 @node Mac OS Topics
30250 @appendix Mac OS Topics
30251 @cindex OS X
30253 @noindent
30254 This chapter describes topics that are specific to Apple's OS X
30255 platform.
30257 @menu
30258 * Codesigning the Debugger::
30259 @end menu
30261 @node Codesigning the Debugger
30262 @section Codesigning the Debugger
30264 @noindent
30265 The Darwin Kernel requires the debugger to have special permissions
30266 before it is allowed to control other processes. These permissions
30267 are granted by codesigning the GDB executable. Without these
30268 permissions, the debugger will report error messages such as:
30270 @smallexample
30271 Starting program: /x/y/foo
30272 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
30273  (please check gdb is codesigned - see taskgated(8))
30274 @end smallexample
30276 Codesigning requires a certificate.  The following procedure explains
30277 how to create one:
30279 @itemize @bullet
30280 @item Start the Keychain Access application (in
30281 /Applications/Utilities/Keychain Access.app)
30283 @item Select the Keychain Access -> Certificate Assistant ->
30284 Create a Certificate... menu
30286 @item Then:
30288 @itemize @bullet
30289 @item Choose a name for the new certificate (this procedure will use
30290 "gdb-cert" as an example)
30292 @item Set "Identity Type" to "Self Signed Root"
30294 @item Set "Certificate Type" to "Code Signing"
30296 @item Activate the "Let me override defaults" option
30298 @end itemize
30300 @item Click several times on "Continue" until the "Specify a Location
30301 For The Certificate" screen appears, then set "Keychain" to "System"
30303 @item Click on "Continue" until the certificate is created
30305 @item Finally, in the view, double-click on the new certificate,
30306 and set "When using this certificate" to "Always Trust"
30308 @item Exit the Keychain Access application and restart the computer
30309 (this is unfortunately required)
30311 @end itemize
30313 Once a certificate has been created, the debugger can be codesigned
30314 as follow. In a Terminal, run the following command...
30316 @smallexample
30317 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
30318 @end smallexample
30320 ... where "gdb-cert" should be replaced by the actual certificate
30321 name chosen above, and <gnat_install_prefix> should be replaced by
30322 the location where you installed GNAT.
30324 @end ifset
30326 @c **********************************
30327 @c * GNU Free Documentation License *
30328 @c **********************************
30329 @include fdl.texi
30330 @c GNU Free Documentation License
30332 @node Index,,GNU Free Documentation License, Top
30333 @unnumbered Index
30335 @printindex cp
30337 @contents
30338 @c Put table of contents at end, otherwise it precedes the "title page" in
30339 @c the .txt version
30340 @c Edit the pdf file to move the contents to the beginning, after the title
30341 @c page
30343 @bye