1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2013, Free Software Foundation, Inc. o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
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''.
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:
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"
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
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
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}.
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
101 @set PLATFORM OpenVMS
102 @set TITLESUFFIX for OpenVMS
107 @c The ARG is an optional argument. To be used for macro arguments in
108 @c their documentation (@defmac).
110 @r{[}@var{\varname\}@r{]}@c
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
123 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
126 @include gcc-common.texi
128 @setchapternewpage odd
133 @title @value{EDITION} User's Guide
137 @titlefont{@i{@value{PLATFORM}}}
143 @subtitle GNAT, The GNU Ada Compiler
148 @vskip 0pt plus 1filll
155 @node Top, About This Guide, (dir), (dir)
156 @top @value{EDITION} User's Guide
159 @value{EDITION} User's Guide @value{PLATFORM}
162 GNAT, The GNU Ada Compiler@*
163 GCC version @value{version-GCC}@*
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::
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
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::
203 * Code Coverage and Profiling::
206 * Compatibility with HP Ada::
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::
214 * Compatibility and Porting Guide::
216 * Microsoft Windows Topics::
219 * GNU Free Documentation License::
222 --- The Detailed Node Listing ---
226 * What This Guide Contains::
227 * What You Should Know before Reading This Guide::
228 * Related Information::
231 Getting Started with GNAT
234 * Running a Simple Ada Program::
235 * Running a Program with Multiple Units::
236 * Using the gnatmake Utility::
238 * Editing with Emacs::
241 * Introduction to GPS::
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::
257 * Building Mixed Ada & C++ Programs::
258 * Comparison between GNAT and C/C++ Compilation Models::
260 * Comparison between GNAT and Conventional Ada Library Models::
262 * Placement of temporary files::
265 Foreign Language Representation
268 * Other 8-Bit Codes::
269 * Wide Character Encodings::
271 Compiling Ada Programs With gcc
273 * Compiling Programs::
275 * Search Paths and the Run-Time Library (RTL)::
276 * Order of Compilation Issues::
281 * Output and Error Message Control::
282 * Warning Message Control::
283 * Debugging and Assertion Control::
284 * Validity Checking::
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::
302 Binding Ada Programs With 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::
316 * Binding with Non-Ada Main Programs::
317 * Binding Programs with No Main Subprogram::
319 Linking Using gnatlink
322 * Switches for gnatlink::
324 The GNAT Make Program 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::
349 * Coverage Analysis::
352 Reducing Size of Ada Executables with 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::
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::
398 The GNAT Metrics Tool gnatmetric
400 * Switches for gnatmetric::
402 File Name Krunching Using gnatkr
407 * Examples of gnatkr Usage::
409 Preprocessing Using gnatprep
410 * Preprocessing Symbols::
412 * Switches for gnatprep::
413 * Form of Definitions File::
414 * Form of Input Text for gnatprep::
416 The GNAT Library Browser 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::
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::
445 Memory Management Issues
447 * Some Useful Memory Pools::
448 * The GNAT Debug Pool Facility::
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
467 * Switches for gnatmem::
468 * Example of gnatmem Usage::
471 Verifying Properties Using gnatcheck
473 Sample Bodies Using gnatstub
476 * Switches for gnatstub::
478 Creating Unit Tests Using gnattest
481 * Switches for gnattest::
482 * Project Attributes for gnattest::
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::
493 * Support for other platforms/run-times::
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::
504 Code Coverage and Profiling
506 * Code Coverage of Ada Programs using gcov::
507 * Profiling an Ada Program using gprof::
510 Running and Debugging Ada Programs
512 * The GNAT Debugger GDB::
514 * Introduction to GDB Commands::
515 * Using Ada Expressions::
516 * Calling User-Defined Subprograms::
517 * Using the Next Command in a Function::
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::
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::
543 * Main Program Definition::
544 * Implementation-Defined Attributes::
545 * Compiler and Run-Time Interfacing::
546 * Program Compilation and Library Management::
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::
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::
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::
583 * Shared Libraries and Options Files::
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
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
618 * Overflow Checking Modes in GNAT::
619 * Specifying the Desired Mode::
621 * Implementation Notes::
623 Conditional Compilation
624 * Use of Boolean Constants::
625 * Debugging - A Special Case::
626 * Conditionalizing Declarations::
627 * Use of Alternative Implementations::
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::
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::
649 * Compatibility with Other Ada Systems::
650 * Representation Clauses::
652 * Transitioning to 64-Bit GNAT for OpenVMS::
656 Microsoft Windows Topics
658 * Using GNAT on Windows::
659 * CONSOLE and WINDOWS subsystems::
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::
668 * Setting Stack Size from gnatlink::
669 * Setting Heap Size from gnatlink::
673 * Codesigning the Debugger::
680 @node About This Guide
681 @unnumbered About This Guide
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.
691 This guide describes the use of @value{EDITION},
692 a compiler and software development
693 toolset for the full Ada programming language.
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.
709 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
710 ``GNAT'' in the remainder of this document.
717 * What This Guide Contains::
718 * What You Should Know before Reading This Guide::
719 * Related Information::
723 @node What This Guide Contains
724 @unnumberedsec What This Guide Contains
727 This guide contains the following chapters:
731 @ref{Getting Started with GNAT}, describes how to get started compiling
732 and running Ada programs with the GNAT Ada programming environment.
734 @ref{The GNAT Compilation Model}, describes the compilation model used
738 @ref{Compiling Using gcc}, describes how to compile
739 Ada programs with @command{gcc}, the Ada compiler.
742 @ref{Binding Using gnatbind}, describes how to
743 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
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.
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
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
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.
773 @ref{Configuration Pragmas}, describes the configuration pragmas
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.
782 @ref{GNAT Project Manager}, describes how to use project files
783 to organize large projects.
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.
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.
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.
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.
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
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.
817 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
818 to delete files that are produced by the compiler, binder and linker.
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
827 @ref{Using the GNU make Utility}, describes some techniques for using
828 the GNAT toolset in Makefiles.
832 @ref{Memory Management Issues}, describes some useful predefined storage pools
833 and in particular the GNAT Debug Pool facility, which helps detect incorrect
836 It also describes @command{gnatmem}, a utility that monitors dynamic
837 allocation and deallocation and helps detect ``memory leaks''.
841 @ref{Stack Related Facilities}, describes some useful tools associated with
842 stack checking and analysis.
845 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
846 a utility that checks Ada code against a set of rules.
849 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
850 a utility that generates empty but compilable bodies for library units.
853 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
854 a utility that generates unit testing templates for library units.
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).
863 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
864 generate automatically Ada bindings from C and C++ headers.
867 @ref{Other Utility Programs}, discusses several other GNAT utilities,
868 including @code{gnathtml}.
872 @ref{Code Coverage and Profiling}, describes how to perform a structural
873 coverage and profile the execution of Ada programs.
877 @ref{Running and Debugging Ada Programs}, describes how to run and debug
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,
888 historical compatibility reasons, the relevant libraries still use the
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.
899 @ref{Example of Binder Output File}, shows the source code for the binder
900 output file for a sample program.
903 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
904 you deal with elaboration order issues.
907 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
908 you deal with arithmetic overflow issues.
911 @ref{Conditional Compilation}, describes how to model conditional compilation,
912 both with Ada in general and with GNAT facilities in particular.
915 @ref{Inline Assembler}, shows how to use the inline assembly facility
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.
925 @ref{Microsoft Windows Topics}, presents information relevant to the
926 Microsoft Windows platform.
929 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
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
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
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
948 Both reference manuals are included in the GNAT documentation
951 @node Related Information
952 @unnumberedsec Related Information
955 For further information about related tools, refer to the following
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.
966 @cite{Using the GNAT Programming Studio}, which describes the GPS
967 Integrated Development Environment.
970 @cite{GNAT Programming Studio Tutorial}, which introduces the
971 main GPS features through examples.
975 @cite{Ada 95 Reference Manual}, which contains reference
976 material for the Ada 95 programming language.
979 @cite{Ada 2005 Reference Manual}, which contains reference
980 material for the Ada 2005 programming language.
983 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
985 in the GNU:[DOCS] directory,
987 for all details on the use of the GNU source-level debugger.
990 @xref{Top,, The extensible self-documenting text editor, emacs,
993 located in the GNU:[DOCS] directory if the EMACS kit is installed,
995 for full information on the extensible editor and programming
1002 @unnumberedsec Conventions
1004 @cindex Typographical conventions
1007 Following are examples of the typographical and graphic conventions used
1012 @code{Functions}, @command{utility program names}, @code{standard names},
1016 @option{Option flags}
1019 @file{File names}, @samp{button names}, and @samp{field names}.
1022 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1029 @r{[}optional information or parameters@r{]}
1032 Examples are described by text
1034 and then shown this way.
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.
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.
1053 @c ****************************
1054 @node Getting Started with GNAT
1055 @chapter Getting Started with GNAT
1058 This chapter describes some simple ways of using GNAT to build
1059 executable Ada programs.
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}.
1075 * Running a Simple Ada Program::
1076 * Running a Program with Multiple Units::
1077 * Using the gnatmake Utility::
1079 * Editing with Emacs::
1082 * Introduction to GPS::
1087 @section Running GNAT
1090 Three steps are needed to create an executable file from an Ada source
1095 The source file(s) must be compiled.
1097 The file(s) must be bound using the GNAT binder.
1099 All appropriate object files must be linked to produce an executable.
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
1111 Any text editor may be used to prepare an Ada program.
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
1121 with Ada.Text_IO; use Ada.Text_IO;
1124 Put_Line ("Hello WORLD!");
1130 This file should be named @file{hello.adb}.
1131 With the normal default file naming conventions, GNAT requires
1133 contain a single compilation unit whose file name is the
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):
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.
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.)
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:
1187 A simpler method of carrying out these steps is to use
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})
1197 $ gnatmake hello.adb
1201 The result is an executable program called @file{hello}, which can be
1209 assuming that the current directory is on the search path
1210 for executable programs.
1213 and, if all has gone well, you will see
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
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
1233 package Greetings is
1238 with Ada.Text_IO; use Ada.Text_IO;
1239 package body Greetings is
1242 Put_Line ("Hello WORLD!");
1245 procedure Goodbye is
1247 Put_Line ("Goodbye WORLD!");
1264 Following the one-unit-per-file rule, place this program in the
1265 following three separate files:
1269 spec of package @code{Greetings}
1272 body of package @code{Greetings}
1275 body of main program
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:
1285 $ gcc -c greetings.adb
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:
1300 $ gcc -c greetings.ads -gnatc
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:
1311 $ gnatmake gmain.adb
1315 In the next section we discuss the advantages of using @command{gnatmake} in
1318 @c *****************************
1319 @node Using the gnatmake Utility
1320 @section Using the @command{gnatmake} Utility
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:
1347 $ gnatmake gmain.adb
1348 $ gnatmake ^gmain^GMAIN^
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.
1372 @node Editing with Emacs
1373 @section Editing with Emacs
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
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.
1401 @node Introduction to GPS
1402 @section Introduction to GPS
1403 @cindex GPS (GNAT Programming Studio)
1404 @cindex GNAT Programming Studio (GPS)
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
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
1425 * Building a New Program with GPS::
1426 * Simple Debugging with GPS::
1429 @node Building a New Program with GPS
1430 @subsection Building a New Program with GPS
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
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
1454 @code{Start with default project in directory}
1457 @code{Create new project with wizard}
1460 @code{Open existing project}
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:
1504 A @emph{Workspace area}, initially greyed out, which you will use for
1505 creating and editing source files
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.)
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
1521 with Ada.Text_IO; use Ada.Text_IO;
1524 Put_Line("Hello from GPS!");
1530 Select @code{File}, then @code{Save As}, and enter the source file name
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.
1539 the @code{Project} menu and then @code{Edit project properties}.
1540 Click the @code{Main files} tab on the left, and then the
1542 Choose @file{hello.adb} from the list, and press @code{Open}.
1543 The project settings window will reflect this action.
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''
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.
1568 @node Simple Debugging with GPS
1569 @subsection Simple Debugging with GPS
1571 This section illustrates basic debugging techniques (setting breakpoints,
1572 examining/modifying variables, single stepping).
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
1581 @item @emph{Creating a source file}
1583 Select @code{File}, then @code{New}, and type in the following program:
1585 @smallexample @c ada
1587 with Ada.Text_IO; use Ada.Text_IO;
1588 procedure Example is
1589 Line : String (1..80);
1592 Put_Line("Type a line of text at each prompt; an empty line to exit");
1596 Put_Line (Line (1..N) );
1604 Select @code{File}, then @code{Save as}, and enter the file name
1607 @item @emph{Updating the project file}
1609 Add @code{Example} as a new main unit for the project:
1612 Select @code{Project}, then @code{Edit Project Properties}.
1615 Select the @code{Main files} tab, click @code{Add}, then
1616 select the file @file{example.adb} from the list, and
1618 You will see the file name appear in the list of main units
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
1638 Thus unless you intentionally remove these settings, you will be able
1639 to debug any program that you develop using GPS.
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
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.
1711 @node The GNAT Compilation Model
1712 @chapter The GNAT Compilation Model
1713 @cindex GNAT compilation model
1714 @cindex Compilation model
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::
1728 * Building Mixed Ada & C++ Programs::
1729 * Comparison between GNAT and C/C++ Compilation Models::
1731 * Comparison between GNAT and Conventional Ada Library Models::
1733 * Placement of temporary files::
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
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:
1764 Vertical tab, @code{16#0B#}
1768 Horizontal tab, @code{16#09#}
1772 Carriage return, @code{16#0D#}
1776 Line feed, @code{16#0A#}
1780 Form feed, @code{16#0C#}
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
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
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}).
1815 * Other 8-Bit Codes::
1816 * Wide Character Encodings::
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
1843 GNAT also supports several other 8-bit coding schemes:
1846 @item ISO 8859-2 (Latin-2)
1849 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1852 @item ISO 8859-3 (Latin-3)
1855 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1858 @item ISO 8859-4 (Latin-4)
1861 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1864 @item ISO 8859-5 (Cyrillic)
1867 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1868 lowercase equivalence.
1870 @item ISO 8859-15 (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).
1899 No upper-half characters in the range 80-FF are allowed in identifiers.
1900 This gives Ada 83 compatibility for identifier names.
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
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:
1920 In this encoding, a wide character is represented by the following five
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
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
1943 @item Shift JIS Coding
1944 @cindex Shift JIS Coding
1945 A wide character is represented by a two-character sequence,
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.
1955 A wide character is represented by a two-character sequence
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.
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:
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}#
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
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.
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
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
2024 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2027 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
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
2035 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2038 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
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.
2051 @item arith_functions.ads
2052 Arith_Functions (package spec)
2053 @item arith_functions.adb
2054 Arith_Functions (package body)
2056 Func.Spec (child package spec)
2058 Func.Spec (child package body)
2060 Sub (subunit of Main)
2061 @item ^a~bad.adb^A$BAD.ADB^
2062 A.Bad (child package body)
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
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
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
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");
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}
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:
2142 $ gcc -c -x ada peculiar_file_name.sim
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
2153 @node Alternative File Naming Schemes
2154 @section Alternative File Naming Schemes
2155 @cindex File naming schemes, alternative
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
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
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:
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.
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.
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.
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
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");
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 => "-");
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);
2293 @node Generating Object Files
2294 @section Generating Object Files
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:
2304 If a package spec has no body, compile the package spec to produce the
2305 object file for the package.
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.
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.
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
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).
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.
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
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
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
2365 In addition to this basic dependency, a given object may depend on
2366 additional source files as follows:
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.
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
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.
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.
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}.
2415 The object file for a parent unit depends on all its subunit body files.
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.
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
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}.
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
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.
2457 Version information (indicates which version of GNAT was used to compile
2458 the unit(s) in question)
2461 Main program information (including priority and time slice settings,
2462 as well as the wide character encoding used during compilation).
2465 List of arguments used in the @command{gcc} command for the compilation
2468 Attributes of the unit, including configuration pragmas used, an indication
2469 of whether the compilation was successful, exception model used etc.
2472 A list of relevant restrictions applying to the unit (used for consistency)
2476 Categorization information (e.g.@: use of pragma @code{Pure}).
2479 Information on all @code{with}'ed units, including presence of
2480 @code{Elaborate} or @code{Elaborate_All} pragmas.
2483 Information from any @code{Linker_Options} pragmas used in the unit
2486 Information on the use of @code{Body_Version} or @code{Version}
2487 attributes in the unit.
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.
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.
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
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
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
2547 This section describes how to develop a mixed-language program,
2548 specifically one that comprises units in both Ada and C.
2551 * Interfacing to C::
2552 * Calling Conventions::
2555 @node Interfacing to C
2556 @subsection Interfacing to C
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:
2574 void print_num (int num)
2576 printf ("num is %d.\n", num);
2582 /* num_from_Ada is declared in my_main.adb */
2583 extern int num_from_Ada;
2587 return num_from_Ada;
2591 @smallexample @c ada
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");
2610 Print_Num (Get_Num);
2616 To build this example, first compile the foreign language files to
2617 generate object files:
2619 ^gcc -c file1.c^gcc -c FILE1.C^
2620 ^gcc -c file2.c^gcc -c FILE2.C^
2624 Then, compile the Ada units to produce a set of object files and ALI
2627 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2631 Run the Ada binder on the Ada main program:
2633 gnatbind my_main.ali
2637 Link the Ada main program, the Ada objects and the other language
2640 gnatlink my_main.ali file1.o file2.o
2644 The last three steps can be grouped in a single command:
2646 gnatmake my_main.adb -largs file1.o file2.o
2649 @cindex Binder output file
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:
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[])
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));
2686 @smallexample @c ada
2689 function Add (A, B : Integer) return Integer;
2690 pragma Export (C, Add, "add");
2694 package body Unit1 is
2695 function Add (A, B : Integer) return Integer is
2703 function Sub (A, B : Integer) return Integer;
2704 pragma Export (C, Sub, "sub");
2708 package body Unit2 is
2709 function Sub (A, B : Integer) return Integer is
2718 The build procedure for this application is similar to the last
2719 example's. First, compile the foreign language files to generate object
2722 ^gcc -c main.c^gcc -c main.c^
2726 Next, compile the Ada units to produce a set of object files and ALI
2729 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2730 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
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:
2737 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2741 Link the Ada main program, the Ada objects and the foreign language
2742 objects. You need only list the last ALI file here:
2744 gnatlink unit2.ali main.o -o exec_file
2747 This procedure yields a binary executable called @file{exec_file}.
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:
2765 @cindex Interfacing to Ada
2766 @cindex Other Ada compilers
2767 @cindex Convention 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
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
2807 Equivalent to Assembler.
2809 @cindex Interfacing to COBOL
2810 @cindex Convention COBOL
2813 Data will be passed according to the conventions described
2814 in section B.4 of the Ada Reference Manual.
2817 @cindex Interfacing to C
2818 @cindex Convention 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
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}.
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.
2850 @cindex Convention Default
2855 @cindex Convention External
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.
2871 @cindex Interfacing to Fortran
2872 @cindex Convention Fortran
2874 Data will be passed according to the conventions described
2875 in section B.5 of the Ada Reference Manual.
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:
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.
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)
2908 pragma Import (Intrinsic, "/");
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.
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");
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
2938 @cindex Convention 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.
2947 @cindex Convention DLL
2949 This is equivalent to @code{Stdcall}.
2952 @cindex Convention Win32
2954 This is equivalent to @code{Stdcall}.
2958 @cindex Convention Stubbed
2960 This is a special convention that indicates that the compiler
2961 should provide a stub body that raises @code{Program_Error}.
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
2971 @smallexample @c ada
2972 pragma Convention_Identifier (Fortran77, Fortran);
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
2981 @node Building Mixed Ada & C++ Programs
2982 @section Building Mixed Ada and C++ Programs
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++.
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.
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::
3004 @node Interfacing to C++
3005 @subsection Interfacing to C++
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).
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:
3022 by modifying the C++ code in order to force a C convention using
3023 the @code{extern "C"} syntax.
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.
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
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
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
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
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++
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:
3078 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
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:
3091 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
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
3100 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3101 to the libgcc libraries are required:
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
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:
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
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.
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
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
3150 Here are the compilation commands:
3152 $ gnatmake -c simple_cpp_interface
3155 $ gnatbind -n simple_cpp_interface
3156 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3157 -lstdc++ ex7.o cpp_main.o
3161 Here are the corresponding sources:
3169 void adainit (void);
3170 void adafinal (void);
3171 void method1 (A *t);
3193 class A : public Origin @{
3195 void method1 (void);
3196 void method2 (int v);
3206 extern "C" @{ void ada_method2 (A *t, int v);@}
3208 void A::method1 (void)
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);
3225 printf ("in A::A, a_value = %d \n",a_value);
3229 @smallexample @c ada
3231 package body Simple_Cpp_Interface is
3233 procedure Ada_Method2 (This : in out A; V : Integer) is
3239 end Simple_Cpp_Interface;
3242 package Simple_Cpp_Interface is
3245 Vptr : System.Address;
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;
3260 @node Interfacing with C++ constructors
3261 @subsection Interfacing with C++ constructors
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
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
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;
3293 type Root is tagged limited 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");
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:
3325 On the right side of an initialization of an object of type @var{T}.
3327 On the right side of an initialization of a record component of type @var{T}.
3329 In an Ada 2005 limited aggregate.
3331 In an Ada 2005 nested limited aggregate.
3333 In an Ada 2005 limited aggregate that initializes an object built in
3334 place by an extended return statement.
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
3345 Obj2 : Root := Constructor;
3346 Obj3 : Root := Constructor (v => 10);
3347 Obj4 : Root := Constructor (30, 40);
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;
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
3373 Obj6 : DT := Function_Returning_DT (50);
3374 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
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;
3395 type Rec2 (D : Integer := 20) is limited record
3397 Data2 : Root := Constructor (D, 30);
3401 The initialization of an object of type @code{Rec2} will call the
3402 non-default C++ constructors specified for the imported components.
3405 @smallexample @c ada
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),
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
3436 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3439 -- Further actions required for construction of
3440 -- objects of type Rec2
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
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.
3470 @b{virtual} void Set_Age (int New_Age);
3471 @b{virtual} int Age ();
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:
3483 @b{class} Carnivore @{
3485 @b{virtual} int Number_Of_Teeth () = 0;
3488 @b{class} Domestic @{
3490 @b{virtual void} Set_Owner (char* Name) = 0;
3494 Using these declarations, we can now say that a @code{Dog} is an animal that is
3495 both Carnivore and Domestic, that is:
3498 @b{class} Dog : Animal, Carnivore, Domestic @{
3500 @b{virtual} int Number_Of_Teeth ();
3501 @b{virtual} void Set_Owner (char* Name);
3503 Dog(); // Constructor
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;
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);
3525 (X : in out Domestic;
3526 Name : Chars_Ptr) is abstract;
3528 type Animal is tagged 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);
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");
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
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.
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;
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;
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);
3612 (X : in out Domestic;
3613 Name : Chars_Ptr) is abstract;
3615 type Animal is tagged 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);
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);
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:
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{}@}
3665 void adainit (void);
3666 void adafinal (void);
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
3681 adainit (); test(); adafinal ();
3686 @node Comparison between GNAT and C/C++ Compilation Models
3687 @section Comparison between GNAT and C/C++ Compilation Models
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
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
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.
3719 @node Comparison between GNAT and Conventional Ada Library Models
3720 @section Comparison between GNAT and Conventional Ada Library Models
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:
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.
3743 Inlining is effective only if the necessary body has already been
3744 compiled into the library.
3747 Compiling a unit may obsolete other units in the library.
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:
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
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.
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.
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
3783 @node Placement of temporary files
3784 @section Placement of temporary files
3785 @cindex Temporary files (user control over placement)
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:
3799 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
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.
3812 @c *************************
3813 @node Compiling Using gcc
3814 @chapter Compiling Using @command{gcc}
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.
3821 * Compiling Programs::
3822 * Switches for gcc::
3823 * Search Paths and the Run-Time Library (RTL)::
3824 * Order of Compilation Issues::
3828 @node Compiling Programs
3829 @section Compiling Programs
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
3838 the body file (@file{.adb}) for a library level subprogram or generic
3842 the spec file (@file{.ads}) for a library level package or generic
3843 package that has no body
3846 the body file (@file{.adb}) for a library level package
3847 or generic package that has a body
3852 You need @emph{not} compile the following files
3857 the spec of a library unit which has a body
3864 because they are compiled as part of compiling related units. GNAT
3866 when the corresponding body is compiled, and subunits when the parent is
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
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
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
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}
3902 where @var{file name} is the name of the Ada file (usually
3904 @file{.ads} for a spec or @file{.adb} for a body).
3907 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
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.
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
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:
3933 $ gcc -c x.adb y.adb z.c
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.^
3944 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3947 @node Switches for gcc
3948 @section Switches for @command{gcc}
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
3963 * Output and Error Message Control::
3964 * Warning Message Control::
3965 * Debugging and Assertion Control::
3966 * Validity Checking::
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::
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.
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.
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.
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.
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
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.
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.
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.
4092 @cindex @option{-fstack-check} (@command{gcc})
4093 Activates stack checking.
4094 See @ref{Stack Overflow Checking} for details.
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.
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.
4109 @cindex @option{-gnat83} (@command{gcc})
4110 Enforce Ada 83 restrictions.
4113 @cindex @option{-gnat95} (@command{gcc})
4114 Enforce Ada 95 restrictions.
4117 @cindex @option{-gnat05} (@command{gcc})
4118 Allow full Ada 2005 features.
4121 @cindex @option{-gnat2005} (@command{gcc})
4122 Allow full Ada 2005 features (same as @option{-gnat05})
4125 @cindex @option{-gnat12} (@command{gcc})
4128 @cindex @option{-gnat2012} (@command{gcc})
4129 Allow full Ada 2012 features (same as @option{-gnat12})
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
4145 @cindex @option{-gnatA} (@command{gcc})
4146 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4150 @cindex @option{-gnatb} (@command{gcc})
4151 Generate brief messages to @file{stderr} even if verbose mode set.
4154 @cindex @option{-gnatB} (@command{gcc})
4155 Assume no invalid (bad) values except for 'Valid attribute use
4156 (@pxref{Validity Checking}).
4159 @cindex @option{-gnatc} (@command{gcc})
4160 Check syntax and semantics only (no code generation attempted).
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).
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
4182 @cindex @option{-gnatD[nn]} (@command{gcc})
4185 @item /XDEBUG /LXDEBUG=nnn
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
4199 (the equal sign is optional)
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}).
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.
4222 @cindex @option{-gnatef} (@command{gcc})
4223 Display full source path name in brief error messages.
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.
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
4251 (the equal sign is optional)
4253 (@pxref{Units to Sources Mapping Files}).
4255 @item -gnatep=@var{file}
4256 @cindex @option{-gnatep} (@command{gcc})
4257 Specify a preprocessing data file
4259 (the equal sign is optional)
4261 (@pxref{Integrated Preprocessing}).
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.
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.
4292 @cindex @option{-gnatE} (@command{gcc})
4293 Full dynamic elaboration checks.
4296 @cindex @option{-gnatf} (@command{gcc})
4297 Full errors. Multiple errors per line, all undefined references, do not
4298 attempt to suppress cascaded errors.
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.
4317 @cindex @option{-gnatG[nn]} (@command{gcc})
4320 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
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
4332 (@var{c}=1/2/3/4/8/9/p/f/n/w).
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.
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)^^.
4360 @cindex @option{-gnatl} (@command{gcc})
4361 Output full source listing with embedded error messages.
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
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.
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.
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.
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}'
4410 all intermediate overflows checked against base type (@code{STRICT})
4412 minimize intermediate overflows (@code{MINIMIZED})
4414 eliminate intermediate overflows (@code{ELIMINATED})
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
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}.
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.
4443 @cindex @option{-gnat-p} (@command{gcc})
4444 Cancel effect of previous @option{-gnatp} switch.
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
4454 @cindex @option{-gnatq} (@command{gcc})
4455 Don't quit. Try semantics, even if parse errors.
4458 @cindex @option{-gnatQ} (@command{gcc})
4459 Don't quit. Generate @file{ALI} and tree files even if illegalities.
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.
4470 @cindex @option{-gnats} (@command{gcc})
4474 @cindex @option{-gnatS} (@command{gcc})
4475 Print package Standard.
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.
4486 @cindex @option{-gnatu} (@command{gcc})
4487 List units for this compilation.
4490 @cindex @option{-gnatU} (@command{gcc})
4491 Tag all error messages with the unique string ``error:''
4494 @cindex @option{-gnatv} (@command{gcc})
4495 Verbose mode. Full error output with source lines to @file{stdout}.
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})
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
4512 (@var{e}=n/h/u/s/e/8).
4515 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4519 @cindex @option{-gnatx} (@command{gcc})
4520 Suppress generation of cross-reference information.
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
4534 (@var{m}=r/c for receiver/caller stubs).
4537 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4538 to be generated and compiled).
4541 @item ^-I^/SEARCH=^@var{dir}
4542 @cindex @option{^-I^/SEARCH^} (@command{gcc})
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})
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)}).
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.
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.
4575 @cindex @option{-nostdinc} (@command{gcc})
4576 Inhibit the search of the default location for the GNAT Run Time
4577 Library (RTL) source files.
4580 @cindex @option{-nostdlib} (@command{gcc})
4581 Inhibit the search of the default location for the GNAT Run Time
4582 Library (RTL) ALI files.
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.
4593 No optimization, the default setting if no @option{-O} appears
4596 Normal optimization, the default if you specify @option{-O} without
4597 an operand. A good compromise between code quality and compilation
4601 Extensive optimization, may improve execution time, possibly at the cost of
4602 substantially increased compilation time.
4605 Same as @option{-O2}, and also includes inline expansion for small subprograms
4609 Optimize space usage
4613 See also @ref{Optimization Levels}.
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}
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:
4629 Perform most optimizations, including those that
4631 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4632 without keyword options.
4635 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4638 Perform some optimizations, but omit ones that are costly.
4641 Same as @code{SOME}.
4644 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4645 automatic inlining of small subprograms within a unit
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.
4653 Optimize space usage
4657 See also @ref{Optimization Levels}.
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
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}).
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.
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.
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.
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
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
4719 is equivalent to specifying the following sequence of switches:
4722 -gnato -gnatf -gnati3
4727 The following restrictions apply to the combination of switches
4732 The switch @option{-gnatc} if combined with other switches must come
4733 first in the string.
4736 The switch @option{-gnats} if combined with other switches must come
4737 first in the string.
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.
4746 The switch @option{-gnat-p} may not be combined with any other switch.
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}).
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}).
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}).
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}).
4770 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4771 a combined list of options.
4775 @node Output and Error Message Control
4776 @subsection Output and Error Message Control
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:
4785 e.adb:3:04: Incorrect spelling of keyword "function"
4786 e.adb:4:20: ";" should be "is"
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.
4793 @code{GPS} can parse the error messages
4794 and point to the referenced character.
4796 The following switches provide control over the error message
4802 @cindex @option{-gnatv} (@command{gcc})
4805 The v stands for verbose.
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:
4814 3. funcion X (Q : Integer)
4816 >>> Incorrect spelling of keyword "function"
4819 >>> ";" should be "is"
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.
4829 @cindex @option{-gnatl} (@command{gcc})
4831 The @code{l} stands for list.
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
4843 1. package body p is
4845 3. procedure a is separate;
4856 2. pragma Elaborate_Body
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^.
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
4903 @cindex @option{-gnatb} (@command{gcc})
4905 The @code{b} stands for brief.
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})
4916 The @code{m} stands for maximum.
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
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
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.
4939 Note that the equal sign is optional, so the switches
4940 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4943 @cindex @option{-gnatf} (@command{gcc})
4944 @cindex Error messages, suppressing
4946 The @code{f} stands for full.
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
4954 e.adb:7:07: "V" is undefined (more references follow)
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
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
4972 The @option{-gnatf} switch also generates additional information for
4973 some error messages. Some examples are:
4977 Details on possibly non-portable unchecked conversion
4979 List possible interpretations for ambiguous calls
4981 Additional details on incorrect parameters
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.
4998 @cindex @option{-gnatq} (@command{gcc})
5000 The @code{q} stands for quit (really ``don't quit'').
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.
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.
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
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.
5040 @node Warning Message Control
5041 @subsection Warning Message Control
5042 @cindex Warning messages
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
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:
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
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.
5073 Possible infinitely recursive calls
5076 Out-of-range values being assigned
5079 Possible order of elaboration problems
5082 Assertions (pragma Assert) that are sure to fail
5088 Address clauses with possibly unaligned values, or where an attempt is
5089 made to overlay a smaller variable with a larger one.
5092 Fixed-point type declarations with a null range
5095 Direct_IO or Sequential_IO instantiated with a type that has access values
5098 Variables that are never assigned a value
5101 Variables that are referenced before being initialized
5104 Task entries with no corresponding @code{accept} statement
5107 Duplicate accepts for the same task entry in a @code{select}
5110 Objects that take too much storage
5113 Unchecked conversion between types of differing sizes
5116 Missing @code{return} statement along some execution path in a function
5119 Incorrect (unrecognized) pragmas
5122 Incorrect external names
5125 Allocation from empty storage pool
5128 Potentially blocking operation in protected type
5131 Suspicious parenthesization of expressions
5134 Mismatching bounds in an aggregate
5137 Attempt to return local value by reference
5140 Premature instantiation of a generic body
5143 Attempt to pack aliased components
5146 Out of bounds array subscripts
5149 Wrong length on string assignment
5152 Violations of style rules if style checking is enabled
5155 Unused @code{with} clauses
5158 @code{Bit_Order} usage that does not have any effect
5161 @code{Standard.Duration} used to resolve universal fixed expression
5164 Dereference of possibly null value
5167 Declaration that is likely to cause storage error
5170 Internal GNAT unit @code{with}'ed by application unit
5173 Values known to be out of range at compile time
5176 Unreferenced labels and variables
5179 Address overlays that could clobber memory
5182 Unexpected initialization when address clause present
5185 Bad alignment for address clause
5188 Useless type conversions
5191 Redundant assignment statements and other redundant constructs
5194 Useless exception handlers
5197 Accidental hiding of name by child unit
5200 Access before elaboration detected at compile time
5203 A range in a @code{for} loop that is known to be null or might be null
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}.
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
5223 @option{-gnatwd} (implicit dereferencing),
5224 @option{-gnatwh} (hiding),
5226 @option{-gnatw.d} (tag warnings with -gnatw switch)
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.
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.
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
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.
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
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
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.
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.
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.
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}.
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.
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}.
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.
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.
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.
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}.
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
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
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.
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.
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.
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
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).
5446 @emph{Suppress warnings on unrecognized pragmas.}
5447 @cindex @option{-gnatwG} (@command{gcc})
5448 This switch suppresses warnings for unrecognized pragmas.
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.
5462 @emph{Suppress warnings on hiding.}
5463 @cindex @option{-gnatwH} (@command{gcc})
5464 This switch suppresses warnings on hiding declarations.
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.
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.
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}.
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.
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.
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..
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}.
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.
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}.
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.
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.
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.
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
5602 This warning is not automatically turned on by the use of @option{-gnatwa}.
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.
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}.
5620 @emph{Suppress listing of inherited aspects.}
5621 @cindex @option{-gnatw.L} (@command{gcc})
5622 This switch suppresses listing of inherited aspects.
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.
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.
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.
5653 @emph{Disable warnings on suspicious modulus values.}
5654 @cindex @option{-gnatw.M} (@command{gcc})
5655 This switch disables warnings for suspicious modulus values.
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}.
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}.
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
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.
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.
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.
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
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
5736 that such warnings are not given.
5737 This warning can also be turned on using @option{-gnatwa}.
5740 @emph{Suppress warnings on parameter ordering.}
5741 @cindex @option{-gnatw.P} (@command{gcc})
5742 This switch suppresses warnings on cases of suspicious parameter
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}.
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.
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:
5773 Assignment of an item to itself.
5775 Type conversion that converts an expression to its own type.
5777 Use of the attribute @code{Base} where @code{typ'Base} is the same
5780 Use of pragma @code{Pack} when all components are placed by a record
5781 representation clause.
5783 Exception handler containing only a reraise statement (raise with no
5784 operand) which has no effect.
5786 Use of the operator abs on an operand that is known at compile time
5789 Comparison of boolean expressions to an explicit True value.
5792 This warning can also be turned on using @option{-gnatwa}.
5793 The default is that warnings for redundant constructs are not given.
5796 @emph{Suppress warnings on redundant constructs.}
5797 @cindex @option{-gnatwR} (@command{gcc})
5798 This switch suppresses warnings for redundant constructs.
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
5810 @emph{Suppress warnings for object renaming function.}
5811 @cindex @option{-gnatwT} (@command{gcc})
5812 This switch suppresses warnings for object renaming function.
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.
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
5840 Note that @option{-gnatwa} does not affect the setting of this warning option.
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.
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.
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.
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}.
5879 @emph{Suppress warnings on suspicious contracts.}
5880 @cindex @option{-gnatw.T} (@command{gcc})
5881 This switch suppresses warnings on suspicious postconditions.
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
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}.
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}).
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}.
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.
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}.
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 => <>);
5955 will suppress warnings on subsequent statements that access components
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}
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.
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}.
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);
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.
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)}.
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
6028 This warning can also be turned on using @option{-gnatwa}.
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.
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.
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.
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}.
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.
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
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}.
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^
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.
6130 A string of warning parameters can be used in the same parameter. For example:
6137 will turn on all optional warnings except for unrecognized pragma warnings,
6138 and also specify that warnings should be treated as errors.
6141 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
6184 @node Debugging and Assertion Control
6185 @subsection Debugging and Assertion Control
6189 @cindex @option{-gnata} (@command{gcc})
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:
6203 @b{pragma} Assert (@var{Boolean-expression} @r{[},
6204 @var{static-string-expression}@r{]})
6205 @b{pragma} Debug (@var{procedure call})
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
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.
6225 @item /DEBUG@r{[}=debug-level@r{]}
6227 Specifies how much debugging information is to be included in
6228 the resulting object file where 'debug-level' is one of the following:
6231 Include both debugger symbol records and traceback
6233 This is the default setting.
6235 Include both debugger symbol records and traceback in
6238 Excludes both debugger symbol records and traceback
6239 the object file. Same as /NODEBUG.
6241 Includes only debugger symbol records in the object
6242 file. Note that this doesn't include traceback information.
6247 @node Validity Checking
6248 @subsection Validity Checking
6249 @findex Validity Checking
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
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.
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.
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.
6303 @emph{All validity checks.}
6304 @cindex @option{-gnatVa} (@command{gcc})
6305 All validity checks are turned on.
6307 That is, @option{-gnatVa} is
6308 equivalent to @option{gnatVcdfimorst}.
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.
6318 @emph{Default (RM) validity checks.}
6319 @cindex @option{-gnatVd} (@command{gcc})
6320 Some validity checks are done by default following normal Ada semantics
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.
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.
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.
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.
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.
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.
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).
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.
6411 @emph{Validity checks for function returns.}
6412 @cindex @option{-gnatVr} (@command{gcc})
6413 The expression in @code{return} statements in functions is validity
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).
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.
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.
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,
6442 the upper case letters @code{CDFIMORST} may
6443 be used to turn off the corresponding lower case option.
6446 the prefix @code{NO} on an option turns off the corresponding validity
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}
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
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.
6504 @code{(option,option,@dots{})} is a sequence of keywords
6507 The string @var{x} is a sequence of letters or digits
6509 indicating the particular style
6510 checks to be performed. The following checks are defined:
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
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.
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
6554 @emph{Check comments, double space.}
6555 Comments must meet the following set of rules:
6560 The ``@code{--}'' that starts the column must either start in column one,
6561 or else at least one blank must precede this sequence.
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.
6568 Full line comments must have at least two blanks following the
6569 ``@code{--}'' that starts the comment, with the following exceptions.
6572 A line consisting only of the ``@code{--}'' characters, possibly preceded
6573 by blanks is permitted.
6576 A comment starting with ``@code{--x}'' where @code{x} is a special character
6578 This allows proper processing of the output generated by specialized tools
6579 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
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).
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.
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
6598 ---------------------------
6599 -- This is a box comment --
6600 -- with two text lines. --
6601 ---------------------------
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
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.
6622 @emph{No form feeds or vertical tabs.}
6623 Neither form feeds nor vertical tab characters are permitted
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.
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
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.
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.
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
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
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
6719 The same alternative format is allowed for loops. For example, both of
6720 the following are permitted:
6722 @smallexample @c ada
6724 Clear : while J < 10 loop
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}).
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
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.
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
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}.
6812 @emph{Check token spacing.}
6813 The following token spacing rules are enforced:
6818 The keywords @code{abs} and @code{not} must be followed by a space.
6821 The token @code{=>} must be surrounded by spaces.
6824 The token @code{<>} must be preceded by a space or a left parenthesis.
6827 Binary operators other than @code{**} must be surrounded by spaces.
6828 There is no restriction on the layout of the @code{**} binary operator.
6831 Colon must be surrounded by spaces.
6834 Colon-equal (assignment, initialization) must be surrounded by spaces.
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
6842 If the token preceding a left parenthesis ends with a letter or digit, then
6843 a space must separate the two tokens.
6846 if the token following a right parenthesis starts with a letter or digit, then
6847 a space must separate the two tokens.
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.
6854 A semicolon must not be preceded by a space, and must not be followed by
6855 a non-blank character.
6858 A unary plus or minus may not be followed by a space.
6861 A vertical bar must be surrounded by spaces.
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}.
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{-}.
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^,
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.
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.
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.
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.
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
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
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.
6971 @cindex @option{-gnatp} (@command{gcc})
6972 @cindex Suppressing checks
6973 @cindex Checks, suppressing
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
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.
7009 @cindex @option{-gnat-p} (@command{gcc})
7010 @cindex Suppressing checks
7011 @cindex Checks, suppressing
7013 This switch cancels the effect of a previous @option{gnatp} switch.
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
7026 Overflow checks are always enabled by this switch. The argument
7027 controls the mode, using the codes
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.
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).
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
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.
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}.
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}.
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
7111 @node Using gcc for Syntax Checking
7112 @subsection Using @command{gcc} for Syntax Checking
7115 @cindex @option{-gnats} (@command{gcc})
7119 The @code{s} stands for ``syntax''.
7122 Run GNAT in syntax checking only mode. For
7123 example, the command
7126 $ gcc -c -gnats x.adb
7130 compiles file @file{x.adb} in syntax-check-only mode. You can check a
7131 series of files in a single command
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.
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:
7146 $ gcc -c -gnats -x ada toto.txt
7147 toto.txt:1:01: warning: empty file, contains no compilation units
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
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}).
7166 @node Using gcc for Semantic Checking
7167 @subsection Using @command{gcc} for Semantic Checking
7170 @cindex @option{-gnatc} (@command{gcc})
7174 The @code{c} stands for ``check''.
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:
7186 The needed source files must be accessible
7187 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7190 Each file must contain only one compilation unit.
7193 The file name and unit name must match (@pxref{File Naming Rules}).
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).
7208 @node Compiling Different Versions of Ada
7209 @subsection Compiling Different Versions of Ada
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.
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
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})
7255 This switch directs the compiler to implement the Ada 95 version of the
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
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
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).
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
7296 This switch directs the compiler to implement the Ada 2012 version of the
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
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.
7323 @node Character Set Control
7324 @subsection Character Set Control
7326 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7327 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7330 Normally GNAT recognizes the Latin-1 character set in source program
7331 identifiers, as described in the Ada Reference Manual.
7333 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7334 single character ^^or word^ indicating the character set, as follows:
7338 ISO 8859-1 (Latin-1) identifiers
7341 ISO 8859-2 (Latin-2) letters allowed in identifiers
7344 ISO 8859-3 (Latin-3) letters allowed in identifiers
7347 ISO 8859-4 (Latin-4) letters allowed in identifiers
7350 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7353 ISO 8859-15 (Latin-9) letters allowed in identifiers
7356 IBM PC letters (code page 437) allowed in identifiers
7359 IBM PC letters (code page 850) allowed in identifiers
7361 @item ^f^FULL_UPPER^
7362 Full upper-half codes allowed in identifiers
7365 No upper-half codes allowed in identifiers
7368 Wide-character codes (that is, codes greater than 255)
7369 allowed in identifiers
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:
7383 Hex encoding (brackets coding also recognized)
7386 Upper half encoding (brackets encoding also recognized)
7389 Shift/JIS encoding (brackets encoding also recognized)
7392 EUC encoding (brackets encoding also recognized)
7395 UTF-8 encoding (brackets encoding also recognized)
7398 Brackets encoding only (default value)
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
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
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}.
7463 @node Subprogram Inlining Control
7464 @subsection Subprogram Inlining Control
7469 @cindex @option{-gnatn} (@command{gcc})
7471 The @code{n} here is intended to suggest the first syllable of the
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}.
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.
7508 @node Auxiliary Output Control
7509 @subsection Auxiliary Output Control
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.
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.
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.
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:
7544 There was an error in at least one source file.
7546 At least one source file did not generate an object file.
7548 The compiler died unexpectedly (internal error for example).
7550 An object file has been generated for every source file.
7555 @node Debugging Control
7556 @subsection Debugging Control
7560 @cindex Debugging options
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}.
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).
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
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).
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.
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.
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.
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.
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.
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.
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.
7795 @node Exception Handling Control
7796 @subsection Exception Handling Control
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
7821 The following switches may be used to control which of the
7822 two exception handling methods is used.
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.
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.
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
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.
7889 /gnat/project1/sources/main.2.ada
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.
7905 @node Integrated Preprocessing
7906 @subsection Integrated Preprocessing
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.
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.
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.
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
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.
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}.
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.
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 '*'.
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.
7977 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7978 be found. Those ^switches^switches^ are:
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}.
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.
8002 Causes a sorted list of symbol names and values to be
8003 listed on the standard output file.
8006 Causes undefined symbols to be treated as having the value @code{FALSE}
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.
8014 Examples of valid lines in a preprocessor data file:
8017 "toto.adb" "prep.def" -u
8018 -- preprocess "toto.adb", using definition file "prep.def",
8019 -- undefined symbol are False.
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.
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}.
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.
8046 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
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^.
8055 @node Code Generation Control
8056 @subsection Code Generation Control
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
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.
8086 @subsection Return Codes
8087 @cindex Return Codes
8088 @cindex @option{/RETURN_CODES=VMS}
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:
8098 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
8099 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
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.
8109 @node Search Paths and the Run-Time Library (RTL)
8110 @section Search Paths and the Run-Time Library (RTL)
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:
8125 The directory containing the source file of the main unit being compiled
8126 (the file name on the command line).
8129 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
8130 @command{gcc} command line, in the order given.
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^.
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
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^.
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).
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).
8160 DEFINE ANOTHER_PATH FOO:[BAG]
8161 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
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.
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.
8178 @ref{Installing a library}
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
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.
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
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:
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
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.
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
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.
8264 The following are some typical Ada compilation command line examples:
8267 @item $ gcc -c xyz.adb
8268 Compile body in file @file{xyz.adb} with all default options.
8271 @item $ gcc -c -O2 -gnata xyz-def.adb
8274 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8277 Compile the child unit package in file @file{xyz-def.adb} with extensive
8278 optimizations, and pragma @code{Assert}/@code{Debug} statements
8281 @item $ gcc -c -gnatc abc-def.adb
8282 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8286 @node Binding Using gnatbind
8287 @chapter Binding Using @code{gnatbind}
8291 * Running gnatbind::
8292 * Switches for gnatbind::
8293 * Command-Line Access::
8294 * Search Paths for gnatbind::
8295 * Examples of gnatbind Usage::
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:
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
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.
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.
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.
8335 @node Running gnatbind
8336 @section Running @code{gnatbind}
8339 The form of the @code{gnatbind} command is
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{]}
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
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
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
8385 Enter @code{gcc -c hello.adb} to compile the main program.
8388 Enter @code{gcc -c p.ads} to compile package @code{P}.
8391 Edit file @file{p.ads}.
8394 Enter @code{gnatbind hello}.
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:
8403 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8404 error: "p.ads" has been modified and must be recompiled
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}
8424 The following switches are available with @code{gnatbind}; details will
8425 be presented in subsequent sections.
8428 * Consistency-Checking Modes::
8429 * Binder Error Message Control::
8430 * Elaboration Control::
8432 * Dynamic Allocation Control::
8433 * Binding with Non-Ada Main Programs::
8434 * Binding Programs with No Main Subprogram::
8441 @cindex @option{--version} @command{gnatbind}
8442 Display Copyright and version, then exit disregarding all other options.
8445 @cindex @option{--help} @command{gnatbind}
8446 If @option{--version} was not used, display usage, then exit disregarding
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
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);
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
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.
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.
8523 See also the packages @code{GNAT.Traceback} and
8524 @code{GNAT.Traceback.Symbolic} for more information.
8526 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8527 @command{gcc} option.
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.
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}.
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^.
8577 (@xref{GNAT and Libraries}, for more details.)
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".
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
8603 Furthermore, under Windows, the sources pointed to by the libraries path
8604 set in the registry are not searched for.
8608 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8612 @cindex @option{-nostdinc} (@command{gnatbind})
8613 Do not look for sources in the system default directory.
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
8639 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8640 Generate binder file suitable for CodePeer.
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
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).
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).
8673 @cindex @option{-static} (@code{gnatbind})
8674 Link against a static GNAT run time.
8677 @cindex @option{-shared} (@code{gnatbind})
8678 Link against a shared GNAT run time when available.
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
8714 @cindex @option{-w} (@code{gnatbind})
8715 Warning mode (@var{x}=s/e for suppress/treat as error)
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
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).
8741 @item /READ_SOURCES=AVAILABLE
8742 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8743 Default mode, in which sources are checked for consistency only if
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})
8758 You may obtain this listing of switches by running @code{gnatbind} with
8762 @node Consistency-Checking Modes
8763 @subsection Consistency-Checking Modes
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
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
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).
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.
8812 @node Binder Error Message Control
8813 @subsection Binder Error Message Control
8816 The following switches provide control over the generation of error
8817 messages from the binder:
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.
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.
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
8848 @item ^-ws^/WARNINGS=SUPPRESS^
8849 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
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.
8858 @item /WARNINGS=NORMAL
8859 Standard mode with warnings generated, but warnings do not get treated
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:
8872 Check that time stamps of a given source unit are consistent
8874 Check that checksums of a given source unit are consistent
8876 Check that consistent versions of @code{GNAT} were used for compilation
8878 Check consistency of configuration pragmas as required
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,
8897 @node Elaboration Control
8898 @subsection Elaboration Control
8901 The following switches provide additional control over the elaboration
8902 order. For full details see @ref{Elaboration Order Handling in GNAT}.
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^}
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.
8928 @node Output Control
8929 @subsection Output Control
8932 The following switches allow additional control over the output
8933 generated by the binder.
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}.
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
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
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.
8990 @node Dynamic Allocation Control
8991 @subsection Dynamic Allocation Control
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.
9002 Allocate memory on 32-bit heap
9005 Allocate memory on 64-bit heap. This is the default
9006 unless explicitly overridden by a @code{'Size} clause on the access type.
9011 See also @ref{Access types and 32/64-bit allocation}.
9015 These switches are only effective on VMS platforms.
9019 @node Binding with Non-Ada Main Programs
9020 @subsection Binding with Non-Ada Main Programs
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:
9033 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
9034 No main program. The main program is not in Ada.
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:
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.
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
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}
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
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:
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
9111 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
9114 @node Command-Line Access
9115 @section Command-Line Access
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
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}
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:
9157 The directory containing the ALI file named in the command line, unless
9158 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
9161 All directories specified by @option{^-I^/SEARCH^}
9162 switches on the @code{gnatbind}
9163 command line, in the order given.
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^.
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
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^.
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
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).
9194 DEFINE ANOTHER_PATH FOO:[BAG]
9195 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
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.
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
9213 @ref{Installing a library}
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.
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
9258 This section contains a number of examples of using the GNAT binding
9259 utility @code{gnatbind}.
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.
9268 @item gnatbind hello -o mainprog.adb
9271 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
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.
9281 @c ------------------------------------
9282 @node Linking Using gnatlink
9283 @chapter Linking Using @command{gnatlink}
9284 @c ------------------------------------
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}).
9300 * Running gnatlink::
9301 * Switches for gnatlink::
9304 @node Running gnatlink
9305 @section Running @command{gnatlink}
9308 The form of the @command{gnatlink} command is
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{]}
9320 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
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}.
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
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
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
9361 Here is an example showing how to generate a linker map:
9364 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9367 Using @var{linker options} it is possible to set the program stack and
9370 See @ref{Setting Stack Size from gnatlink} and
9371 @ref{Setting Heap Size from gnatlink}.
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.
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.
9387 @node Switches for gnatlink
9388 @section Switches for @command{gnatlink}
9391 The following switches are available with the @command{gnatlink} utility:
9397 @cindex @option{--version} @command{gnatlink}
9398 Display Copyright and version, then exit disregarding all other options.
9401 @cindex @option{--help} @command{gnatlink}
9402 If @option{--version} was not used, display usage, then exit disregarding
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
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.
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
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^}.
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.
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.
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".
9474 When linking an executable, create a map file. The name of the map file is
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
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
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
9534 Prefer linking with object libraries over sharable images, even without
9540 @node The GNAT Make Program gnatmake
9541 @chapter The GNAT Make Program @command{gnatmake}
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::
9553 A typical development cycle when working on an Ada program consists of
9554 the following steps:
9558 Edit some sources to fix bugs.
9564 Compile all sources affected.
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
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
9592 @node Running gnatmake
9593 @section Running @command{gnatmake}
9596 The usual form of the @command{gnatmake} command is
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{]}
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
9632 @node Switches for gnatmake
9633 @section Switches for @command{gnatmake}
9636 You may specify any of the following switches to @command{gnatmake}:
9642 @cindex @option{--version} @command{gnatmake}
9643 Display Copyright and version, then exit disregarding all other options.
9646 @cindex @option{--help} @command{gnatmake}
9647 If @option{--version} was not used, display usage, then exit disregarding
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.
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
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.
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
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.
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
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.
9752 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9755 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9758 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
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
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
9814 completed x out of y (zz%)
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.
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.
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.
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.
9876 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9877 Enable debugging. This switch is simply passed to the compiler and to the
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}
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)
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
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
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}.
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
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.
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}.
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.
10076 @item @command{gcc} @asis{switches}
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.)
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.
10090 Source and library search path switches:
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
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}.
10147 Furthermore, under Windows, the sources pointed to by the libraries path
10148 set in the registry are not searched for.
10152 @cindex @option{-nostdinc} (@command{gnatmake})
10153 Do not look for source files in the system default directory.
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
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):
10168 @item <current directory>/$rts_path
10170 @item <default-search-dir>/$rts_path
10172 @item <default-search-dir>/rts-$rts_path
10176 The selected path is handled like a normal RTS path.
10180 @node Mode Switches for gnatmake
10181 @section Mode Switches for @command{gnatmake}
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.
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}.
10218 @node Notes on the Command Line
10219 @section Notes on the Command Line
10222 This section contains some additional useful notes on the operation
10223 of the @command{gnatmake} command.
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.
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
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
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.
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
10267 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10270 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10271 /SKIP_MISSING=@i{[OBJ_DIR]} main
10276 Using @command{gnatmake} along with the
10277 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10278 switch provides a mechanism for avoiding unnecessary recompilations. Using
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.
10291 @node How gnatmake Works
10292 @section How @command{gnatmake} Works
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
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
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
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^}.
10356 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10360 @item gnatmake Main_Unit /QUIET
10361 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10362 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
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.
10371 @c *************************
10372 @node Improving Performance
10373 @chapter Improving Performance
10374 @cindex Improving performance
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.
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::
10392 @c *****************************
10393 @node Performance Considerations
10394 @section Performance Considerations
10397 The GNAT system provides a number of options that allow a trade-off
10402 performance of the generated code
10405 speed of compilation
10408 minimization of dependences and recompilation
10411 the degree of run-time checking.
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:
10424 no inlining of subprogram calls
10427 all run-time checks enabled except overflow and elaboration checks
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.
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::
10446 * Coverage Analysis::
10450 @node Controlling Run-Time Checks
10451 @subsection Controlling Run-Time Checks
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
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
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
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);
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})
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.
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
10556 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10557 @option{-O2}, @option{-O3}, and @option{-Os})
10560 @code{OPTIMIZE} qualifier
10562 to @command{gcc} to control the optimization level:
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^
10585 @itemx /OPTIMIZE=DEVELOPMENT
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.
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
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
10635 Although it is possible to do a reasonable amount of debugging at
10637 nonzero optimization levels,
10638 the higher the level the more likely that
10641 @option{/OPTIMIZE} settings other than @code{NONE},
10642 such settings will make it more likely that
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:
10668 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10670 the PC bouncing back and forth in the code. This may result from any of
10671 the following optimizations:
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.
10680 @i{Invariant code motion:} moving an expression that does not change within a
10681 loop, to the beginning of the loop.
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.
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.
10704 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10705 There are various reasons for this effect:
10709 In a subprogram prologue, a parameter may not yet have been moved to its
10713 A variable may be dead, and its register re-used. This is
10714 probably the most common cause.
10717 As mentioned above, the assignment of a value to a variable may
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
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.
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
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
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.
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.
10757 @node Inlining of Subprograms
10758 @subsection Inlining of Subprograms
10761 A call to a subprogram in the current unit is inlined if all the
10762 following conditions are met:
10766 The optimization level is at least @option{-O1}.
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
10774 @cindex pragma 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.
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:
10790 The optimization level is at least @option{-O1}.
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
10798 The call appears in a body (not in a package spec).
10801 There is a @code{pragma Inline} for the subprogram.
10804 The @option{^-gnatn^/INLINE^} switch is used on the command line.
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
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
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
10915 A : array (1..4, 1..4) of Long_Float;
10916 S : array (1..4) of Long_Float;
10920 for I in A'Range(1) loop
10921 for J in A'Range(2) loop
10922 S (I) := S (I) + A (I, J);
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))
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
10953 @smallexample @c ada
10954 type Array_Type is array (1 .. 4) of Long_Float;
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;
10969 or unconstrained array types:
10971 @smallexample @c ada
10972 type Array_Type is array (Positive range <>) of Long_Float;
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);
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
11015 @cindex Strict Aliasing
11016 @cindex No_Strict_Aliasing
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
11027 type Int1 is new Integer;
11028 type Int2 is new Integer;
11029 type Int1A is access Int1;
11030 type Int2A is access Int2;
11037 for J in Data'Range loop
11038 if Data (J) = Int1V.all then
11039 Int2V.all := Int2V.all + 1;
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
11069 type int1 is new integer;
11070 type int2 is new integer;
11071 type a1 is access int1;
11072 type a2 is access int2;
11077 function to_a2 (Input : a1) return a2;
11080 with Unchecked_Conversion;
11082 function to_a2 (Input : a1) return a2 is
11084 new Unchecked_Conversion (a1, a2);
11086 return to_a2u (Input);
11092 with Text_IO; use Text_IO;
11094 v1 : a1 := new int1;
11095 v2 : a2 := to_a2 (v1);
11099 put_line (int1'image (v1.all));
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
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:
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);"
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
11177 @smallexample @c ada
11178 pragma Warnings (Off);
11180 new Unchecked_Conversion (a1, a2);
11181 pragma Warnings (On);
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);
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.
11243 @node Coverage Analysis
11244 @subsection Coverage Analysis
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.
11253 @node Text_IO Suggestions
11254 @section @code{Text_IO} Suggestions
11255 @cindex @code{Text_IO} and performance
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}
11281 This section describes @command{gnatelim}, a tool which detects unused
11282 subprograms and helps the compiler to create a smaller executable for your
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::
11294 @node About gnatelim
11295 @subsection About @code{gnatelim}
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
11326 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11329 Note that @code{gnatelim} does not need object files.
11331 @node Running gnatelim
11332 @subsection Running @code{gnatelim}
11335 @code{gnatelim} has the following command-line interface:
11338 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
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
11357 @code{gnatelim} has the following switches:
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.
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
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
11399 @cindex @option{^-t^/TIME^} (@command{gnatelim})
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
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.
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
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
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:
11442 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
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
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:
11461 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
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
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.
11485 Create a complete set of @file{ALI} files (if the program has not been
11489 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11493 Generate a list of @code{Eliminate} pragmas in default configuration file
11494 @file{gnat.adc} in the current directory
11497 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11500 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11505 Recompile the application
11508 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
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
11518 This section describes how you can eliminate unused subprograms and data from
11519 your executable just by setting options at compilation time.
11522 * About unused subprogram/data elimination::
11523 * Compilation options::
11524 * Example of unused subprogram/data elimination::
11527 @node About unused subprogram/data elimination
11528 @subsection About unused subprogram/data elimination
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
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
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
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
11581 Here is a simple example:
11583 @smallexample @c ada
11592 Used_Data : Integer;
11593 Unused_Data : Integer;
11595 procedure Used (Data : Integer);
11596 procedure Unused (Data : Integer);
11599 package body Aux is
11600 procedure Used (Data : Integer) is
11605 procedure Unused (Data : Integer) is
11607 Unused_Data := Data;
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.
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
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}
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.
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::
11656 @node Handling Files with Multiple Units
11657 @section Handling Files with Multiple Units
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
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'',
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
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
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}
11750 The @code{gnatchop} command has the form:
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{]}
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
11781 with Text_IO; use Text_IO;
11784 Put_Line ("Hello");
11794 $ gnatchop ^hellofiles^HELLOFILES.^
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
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
11809 For example, given a
11810 file called @file{toto.txt} containing
11812 @smallexample @c ada
11824 $ gnatchop ^toto.txt^TOT.TXT^
11828 will not produce any new file and will result in the following warnings:
11831 toto.txt:1:01: warning: empty file, contains no compilation units
11832 no compilation units found
11833 no source files written
11836 @node Switches for gnatchop
11837 @section Switches for @code{gnatchop}
11840 @command{gnatchop} recognizes the following switches:
11846 @cindex @option{--version} @command{gnatchop}
11847 Display Copyright and version, then exit disregarding all other options.
11850 @cindex @option{--help} @command{gnatchop}
11851 If @option{--version} was not used, display usage, then exit disregarding
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.
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.
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}
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.
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
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},
11889 with DOS-like file systems, is used. If no @option{-k} switch
11891 there is no limit on the length of file names.
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.
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
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
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.
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.
11954 @node Examples of gnatchop Usage
11955 @section Examples of @code{gnatchop} Usage
11959 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11962 @item gnatchop -w hello_s.ada prerelease/files
11965 Chops the source file @file{hello_s.ada}. The output files will be
11966 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
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}^
11978 @command{gnatchop} is used at the other end to reconstitute the original
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.
11992 @node Configuration Pragmas
11993 @chapter Configuration Pragmas
11994 @cindex Configuration pragmas
11995 @cindex Pragmas, configuration
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:
12017 Assume_No_Invalid_Values
12022 Compile_Time_Warning
12024 Component_Alignment
12025 Convention_Identifier
12028 Default_Storage_Pool
12034 External_Name_Casing
12037 Float_Representation
12050 Priority_Specific_Dispatching
12053 Propagate_Exceptions
12056 Restricted_Run_Time
12058 Restrictions_Warnings
12060 Short_Circuit_And_Or
12062 Source_File_Name_Project
12065 Suppress_Exception_Locations
12066 Task_Dispatching_Policy
12072 Wide_Character_Encoding
12077 * Handling of Configuration Pragmas::
12078 * The Configuration Pragmas Files::
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}
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
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
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
12154 Of special interest to GNAT OpenVMS Alpha is the following
12155 configuration pragma:
12157 @smallexample @c ada
12159 pragma Extend_System (Aux_DEC);
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.
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
12174 * Arbitrary File Naming Conventions::
12175 * Running gnatname::
12176 * Switches for gnatname::
12177 * Examples of gnatname Usage::
12180 @node Arbitrary File Naming Conventions
12181 @section Arbitrary File Naming Conventions
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.
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})
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
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
12205 @node Running gnatname
12206 @section Running @code{gnatname}
12209 The usual form of the @code{gnatname} command is
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{]}
12220 All of the arguments are optional. If invoked without any argument,
12221 @code{gnatname} will display its usage.
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
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.
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.
12246 Examples of Naming Patterns are
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).
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
12265 @node Switches for gnatname
12266 @section Switches for @code{gnatname}
12269 Switches for @code{gnatname} must precede any specified Naming Pattern.
12272 You may specify any of the following switches to @code{gnatname}:
12278 @cindex @option{--version} @command{gnatname}
12279 Display Copyright and version, then exit disregarding all other options.
12282 @cindex @option{--help} @command{gnatname}
12283 If @option{--version} was not used, display usage, then exit disregarding
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
12294 There may be zero, one or more space between @option{-c} and
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=^}
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
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.
12339 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
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^}.
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,
12378 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12381 will look for Ada units in all files with the @file{.ada} extension,
12382 except those whose names end with @file{_nt.ada}.
12386 @node Examples of gnatname Usage
12387 @section Examples of @code{gnatname} Usage
12391 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12397 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
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.
12408 Note the optional spaces after @option{-c} and @option{-d}.
12413 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12414 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
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_*"
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}
12445 @macro PROJECTFILE{TXT}
12449 @c simulates a newline when in a @CODESAMPLE
12460 @macro TIPHTML{TXT}
12464 @macro IMPORTANT{TXT}
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}
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
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
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}).
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::
12526 @node Switches for gnatxref
12527 @section @code{gnatxref} Switches
12530 The command invocation for @code{gnatxref} is:
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{]}
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
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.
12558 The switches can be:
12562 @cindex @option{--version} @command{gnatxref}
12563 Display Copyright and version, then exit disregarding all other options.
12566 @cindex @option{--help} @command{gnatxref}
12567 If @option{--version} was not used, display usage, then exit disregarding
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.
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}.
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}.
12591 @cindex @option{-nostdinc} (@command{gnatxref})
12592 Do not look for sources in the system default directory.
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}.
12628 @cindex @option{-IDIR} (@command{gnatxref})
12629 Equivalent to @samp{-aODIR -aIDIR}.
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^}.
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.
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.
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
12670 The command line for @code{gnatfind} is:
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{]}
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.
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.
12703 is a decimal integer identifying the line number containing
12704 the reference to the entity (or entities) to be located.
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
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.
12732 At least one of 'sourcefile' or 'pattern' has to be present on
12735 The following switches are available:
12739 @cindex @option{--version} @command{gnatfind}
12740 Display Copyright and version, then exit disregarding all other options.
12743 @cindex @option{--help} @command{gnatfind}
12744 If @option{--version} was not used, display usage, then exit disregarding
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.
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}.
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}.
12768 @cindex @option{-nostdinc} (@command{gnatfind})
12769 Do not look for sources in the system default directory.
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}.
12811 @cindex @option{-IDIR} (@command{gnatfind})
12812 Equivalent to @samp{-aODIR -aIDIR}.
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.
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}
12861 Project files allow a programmer to specify how to compile its
12862 application, where to find sources, etc. These files are used
12864 primarily by GPS, but they can also be used
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
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
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
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
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.
12919 @item comp_cmd=COMMAND
12920 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12923 @item comp_cmd=COMMAND
12924 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12926 specifies the command used to compile a single file in the application.
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@}"}]
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@}"}]
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
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}
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:
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:
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
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
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
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 ()[].*+?^^^
13021 Following are a few examples:
13025 will match any of the two strings @samp{abcde} and @samp{fghi},
13028 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13029 @samp{abcccd}, and so on,
13032 will match any string which has only lowercase characters in it (and at
13033 least one character.
13038 @node Examples of gnatxref Usage
13039 @section Examples of @code{gnatxref} Usage
13041 @subsection General Usage
13044 For the following examples, we will consider the following units:
13046 @smallexample @c ada
13052 3: procedure Foo (B : in Integer);
13059 1: package body Main is
13060 2: procedure Foo (B : in Integer) is
13071 2: procedure Print (B : Integer);
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:
13097 Decl: main.ads 3:20
13098 Body: main.adb 2:20
13099 Ref: main.adb 4:13 5:13 6:19
13102 Ref: main.adb 6:8 7:8
13112 Decl: main.ads 3:15
13113 Body: main.adb 2:15
13116 Body: main.adb 1:14
13119 Ref: main.adb 6:12 7:12
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
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}.
13145 $ gnatxref -v gnatfind.adb > tags
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.
13157 @node Examples of gnatfind Usage
13158 @section Examples of @code{gnatfind} Usage
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
13167 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13170 The output will look like:
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
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:
13189 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13191 ^directory/^[directory]^main.adb:24:10: xyz <= body
13193 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13198 This can make it easier to find exactly the location your are looking
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.
13223 @c *********************************
13224 @node The GNAT Pretty-Printer gnatpp
13225 @chapter The GNAT Pretty-Printer @command{gnatpp}
13227 @cindex Pretty-Printer
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
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
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{]}
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
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
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
13290 * Switches for gnatpp::
13291 * Formatting Rules::
13294 @node Switches for gnatpp
13295 @section Switches for @command{gnatpp}
13298 The following subsections describe the various switches accepted by
13299 @command{gnatpp}, organized by category.
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
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
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}.
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
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.
13340 * Alignment 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::
13350 @node Alignment Control
13351 @subsection Alignment Control
13352 @cindex Alignment control in @command{gnatpp}
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.
13363 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13367 Set all alignments to ON
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
13391 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13394 @node Casing Control
13395 @subsection Casing Control
13396 @cindex Casing control in @command{gnatpp}
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
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.
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
13456 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13457 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13460 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13461 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
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^.
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
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
13535 @node Construct Layout Control
13536 @subsection Construct Layout Control
13537 @cindex Layout control in @command{gnatpp}
13540 This group of @command{gnatpp} switches controls the layout of comments and
13541 complex syntactic constructs. See @ref{Formatting Comments} for details
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^
13571 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13574 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
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
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
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.
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.
13624 For the @option{/COMMENTS_LAYOUT} qualifier:
13627 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13629 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13630 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13634 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13635 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13638 @node General Text Layout Control
13639 @subsection General Text Layout Control
13642 These switches allow control over line length and indentation.
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.
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)
13663 @node Other Formatting Options
13664 @subsection Other Formatting Options
13667 These switches control the inclusion of missing end/exit labels, and
13668 the indentation level in @b{case} statements.
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
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.
13709 @node Setting the Source Search Path
13710 @subsection Setting the Source Search Path
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.
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
13735 @node Output File Control
13736 @subsection Output File Control
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^}
13745 The output may be redirected by the following switches:
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
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^}
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
13798 @var{e} is one of the following:
13806 Upper half encoding
13808 @item ^s^SHIFT_JIS^
13818 Brackets encoding (default value)
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.
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
13839 The additional @command{gnatpp} switches are defined in this subsection.
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
13850 @item ^-v^/VERBOSE^
13851 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
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})
13859 @command{gnatpp} generates a warning whenever it cannot provide
13860 a required layout in the result source.
13863 @node Formatting Rules
13864 @section Formatting Rules
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.
13872 * White Space and Empty Lines::
13873 * Formatting Comments::
13874 * Construct Layout::
13878 @node White Space and Empty Lines
13879 @subsection White Space and Empty Lines
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,
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
13915 Comments in Ada code are of two kinds:
13918 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13919 ``white space'') on a line
13922 an @emph{end-of-line comment}, which follows some other Ada lexical element
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).
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
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.
13957 @smallexample @c ada
13969 Reference-manual indentation produces:
13971 @smallexample @c ada
13983 while GNAT-style indentation produces:
13985 @smallexample @c ada
13997 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13998 (GNAT style comment beginning) has the following
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.
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.
14018 That is, if in the original source we have:
14020 @smallexample @c ada
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
14031 Then in the formatted source we get
14033 @smallexample @c ada
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
14044 A comment that exceeds the line length limit will be split.
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).
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
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:
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)
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
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:
14099 @multitable @columnfractions .5 .5
14100 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14103 @smallexample @c ada
14110 @smallexample @c ada
14119 @smallexample @c ada
14121 a at 0 range 0 .. 31;
14122 b at 4 range 0 .. 31;
14126 @smallexample @c ada
14129 a at 0 range 0 .. 31;
14130 b at 4 range 0 .. 31;
14135 @smallexample @c ada
14143 @smallexample @c ada
14153 @smallexample @c ada
14154 Clear : for J in 1 .. 10 loop
14159 @smallexample @c ada
14161 for J in 1 .. 10 loop
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;
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;
14186 Block : declare Block :
14187 A : Integer := 3; declare
14188 begin A : Integer := 3;
14190 end Block; Proc (A, A);
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;
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.
14214 @subsection Name Casing
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.
14223 With @option{-nD} (``as declared'', which is the default),
14226 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
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^} ---
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
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
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:
14284 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14286 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
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
14299 the value of a @option{-D@var{file}} switch
14302 an option to the @option{/DICTIONARY} qualifier
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):
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
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
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
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
14333 when @command{gnatpp} checks if the word or subword is in the dictionary,
14334 this check is not case sensitive
14338 For example, suppose we have the following source to reformat:
14340 @smallexample @c ada
14343 name1 : integer := 1;
14344 name4_name3_name2 : integer := 2;
14345 name2_name3_name4 : Boolean;
14348 name2_name3_name4 := name4_name3_name2 > name1;
14354 And suppose we have two dictionaries:
14371 If @command{gnatpp} is called with the following switches:
14375 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14378 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14383 then we will get the following name casing in the @command{gnatpp} output:
14385 @smallexample @c ada
14388 NAME1 : Integer := 1;
14389 Name4_NAME3_Name2 : Integer := 2;
14390 Name2_NAME3_Name4 : Boolean;
14393 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14398 @c *********************************
14399 @node The GNAT Metric Tool gnatmetric
14400 @chapter The GNAT Metric Tool @command{gnatmetric}
14402 @cindex Metric tool
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
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{]}
14440 @var{switches} specify the metrics to compute and define the destination for
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
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.
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
14464 * Switches for gnatmetric::
14467 @node Switches for gnatmetric
14468 @section Switches for @command{gnatmetric}
14471 The following subsections describe the various switches accepted by
14472 @command{gnatmetric}, organized by category.
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::
14482 @node Output Files Control
14483 @subsection Output File Control
14484 @cindex Output file control in @command{gnatmetric}
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
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:
14513 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14515 Generate the XML output
14517 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
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
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.)
14555 @node Disable Metrics For Local Units
14556 @subsection Disable Metrics For Local Units
14557 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14560 @command{gnatmetric} relies on the GNAT compilation model @minus{}
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:
14571 subprogram (and generic subprogram) bodies;
14574 package (and generic package) specs and bodies;
14577 task object and type specifications and bodies;
14580 protected object and type specifications and bodies.
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
14594 Suppression of metrics computation for eligible local units can be
14595 obtained via the following switch:
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
14604 @node Specifying a set of metrics to compute
14605 @subsection Specifying a set of metrics to compute
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.
14617 * Line Metrics Control::
14618 * Syntax Metrics Control::
14619 * Complexity Metrics Control::
14620 * Coupling Metrics Control::
14623 @node Line Metrics Control
14624 @subsubsection Line Metrics Control
14625 @cindex Line metrics control in @command{gnatmetric}
14628 For any (legal) source file, and for each of its
14629 eligible local program units, @command{gnatmetric} computes the following
14634 the total number of lines;
14637 the total number of code lines (i.e., non-blank lines that are not comments)
14640 the number of comment lines
14643 the number of code lines containing end-of-line comments;
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;
14650 the number of empty lines and lines containing only space characters and/or
14651 format effectors (blank lines)
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)
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
14666 You can use the following switches to select the specific line metrics
14667 to be computed and reported.
14670 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14673 @cindex @option{--no-lines@var{x}}
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.
14731 @node Syntax Metrics Control
14732 @subsubsection Syntax Metrics Control
14733 @cindex Syntax metrics control in @command{gnatmetric}
14736 @command{gnatmetric} computes various syntactic metrics for the
14737 outermost unit and for each eligible local unit:
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
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
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})
14773 For the outermost unit in the file, @command{gnatmetric} additionally computes
14774 the following metrics:
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
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
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.
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,
14801 Along with the total number of public types, the following
14802 types are counted and reported separately:
14809 Root tagged types (abstract, non-abstract, private, non-private). Type
14810 extensions are @emph{not} counted
14813 Private types (including private extensions)
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
14829 No distinction is made among different kinds of types (abstract,
14830 private etc.); the total number of types is computed and reported.
14835 By default, all the syntax metrics are computed and reported. You can use the
14836 following switches to select specific syntax metrics.
14840 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14843 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
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
14902 @node Complexity Metrics Control
14903 @subsubsection Complexity Metrics Control
14904 @cindex Complexity metrics control in @command{gnatmetric}
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:
14914 McCabe cyclomatic complexity;
14917 McCabe essential complexity;
14920 maximal loop nesting level;
14923 extra exit points (for subprograms);
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:
14937 the complexity introduced by control
14938 statements only, without taking into account short-circuit forms,
14941 the complexity introduced by short-circuit control forms only, and
14945 cyclomatic complexity, which is the sum of these two values.
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:
14991 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14994 @cindex @option{--no-complexity@var{x}}
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
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
15052 @node Coupling Metrics Control
15053 @subsubsection Coupling Metrics Control
15054 @cindex Coupling metrics control in @command{gnatmetric}
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:
15068 @emph{object-oriented coupling} - for classes in traditional object-oriented
15072 @emph{unit coupling} - for all the program units making up a program;
15075 @emph{control coupling} - this metric counts dependencies between a unit and
15076 only those units that define subprograms;
15080 Two kinds of coupling metrics are computed:
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
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
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
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
15159 function F_1 (I : Integer) return Integer;
15163 type T_2 is new Integer;
15166 package body Lib_1 is
15167 function F_1 (I : Integer) return Integer is
15173 with Lib_2; use Lib_2;
15176 function Fun (I : Integer) return Integer;
15179 with Lib_1; use Lib_1;
15180 package body Pack is
15181 function Fun (I : Integer) return Integer is
15189 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
15190 units, the result will be:
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
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
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:
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})
15254 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
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
15285 @node Other gnatmetric Switches
15286 @subsection Other @code{gnatmetric} Switches
15289 Additional @command{gnatmetric} switches are as follows:
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})
15303 @command{gnatmetric} generates version information and then
15304 a trace of sources being processed.
15307 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
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:
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:
15324 gnat metric -Pproj -U
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:
15333 gnat metric -Pproj -U main
15337 @c ***********************************
15338 @node File Name Krunching Using gnatkr
15339 @chapter File Name Krunching Using @code{gnatkr}
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.
15351 * Krunching Method::
15352 * Examples of gnatkr Usage::
15356 @section About @code{gnatkr}
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:
15364 Take the unit name and replace all dots by hyphens.
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.
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-},^
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.
15393 @section Using @code{gnatkr}
15396 The @code{gnatkr} command has the form
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{]}
15408 $ gnatkr @var{name} /COUNT=nn
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.
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
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:
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.
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.
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
15484 Final file name: oustwifi.adb
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:
15494 replaced by @file{^a^A^-}
15497 replaced by @file{^g^G^-}
15500 replaced by @file{^i^I^-}
15503 replaced by @file{^s^S^-}
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:
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
15527 Final file name: a-stwifi.adb
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
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
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
15554 @node Preprocessing Using gnatprep
15555 @chapter Preprocessing Using @code{gnatprep}
15559 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
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}.
15567 * Preprocessing Symbols::
15569 * Switches for gnatprep::
15570 * Form of Definitions File::
15571 * Form of Input Text for gnatprep::
15574 @node Preprocessing Symbols
15575 @section Preprocessing Symbols
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}
15587 To call @code{gnatprep} use
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{]}
15599 is an optional sequence of switches as described in the next section.
15602 is the full name of the input file, which is an Ada source
15603 file containing preprocessor directives.
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.
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.
15617 @node Switches for gnatprep
15618 @section Switches for @code{gnatprep}
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.
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.
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.
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.
15698 @node Form of Definitions File
15699 @section Form of Definitions File
15702 The definitions file contains lines of the form
15709 where symbol is a preprocessing symbol, and value is one of the following:
15713 Empty, corresponding to a null substitution
15715 A string literal using normal Ada syntax
15717 Any sequence of characters from the set
15718 (letters, digits, period, underline).
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}
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
15738 #if @i{expression} @r{[}then@r{]}
15740 #elsif @i{expression} @r{[}then@r{]}
15742 #elsif @i{expression} @r{[}then@r{]}
15753 In this example, @i{expression} is defined by the following grammar:
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} )
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
15775 This should be one of the following:
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
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}
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
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:
15842 Header : String := "$XYZ";
15846 you should set XYZ to @code{"hello"} and write:
15849 Header : String := $XYZ;
15853 and then the substitution will occur as desired.
15855 @node The GNAT Library Browser gnatls
15856 @chapter The GNAT Library Browser @code{gnatls}
15858 @cindex Library browser
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}).
15871 * Switches for gnatls::
15872 * Examples of gnatls Usage::
15875 @node Running gnatls
15876 @section Running @code{gnatls}
15879 The @code{gnatls} command has the form
15882 $ gnatls switches @var{object_or_ali_file}
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:
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
15911 The first line can be interpreted as follows: the main unit which is
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:
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.
15944 @node Switches for gnatls
15945 @section Switches for @code{gnatls}
15948 @code{gnatls} recognizes the following switches:
15952 @cindex @option{--version} @command{gnatls}
15953 Display Copyright and version, then exit disregarding all other options.
15956 @cindex @option{--help} @command{gnatls}
15957 If @option{--version} was not used, display usage, then exit disregarding
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^
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:
16017 @item Preelaborable
16018 The unit is preelaborable in the Ada sense.
16021 No elaboration code has been produced by the compiler for this unit.
16024 The unit is pure in the Ada sense.
16026 @item Elaborate_Body
16027 The unit contains a pragma Elaborate_Body.
16030 The unit contains a pragma Remote_Types.
16032 @item Shared_Passive
16033 The unit contains a pragma Shared_Passive.
16036 This unit is part of the predefined environment and cannot be modified
16039 @item Remote_Call_Interface
16040 The unit contains a pragma Remote_Call_Interface.
16046 @node Examples of gnatls Usage
16047 @section Example of @code{gnatls} Usage
16051 Example of using the verbose switch. Note how the source and
16052 object paths are affected by the -I switch.
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>
16063 /home/comar/local/adainclude/
16065 Object Search Path:
16066 <Current_Directory>
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/
16077 Kind => subprogram body
16078 Flags => No_Elab_Code
16079 Source => demo1.adb modified
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.
16089 $ gnatls -d demo2.o
16090 ./demo2.o demo2 OK demo2.adb
16096 $ gnatls -d -s -a demo1.o
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
16105 /home/comar/local/adainclude/gnat.ads
16106 /home/comar/local/adainclude/g-io.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
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
16134 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16135 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.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
16151 @node Cleaning Up Using gnatclean
16152 @chapter Cleaning Up Using @code{gnatclean}
16154 @cindex Cleaning tool
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.
16163 * Running gnatclean::
16164 * Switches for gnatclean::
16165 @c * Examples of gnatclean Usage::
16168 @node Running gnatclean
16169 @section Running @code{gnatclean}
16172 The @code{gnatclean} command has the form:
16175 $ gnatclean switches @var{names}
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.
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}
16194 @code{gnatclean} recognizes the following switches:
16198 @cindex @option{--version} @command{gnatclean}
16199 Display Copyright and version, then exit disregarding all other options.
16202 @cindex @option{--help} @command{gnatclean}
16203 If @option{--version} was not used, display usage, then exit disregarding
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
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
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.
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.
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})
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
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.
16296 @c @node Examples of gnatclean Usage
16297 @c @section Examples of @code{gnatclean} Usage
16300 @node GNAT and Libraries
16301 @chapter GNAT and Libraries
16302 @cindex Library, building, installing, using
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
16311 * Introduction to Libraries in GNAT::
16312 * General Ada Libraries::
16313 * Stand-alone Ada Libraries::
16314 * Rebuilding the GNAT Run-Time Library::
16317 @node Introduction to Libraries in GNAT
16318 @section Introduction to Libraries in GNAT
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:
16341 @xref{The Ada Library Information Files}.
16343 Object files, an archive or a shared library.
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)
16363 @node General Ada Libraries
16364 @section General Ada Libraries
16367 * Building a library::
16368 * Installing a library::
16369 * Using a library::
16372 @node Building a library
16373 @subsection Building a library
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:
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
16395 These attributes specify additional low-level options to be used during
16396 library generation, and redefine the actual application used to generate
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
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";
16419 and the compilation command to build and install the library:
16421 @smallexample @c ada
16422 $ gnatmake -Pmy_lib
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
16444 with My_Lib.Service1;
16445 with My_Lib.Service2;
16446 with My_Lib.Service3;
16447 procedure My_Lib_Dummy is
16455 Here are the generic commands that will build an archive or a shared library.
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
16475 # Make the ALI files read-only so that gnatmake will not try to
16476 # regenerate the objects that are in the library
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}
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:
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
16515 The files @file{ada_source_path} and @file{ada_object_path} might not be
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
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
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
16547 @smallexample @c projectfile
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
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";
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.
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:
16587 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16592 This can be expressed more simply:
16597 when the following conditions are met:
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}
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}
16608 a pragma @code{Linker_Options} has been added to one of the sources.
16611 @smallexample @c ada
16612 pragma Linker_Options ("-lmy_lib");
16616 @node Stand-alone Ada Libraries
16617 @section Stand-alone Ada Libraries
16618 @cindex Stand-alone library, building, using
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::
16627 @node Introduction to Stand-alone Libraries
16628 @subsection Introduction to Stand-alone Libraries
16631 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
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}
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,
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
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
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
16674 for Library_Dir use "lib_dir";
16675 for Library_Name use "dummy";
16676 for Library_Interface use ("int1", "int1.child");
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}
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
16697 with the project-level attribute @code{Library_Auto_Init} set to
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.
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
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";
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:
16746 Compile all library sources.
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:
16754 gnatbind -n int1.ali int2.ali -Lsal1
16758 Compile the binder generated file:
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.
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
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
16786 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
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");
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)
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);
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.
16836 #include "mylib_interface.h"
16841 /* First, elaborate the library before using it */
16844 /* Main program, using the library exported entities */
16846 do_something_else ();
16848 /* Library finalization at the end of the program */
16855 Note that invoking any library finalization procedure generated by
16856 @code{gnatbind} shuts down the Ada run-time environment.
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
16866 The pragmas listed below should be used with caution inside libraries,
16867 as they can create incompatibilities with other Ada libraries:
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}
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
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:
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
16921 @node Using the GNU make Utility
16922 @chapter Using the GNU @code{make} Utility
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
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::
16943 @node Using gnatmake in a Makefile
16944 @section Using gnatmake in a Makefile
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.
16968 @font@heightrm=cmr8
16971 ## This Makefile is intended to be used with the following directory
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)
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
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.
16995 # Name of the main program (no extension)
16998 # If we need to build objects with -fPIC, uncomment the following line
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.
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%@}
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
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
17037 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17040 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17041 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17042 $@{RM@} $@{CSC_LIST:%=%/*.o@}
17043 $@{RM@} *.o *.ali $@{MAIN@}
17046 @node Automatically Creating a List of Directories
17047 @section Automatically Creating a List of Directories
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
17056 However, in larger projects, which might involve hundreds of
17057 subdirectories, it might be more convenient to generate this list
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
17075 @font@heightrm=cmr8
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
17083 # -> b -> ba -> baa
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
17093 # First method: specify explicitly the list of directories
17094 # This allows you to specify any subset of all the directories you need.
17097 DIRS := a/aa/ a/ab/ b/ba/
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/
17110 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17111 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
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
17120 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17124 @node Generating the Command Line Switches
17125 @section Generating the Command Line Switches
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
17137 # see "Automatically creating a list of directories" to create
17142 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17143 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17146 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17149 @node Overcoming Command Line Length Limits
17150 @section Overcoming Command Line Length Limits
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
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.
17180 @font@heightrm=cmr8
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
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
17212 @node Memory Management Issues
17213 @chapter Memory Management Issues
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'').
17220 It also describes the @command{gnatmem} tool, which can be used to track down
17225 * Some Useful Memory Pools::
17226 * The GNAT Debug Pool Facility::
17228 * The gnatmem Tool::
17232 @node Some Useful Memory Pools
17233 @section Some Useful Memory Pools
17234 @findex Memory Pool
17235 @cindex storage, pool
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;
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;
17275 for I in 1 .. 50 loop
17280 for I in 1 .. 100 loop
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;
17300 @node The GNAT Debug Pool Facility
17301 @section The GNAT Debug Pool Facility
17303 @cindex storage, pool, memory corruption
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;
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:
17335 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17337 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17339 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17341 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
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
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);
17381 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17391 Put_Line (Integer'Image(B.all));
17393 when E : others => Put_Line ("raised: " & Exception_Name (E));
17398 when E : others => Put_Line ("raised: " & Exception_Name (E));
17402 Put_Line (Integer'Image(B.all));
17404 when E : others => Put_Line ("raised: " & Exception_Name (E));
17409 when E : others => Put_Line ("raised: " & Exception_Name (E));
17412 end Debug_Pool_Test;
17416 The debug pool mechanism provides the following precise diagnostics on the
17417 execution of this erroneous program:
17420 Total allocated bytes : 0
17421 Total deallocated bytes : 0
17422 Current Water Mark: 0
17426 Total allocated bytes : 8
17427 Total deallocated bytes : 0
17428 Current 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
17436 Total allocated bytes : 8
17437 Total deallocated bytes : 4
17438 Current Water Mark: 4
17443 @node The gnatmem Tool
17444 @section The @command{gnatmem} Tool
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:
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.
17461 Backtraces for all incorrect deallocations, that is to say deallocations
17462 which do not correspond to a valid allocation.
17465 Information on each allocation that is potentially the origin of a memory
17470 * Running gnatmem::
17471 * Switches for gnatmem::
17472 * Example of gnatmem Usage::
17475 @node Running gnatmem
17476 @subsection Running @code{gnatmem}
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).
17487 The @code{gnatmem} command has the form
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}
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}:
17503 $ gnatmake -g my_program -largs -lgmem
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^}.
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:
17530 $ gnatmem my_program
17534 This will produce the output with the following format:
17536 *************** debut cc
17538 $ gnatmem my_program
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
17556 my_program.adb:23 my_program.alloc
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.
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}
17579 @code{gnatmem} recognizes the following switches:
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.
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.
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.
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.
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}.
17622 @node Example of gnatmem Usage
17623 @subsection Example of @code{gnatmem} Usage
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
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);
17641 procedure My_Alloc is
17646 procedure My_DeAlloc is
17654 for I in 1 .. 5 loop
17655 for J in I .. 5 loop
17666 The program needs to be compiled with debugging option and linked with
17667 @code{gmem} library:
17670 $ gnatmake -g test_gm -largs -lgmem
17674 Then we execute the program as usual:
17681 Then @code{gnatmem} is invoked simply with
17687 which produces the following output (result may vary on different platforms):
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
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
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
17719 s-secsta.adb:181 system.secondary_stack.ss_init
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:
17736 $ gnatmem 3 test_gm
17740 which will give the following output:
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
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
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
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
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
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.
17797 @node Stack Related Facilities
17798 @chapter Stack Related Facilities
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.
17806 * Stack Overflow Checking::
17807 * Static Stack Usage Analysis::
17808 * Dynamic Stack Usage Analysis::
17811 @node Stack Overflow Checking
17812 @section Stack Overflow Checking
17813 @cindex Stack Overflow Checking
17814 @cindex -fstack-check
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
17829 To activate stack checking, compile all units with the gcc option
17830 @option{-fstack-check}. For example:
17833 gcc -c -fstack-check package1.adb
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.
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
17859 SET GNAT_STACK_LIMIT 1600
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.
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
17877 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
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.
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}
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:
17897 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17901 @node Static Stack Usage Analysis
17902 @section Static Stack Usage Analysis
17903 @cindex Static Stack Usage Analysis
17904 @cindex -fstack-usage
17907 A unit compiled with @option{-fstack-usage} will generate an extra file
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:
17916 The name of the function.
17920 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17923 The second field corresponds to the size of the known part of the function
17926 The qualifier @code{static} means that the function frame size
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
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
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
17947 It is possible to measure the maximum amount of stack used by a task, by
17948 adding a switch to @command{gnatbind}, as:
17951 $ gnatbind -u0 file
17955 With this option, at each task termination, its stack usage is output on
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:
17963 $ gnatbind -u100 file
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
17972 Index | Task Name | Stack Size | Stack Usage
17979 is a number associated with each task.
17982 is the name of the task analyzed.
17985 is the maximum size for the stack.
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.
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.
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 *********************************
18004 @c *********************************
18005 @node Verifying Properties Using gnatcheck
18006 @chapter Verifying Properties Using @command{gnatcheck}
18008 @cindex @command{gnatcheck}
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.
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}
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).
18051 * Running gnatstub::
18052 * Switches for gnatstub::
18055 @node Running gnatstub
18056 @section Running @command{gnatstub}
18059 @command{gnatstub} has a command-line interface of the form:
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{]}
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
18074 The file name does not have to follow the GNAT file name conventions. If the
18076 does not follow GNAT file naming conventions, the name of the body file must
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,
18083 of the body file from the argument file name by replacing the @file{.ads}
18085 with the @file{.adb} suffix.
18088 indicates the directory in which the body stub is to be placed (the default
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
18101 is an optional sequence of switches as described in the next section
18104 @node Switches for gnatstub
18105 @section Switches for @command{gnatstub}
18111 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18112 If the destination directory already contains a file with the name of the
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.
18132 @cindex @option{-IDIR} (@command{gnatstub})
18134 @cindex @option{-I-} (@command{gnatstub})
18137 @item /NOCURRENT_DIRECTORY
18138 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18140 ^These switches have ^This switch has^ the same meaning as in calls to
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
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
18199 the GNAT file naming
18200 conventions. If this switch is omitted the default name for the body will be
18202 from the argument file name according to the GNAT file naming conventions.
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
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,
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.
18235 @c *********************************
18236 @node Creating Unit Tests Using gnattest
18237 @chapter Creating Unit Tests Using @command{gnattest}
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.
18260 * Running gnattest::
18261 * Switches for gnattest::
18262 * Project Attributes for gnattest::
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::
18273 * Support for other platforms/run-times::
18275 * Current Limitations::
18278 @node Running gnattest
18279 @section Running @command{gnattest}
18282 @command{gnattest} has a command-line interface of the form
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{]}
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.
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
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.
18314 is an optional sequence of switches as described in the next section.
18318 @command{gnattest} results can be found in two different places.
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:
18331 gnatmake -P<harness-dir>/test_driver
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
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.
18352 @node Switches for gnattest
18353 @section Switches for @command{gnattest}
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.
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}.
18377 @cindex @option{-q} (@command{gnattest})
18378 Suppresses noncritical output messages.
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.
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}
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
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}
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:
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.
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.
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.
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".
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
18492 Let's take a very simple example using the first @command{gnattest} example
18496 <install_prefix>/share/examples/gnattest/simple
18499 This project contains a simple package containing one subprogram. By running gnattest:
18502 $ gnattest --harness-dir=driver -Psimple.gpr
18505 a test driver is created in directory "driver". It can be compiled and run:
18509 $ gprbuild -Ptest_driver
18513 One failed test with diagnosis "test not implemented" is reported.
18514 Since no special output option was specified, the test package Simple.Tests
18518 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
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");
18540 After recompiling and running the test driver, one successfully passed test
18543 @node Setting Up and Tearing Down the Testing Environment
18544 @section Setting Up and Tearing Down the Testing Environment
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
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:
18573 gnattest --harness-dir=driver -Psimple.gpr
18575 gprbuild -Ptest_driver
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
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
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:
18605 test_runner --skeleton-default=pass
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
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):
18626 cd <install_prefix>/share/examples/gnattest/tagged_rec
18627 gnattest --harness-dir=driver -Ptagged_rec.gpr
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:
18634 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
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
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
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.
18671 gprbuild -Ptest_driver
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
18679 @node Tagged Types Substitutability Testing
18680 @section Tagged Types Substitutability Testing
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
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
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:
18711 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
18713 gprbuild -Ptest_driver
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
18724 @node Testing with Contracts
18725 @section Testing with Contracts
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:
18740 cd <install_prefix>/share/examples/gnattest/contracts
18741 gnattest --harness-dir=driver -Pcontracts.gpr
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
18748 @smallexample @c ada
18749 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
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");
18762 gprbuild -Ptest_driver
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
18772 @node Additional Tests
18773 @section Additional Tests
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
18788 <install_prefix>/share/examples/gnattest/additional_tests/
18791 To create a test driver for already-written tests, use the --harness-only
18795 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18797 gnatmake -Pharness_only/test_driver.gpr
18798 harness_only/test_runner
18801 Additional tests can also be executed together with generated tests:
18804 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18805 --harness-dir=mixing
18806 gnatmake -Pmixing/test_driver.gpr
18811 @node Support for other platforms/run-times
18812 @section Support for other platforms/run-times
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:
18829 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
18833 @node Current Limitations
18834 @section Current Limitations
18838 The tool currently does not support following features:
18841 @item generic tests for generic packages and package instantiations
18842 @item tests for protected subprograms and entries
18846 @c *********************************
18847 @node Performing Dimensionality Analysis in GNAT
18848 @chapter Performing Dimensionality Analysis in GNAT
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
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'));
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
18891 Dimension => (Symbol => 'm',
18896 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
18897 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
18900 The package also defines conventional names for values of each unit, for
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;
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;
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);
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;
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);
18955 Execution of this program yields:
18957 Gravitational constant: 9.81 m/sec^^^2
18958 distance travelled in 10 seconds of free fall 490.50 m
18962 However, incorrect assignments such as:
18964 @smallexample @c ada
18966 Distance := 5.0 * kg:
18970 are rejected with the following diagnoses:
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]
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);
18995 then the output includes:
18997 Final velocity: 98.10 m.s**(-1)
19000 @c *********************************
19001 @node Generating Ada Bindings for C and C++ headers
19002 @chapter Generating Ada Bindings for C and C++ headers
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:
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}).
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.
19030 * Running the binding generator::
19031 * Generating bindings for C++ headers::
19035 @node Running the binding generator
19036 @section Running the binding generator
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:
19045 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19046 $ gcc -c -gnat05 *.ads
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:
19077 extern void foo (int variable);
19080 with the C front-end, @code{variable} is ignored, and the above is handled as:
19083 extern void foo (int);
19086 generating a generic:
19089 procedure foo (param1 : int);
19092 with the C++ front-end, the name is available, and we generate:
19095 procedure foo (variable : int);
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:
19103 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
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}:
19119 #include <readline/readline.h>
19122 and then generate Ada bindings from this file:
19125 $ g++ -c -fdump-ada-spec readline1.h
19128 @node Generating bindings for C++ headers
19129 @section Generating bindings for C++ headers
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:
19148 virtual int Number_Of_Teeth () = 0;
19153 virtual void Set_Owner (char* Name) = 0;
19159 virtual void Set_Age (int New_Age);
19162 class Dog : Animal, Carnivore, Domestic @{
19167 virtual int Number_Of_Teeth ();
19168 virtual void Set_Owner (char* Name);
19176 The corresponding Ada code is generated:
19178 @smallexample @c ada
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;
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;
19197 use Class_Domestic;
19199 package Class_Animal is
19200 type Animal is tagged limited record
19201 Age_Count : aliased int;
19203 pragma Import (CPP, Animal);
19205 procedure Set_Age (this : access Animal; New_Age : int);
19206 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
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;
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");
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
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.
19253 @cindex @option{-C} (@command{gcc})
19254 Extract comments from headers and generate Ada comments in the Ada spec files.
19257 @node Other Utility Programs
19258 @chapter Other Utility Programs
19261 This chapter discusses some other utility programs available in the Ada
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::
19275 @node Using Other Utility Programs with GNAT
19276 @section Using Other Utility Programs with GNAT
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.
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
19291 @node The External Symbol Naming Scheme of GNAT
19292 @section The External Symbol Naming Scheme of GNAT
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
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
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}.
19319 Of course if a @code{pragma Export} is used this may be overridden:
19321 @smallexample @c ada
19326 pragma Export (Var1, C, External_Name => "var1_name");
19328 pragma Export (Var2, C, Link_Name => "var2_link_name");
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
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
19354 procedure Hello (S : String);
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}
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:
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}
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:
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.
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.
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}.
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
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.
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.
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
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
19468 @node Installing gnathtml
19469 @section Installing @code{gnathtml}
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:
19480 #!full_path_name_to_perl
19484 Alternatively, you may run the script using the following command line:
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}
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.
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.
19512 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19513 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19514 $ RUN/DEBUG <PROGRAM_NAME>
19520 @c ******************************
19521 @node Code Coverage and Profiling
19522 @chapter Code Coverage and Profiling
19523 @cindex Code Coverage
19527 This chapter describes how to use @code{gcov} - coverage testing tool - and
19528 @code{gprof} - profiler tool - on your Ada programs.
19531 * Code Coverage of Ada Programs using gcov::
19532 * Profiling an Ada Program using gprof::
19535 @node Code Coverage of Ada Programs using gcov
19536 @section Code Coverage of Ada Programs using gcov
19538 @cindex -fprofile-arcs
19539 @cindex -ftest-coverage
19541 @cindex Code Coverage
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
19552 This chapter provides a quick startup guide, and
19553 details some Gnat-specific features.
19556 * Quick startup guide::
19560 @node Quick startup guide
19561 @subsection Quick startup guide
19563 In order to perform coverage analysis of a program using @code{gcov}, 3
19568 Code instrumentation during the compilation process
19570 Execution of the instrumented program
19572 Execution of the @code{gcov} tool to generate the result.
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
19580 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19581 @code{-fprofile-arcs}.
19584 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19585 -largs -fprofile-arcs
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
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
19644 solaris sparc/sparc64/x86
19650 In order to profile a program using @code{gprof}, 3 steps are needed:
19654 Code instrumentation, requiring a full recompilation of the project with the
19657 Execution of the program under the analysis conditions, i.e. with the desired
19660 Analysis of the results using the @code{gprof} tool.
19664 The following sections detail the different steps, and indicate how
19665 to interpret the results:
19667 * Compilation for profiling::
19668 * Program execution::
19670 * Interpretation of profiling results::
19673 @node Compilation for profiling
19674 @subsection Compilation for 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:
19685 gnatmake -f -pg -P my_project
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
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
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
19711 The @code{gprof} tool is called as follow:
19714 gprof my_prog gmon.out
19725 The complete form of the gprof command line is the following:
19728 gprof [^switches^options^] [executable [data-file]]
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:
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}
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}
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.
19788 @node Interpretation of profiling results
19789 @subsection Interpretation of profiling results
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.
19806 @c ******************************
19807 @node Running and Debugging Ada Programs
19808 @chapter Running and Debugging Ada Programs
19812 This chapter discusses how to debug Ada programs.
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.
19819 An incorrect Ada program may be handled in three ways by the GNAT compiler:
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
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.
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.
19840 * The GNAT Debugger GDB::
19842 * Introduction to GDB Commands::
19843 * Using Ada Expressions::
19844 * Calling User-Defined Subprograms::
19845 * Using the Next Command in a Function::
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::
19859 @node The GNAT Debugger GDB
19860 @section The GNAT Debugger GDB
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},
19871 located in the GNU:[DOCS] directory,
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.
19920 @section Running GDB
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
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.
19935 The command to run @code{GDB} is
19938 $ ^gdb program^GDB PROGRAM^
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
19953 @code{GDB} contains a large repertoire of commands. @xref{Top,,
19954 Debugging with GDB, gdb, Debugging with GDB},
19956 located in the GNU:[DOCS] directory,
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
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.
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
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.
20006 Continues execution following a breakpoint, until the next breakpoint or the
20007 termination of the program.
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.
20015 Executes a single line. If this line is a subprogram call, executes and
20016 returns from the call.
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.
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.
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.
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.
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
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
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}).
20072 That type safety and strict adherence to Ada language restrictions
20073 are not particularly important to the @code{GDB} user.
20076 That brevity is important to the @code{GDB} user.
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
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:
20098 call subprogram-name (parameters)
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
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
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
20164 You can set catchpoints that stop the program execution when your program
20165 raises selected exceptions.
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}.
20192 @code{GDB} allows the following task-related commands:
20196 This command shows a list of current Ada tasks, as in the following example:
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
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
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
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
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
20268 generic package k is
20269 procedure kp (v1 : in out integer);
20273 procedure kp (v1 : in out integer) is
20279 package k1 is new k;
20280 package k2 is new k;
20282 var : integer := 1;
20295 Then to break on a call to procedure kp in the k2 instance, simply
20299 (gdb) break g.k2.kp
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
20307 @node Remote Debugging using gdbserver
20308 @section Remote Debugging using gdbserver
20309 @cindex Remote Debugging using gdbserver
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.
20325 $ gdbserver localhost:4444 program
20326 Process program created; pid = 5685
20327 Listening on port 4444
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.
20337 (gdb) target remote targethost:4444
20338 Remote debugging using targethost:4444
20339 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
20341 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
20345 Breakpoint 1, foo () at foo.adb:4
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
20362 When presented with programs that contain serious errors in syntax
20364 GNAT may on rare occasions experience problems in operation, such
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.
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.
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.
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.
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
20413 @node Naming Conventions for GNAT Source Files
20414 @section Naming Conventions for GNAT Source Files
20417 In order to examine the workings of the GNAT system, the following
20418 brief description of its organization may be helpful:
20422 Files with prefix @file{^sc^SC^} contain the lexical scanner.
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}.
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.
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}.
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.
20450 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20451 data structures used by the front-end.
20454 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20455 the abstract syntax tree as produced by the parser.
20458 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20459 all entities, computed during semantic analysis.
20462 Library management issues are dealt with in files with prefix
20468 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20469 defined in Annex A.
20474 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20475 defined in Annex B.
20479 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20480 both language-defined children and GNAT run-time routines.
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.
20489 @node Getting Internal Debugging Information
20490 @section Getting Internal Debugging Information
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
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
20513 @cindex stack traceback
20514 @cindex stack unwinding
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.
20533 * Non-Symbolic Traceback::
20534 * Symbolic Traceback::
20537 @node Non-Symbolic Traceback
20538 @subsection Non-Symbolic Traceback
20539 @cindex traceback, non-symbolic
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
20547 * Tracebacks From an Unhandled Exception::
20548 * Tracebacks From Exception Occurrences (non-symbolic)::
20549 * Tracebacks From Anywhere in a Program (non-symbolic)::
20552 @node Tracebacks From an Unhandled Exception
20553 @subsubsection Tracebacks From an Unhandled Exception
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
20570 raise Constraint_Error;
20585 $ gnatmake stb -bargs -E
20588 Execution terminated by unhandled exception
20589 Exception name: CONSTRAINT_ERROR
20591 Call stack traceback locations:
20592 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
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.
20604 $ gnatmake -g stb -bargs -E
20607 Execution terminated by unhandled exception
20608 Exception name: CONSTRAINT_ERROR
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
20626 The @code{addr2line} tool has several other useful options:
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}.
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
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:
20665 Furthermore, this feature is not implemented inside Windows DLL. Only
20666 the non-symbolic traceback is reported in this case.
20669 (gdb) break *0x401373
20670 Breakpoint 1 at 0x401373: file stb.adb, line 5.
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
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
20692 with Ada.Exceptions;
20697 use Ada.Exceptions;
20705 Text_IO.Put_Line (Exception_Information (E));
20719 This program will output:
20724 Exception name: CONSTRAINT_ERROR
20725 Message: stb.adb:12
20726 Call stack traceback locations:
20727 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20730 @node Tracebacks From Anywhere in a Program (non-symbolic)
20731 @subsubsection Tracebacks From Anywhere in a Program
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.
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
20749 with GNAT.Traceback;
20750 with GNAT.Debug_Utilities;
20756 use GNAT.Traceback;
20759 TB : Tracebacks_Array (1 .. 10);
20760 -- We are asking for a maximum of 10 stack frames.
20762 -- Len will receive the actual number of stack frames returned.
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)));
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#
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
20804 A symbolic traceback is a stack traceback in which procedure names are
20805 associated with each code location.
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.
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.
20818 * Tracebacks From Exception Occurrences (symbolic)::
20819 * Tracebacks From Anywhere in a Program (symbolic)::
20822 @node Tracebacks From Exception Occurrences (symbolic)
20823 @subsubsection Tracebacks From Exception Occurrences
20825 @smallexample @c ada
20827 with GNAT.Traceback.Symbolic;
20833 raise Constraint_Error;
20850 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20855 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
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
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
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
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
20890 with GNAT.Traceback;
20891 with GNAT.Traceback.Symbolic;
20896 use GNAT.Traceback;
20897 use GNAT.Traceback.Symbolic;
20900 TB : Tracebacks_Array (1 .. 10);
20901 -- We are asking for a maximum of 10 stack frames.
20903 -- Len will receive the actual number of stack frames returned.
20905 Call_Chain (TB, Len);
20906 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20919 @c ******************************
20921 @node Compatibility with HP Ada
20922 @chapter Compatibility with HP Ada
20923 @cindex Compatibility
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.
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::
20970 * Main Program Definition::
20971 * Implementation-Defined Attributes::
20972 * Compiler and Run-Time Interfacing::
20973 * Program Compilation and Library Management::
20975 * Implementation Limits::
20976 * Tools and Utilities::
20979 @node Ada Language Compatibility
20980 @section Ada Language Compatibility
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}
21005 An Ada compiler is allowed to add
21006 implementation-dependent declarations to package @code{System}.
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
21012 However, HP Ada adds an extensive set of declarations to package
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
21023 pragma Extend_System (Aux_DEC);
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
21049 with System.Aux_DEC;
21050 use System.Aux_DEC;
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}
21064 @node Language-Related Features
21065 @section Language-Related Features
21068 The following sections highlight differences in types,
21069 representations of types, operations, alignment, and
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::
21082 @node Integer Types and Representations
21083 @subsection Integer Types and Representations
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.
21091 HP Ada for OpenVMS Alpha systems has defined the
21092 following additional integer types in package @code{System}:
21109 @code{LARGEST_INTEGER}
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
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
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
21133 For example, the declarations:
21135 @smallexample @c ada
21137 type F_Float is digits 6;
21138 pragma Float_Representation (VAX_Float, F_Float);
21143 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21145 This set of declarations actually appears in @code{System.Aux_DEC},
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}
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
21166 pragma Float_Representation(VAX_Float | IEEE_Float);
21171 This pragma controls the representation of floating-point
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.
21184 @code{IEEE_Float} specifies that floating-point
21185 types are represented by default with the IEEE single and
21186 double floating-point types.
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},
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.
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
21222 pragma Long_Float (D_FLOAT | G_FLOAT);
21226 @node Fixed-Point Types and Representations
21227 @subsection Fixed-Point Types and Representations
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
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
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
21287 @smallexample @c ada
21289 X, Y : Integer := Init_Func;
21290 Q : String (X .. Y) := "abc";
21292 for Q'Address use Compute_Address;
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
21303 X, Y : Integer := Init_Func;
21304 Q_Address : constant Address := Compute_Address;
21305 Q : String (X .. Y) := "abc";
21307 for Q'Address use Q_Address;
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
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}
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}
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
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}
21372 By default, GNAT supplies a version of @code{SYSTEM} that matches
21373 the definition given in the @cite{Ada Reference Manual}.
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
21381 type Name is (SYSTEM_NAME_GNAT);
21382 System_Name : constant Name := SYSTEM_NAME_GNAT;
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
21397 pragma Extend_System (Aux_DEC);
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);
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
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.
21439 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
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#);
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,
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
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);
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
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.
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::
21495 * External Interrupts::
21498 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21499 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
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
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
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
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:
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}.
21571 @node Scheduling and Task Priority
21572 @subsection Scheduling and Task Priority
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
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
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
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
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
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}
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}
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
21708 GNAT also supplies a number of implementation-defined pragmas including the
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}
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}
21772 For full details on these and other GNAT implementation-defined pragmas,
21773 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21777 * Restrictions on the Pragma INLINE::
21778 * Restrictions on the Pragma INTERFACE::
21779 * Restrictions on the Pragma SYSTEM_NAME::
21782 @node Restrictions on the Pragma INLINE
21783 @subsection Restrictions on Pragma @code{INLINE}
21786 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
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:
21795 @item Subprogram body or stub (imported subprogram is allowed)
21799 @item Generic declarations
21801 @item Instantiations
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
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}
21828 The following restrictions on pragma @code{INTERFACE}
21829 are enforced by both HP Ada and GNAT:
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.
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.
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}
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
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
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
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).
21886 * Changes to DECLIB::
21889 @node Changes to DECLIB
21890 @subsection Changes to @code{DECLIB}
21893 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21894 compatibility are minor and include the following:
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.
21915 None of the above changes is visible to users.
21921 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
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
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)
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
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.
21983 * Shared Libraries and Options Files::
21984 * Interfaces to C::
21987 @node Shared Libraries and Options Files
21988 @subsection Shared Libraries and Options Files
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
22008 provides the following Ada types and operations:
22011 @item C types package (@code{C_TYPES})
22013 @item C strings (@code{C_TYPES.NULL_TERMINATED})
22015 @item Other_types (@code{SHORT_INT})
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
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:
22039 @item Procedure with no formal parameters (returns @code{0} upon
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.
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:
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
22068 @node Implementation-Defined Attributes
22069 @section Implementation-Defined Attributes
22072 GNAT provides all HP Ada implementation-defined
22075 @node Compiler and Run-Time Interfacing
22076 @section Compiler and Run-Time Interfacing
22079 HP Ada provides the following qualifiers to pass options to the linker
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}
22094 To pass options to the linker, GNAT provides the following
22098 @item @option{/EXECUTABLE=@var{exec-name}}
22100 @item @option{/VERBOSE}
22102 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
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
22112 @item @code{OPTIMIZE}
22114 @item @code{INLINE}
22116 @item @code{INLINE_GENERIC}
22118 @item @code{SUPPRESS_ALL}
22120 @item @code{PASSIVE}
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
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
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
22152 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
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
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}
22184 Copies a foreign object file into the program library as a
22187 @item @command{ACS COPY UNIT}
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}
22201 Deletes a program library and its contents.
22203 @item @command{ACS DELETE SUBLIBRARY}
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
22217 @item @command{ACS ENTER FOREIGN}
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}
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}
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}
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}
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}
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
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
22304 @item @command{ACS SPAWN}
22305 @tab [No equivalent]@*
22306 Creates a subprocess of the current process (same as @command{DCL SPAWN}
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
22319 @section Input-Output
22322 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22323 Management Services (RMS) to perform operations on
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)}
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:
22359 @item RMS file organizations and access methods
22361 @item OpenVMS file specifications and directories
22363 @item OpenVMS File Definition Language (FDL)
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:
22375 @item @code{TEXT_IO}
22377 @item @code{SEQUENTIAL_IO}
22379 @item @code{DIRECT_IO}
22383 The use of the standard child package syntax (for
22384 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
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:
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
22420 @node Implementation Limits
22421 @section Implementation Limits
22424 The following table lists implementation limits for HP Ada
22426 @multitable @columnfractions .60 .20 .20
22428 @item @emph{Compilation Parameter}
22433 @item In a subprogram or entry declaration, maximum number of
22434 formal parameters that are of an unconstrained record type
22439 @item Maximum identifier length (number of characters)
22444 @item Maximum number of characters in a source line
22449 @item Maximum collection size (number of bytes)
22454 @item Maximum number of discriminants for a record type
22459 @item Maximum number of formal parameters in an entry or
22460 subprogram declaration
22465 @item Maximum number of dimensions in an array type
22470 @item Maximum number of library units and subunits in a compilation.
22475 @item Maximum number of library units and subunits in an execution.
22480 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22481 or @code{PSECT_OBJECT}
22486 @item Maximum number of enumeration literals in an enumeration type
22492 @item Maximum number of lines in a source file
22497 @item Maximum number of bits in any object
22502 @item Maximum size of the static portion of a stack frame (approximate)
22507 @node Tools and Utilities
22508 @section Tools and Utilities
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.
22518 @c Specify table in TeX since Texinfo does a poor job
22522 \settabs\+Language-Sensitive Editor\quad
22523 &Product with HP Ada\quad
22526 &\it Product with HP Ada
22527 & \it Product with @value{EDITION}\cr
22529 \+Code Management System
22533 \+Language-Sensitive Editor
22535 & emacs or HP LSE (Alpha)\cr
22545 & OpenVMS Debug (I64)\cr
22547 \+Source Code Analyzer /
22564 \+Coverage Analyzer
22568 \+Module Management
22570 & Not applicable\cr
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
22583 @c @multitable @columnfractions .3 .4 .4
22584 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22586 @tab @i{Tool with HP Ada}
22587 @tab @i{Tool with @value{EDITION}}
22588 @item Code Management@*System
22591 @item Language-Sensitive@*Editor
22593 @tab emacs or HP LSE (Alpha)
22602 @tab OpenVMS Debug (I64)
22603 @item Source Code Analyzer /@*Cross Referencer
22607 @tab HP Digital Test@*Manager (DTM)
22609 @item Performance and@*Coverage Analyzer
22612 @item Module Management@*System
22614 @tab Not applicable
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)
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:
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
22641 For exception handling, either or both of two models are supplied:
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
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.
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::
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
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
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
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
22806 @node Specifying a Run-Time Library
22807 @section Specifying a Run-Time Library
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:
22816 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
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:
22834 +--- adainclude----------+
22836 +--- adalib-----------+ |
22838 +--- rts-native | |
22840 | +--- adainclude <---+
22842 | +--- adalib <----+
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:
22858 $ rm -f adainclude adalib
22859 $ ln -s rts-sjlj/adainclude adainclude
22860 $ ln -s rts-sjlj/adalib adalib
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
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
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
22888 @cindex @code{SCHED_FIFO} scheduling policy
22889 you can use one of the following:
22893 @code{pragma Time_Slice (0.0)}
22894 @cindex pragma Time_Slice
22896 the corresponding binder option @option{-T0}
22897 @cindex @option{-T0} option
22899 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22900 @cindex pragma Task_Dispatching_Policy
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}
22910 @node Solaris-Specific Considerations
22911 @section Solaris-Specific Considerations
22912 @cindex Solaris Sparc threads libraries
22915 This section addresses some topics related to the various threads libraries
22919 * Solaris Threads Issues::
22922 @node Solaris Threads Issues
22923 @subsection Solaris Threads Issues
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)
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
22952 setting the environment variable @env{GNAT_PROCESSOR}
22953 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22954 to one of the following:
22958 Use the default configuration (run the program on all
22959 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22963 Let the run-time implementation choose one processor and run the program on
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).
22972 @node Linux-Specific Considerations
22973 @section Linux-Specific Considerations
22974 @cindex Linux threads libraries
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
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
23001 @node RTX-Specific Considerations
23002 @section RTX-Specific Considerations
23003 @cindex RTX libraries
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:
23011 Windows executables that run in Ring 3 to utilize memory protection
23012 (@emph{rts-rtx-w32}).
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.
23022 @node HP-UX-Specific Considerations
23023 @section HP-UX-Specific Considerations
23024 @cindex HP-UX Scheduling
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:
23041 @code{pragma Time_Slice (0.0)}
23042 @cindex pragma Time_Slice
23044 the corresponding binder option @option{-T0}
23045 @cindex @option{-T0} option
23047 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23048 @cindex pragma Task_Dispatching_Policy
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
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
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
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.
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.
23137 argv : System.Address;
23138 envp : System.Address)
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
23275 -- gnat.heap_sort_a (spec)
23276 -- gnat.heap_sort_a (body)
23277 -- gnat.htable (spec)
23278 -- gnat.htable (body)
23279 -- interfaces (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)
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)
23330 -- END ELABORATION ORDER
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");
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.
23363 pragma Import (Ada, E040, "interfaces__c_streams_E");
23366 pragma Import (Ada, E008, "ada__exceptions_E");
23369 pragma Import (Ada, E014, "system__exception_table_E");
23372 pragma Import (Ada, E053, "ada__io_exceptions_E");
23375 pragma Import (Ada, E017, "system__exceptions_E");
23378 pragma Import (Ada, E024, "system__secondary_stack_E");
23381 pragma Import (Ada, E030, "system__stack_checking_E");
23384 pragma Import (Ada, E028, "system__soft_links_E");
23387 pragma Import (Ada, E035, "ada__tags_E");
23390 pragma Import (Ada, E033, "ada__streams_E");
23393 pragma Import (Ada, E046, "system__finalization_root_E");
23396 pragma Import (Ada, E048, "system__finalization_implementation_E");
23399 pragma Import (Ada, E044, "ada__finalization_E");
23402 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23405 pragma Import (Ada, E055, "system__file_control_block_E");
23408 pragma Import (Ada, E042, "system__file_io_E");
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 := (
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
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
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
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
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.
23561 Interfaces.C_Streams'Elab_Spec;
23565 Ada.Exceptions'Elab_Spec;
23568 System.Exception_Table'Elab_Body;
23572 Ada.Io_Exceptions'Elab_Spec;
23576 System.Exceptions'Elab_Spec;
23580 System.Stack_Checking'Elab_Spec;
23583 System.Soft_Links'Elab_Body;
23588 System.Secondary_Stack'Elab_Body;
23592 Ada.Tags'Elab_Spec;
23595 Ada.Tags'Elab_Body;
23599 Ada.Streams'Elab_Spec;
23603 System.Finalization_Root'Elab_Spec;
23607 Ada.Exceptions'Elab_Body;
23611 System.Finalization_Implementation'Elab_Spec;
23614 System.Finalization_Implementation'Elab_Body;
23618 Ada.Finalization'Elab_Spec;
23622 Ada.Finalization.List_Controller'Elab_Spec;
23626 System.File_Control_Block'Elab_Spec;
23630 System.File_Io'Elab_Body;
23634 Ada.Text_Io'Elab_Spec;
23637 Ada.Text_Io'Elab_Body;
23641 Elab_Final_Code := 0;
23649 procedure adafinal is
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
23663 @findex Main Program
23666 argv : System.Address;
23667 envp : System.Address)
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
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
23697 procedure Ada_Main_Program;
23698 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23700 -- Start of processing for main
23703 -- Save global variables
23709 -- Call low level system initialization
23713 -- Call our generated Ada initialization routine
23717 -- This is the point at which we want the debugger to get
23722 -- Now we call the main program of the partition
23726 -- Perform Ada finalization
23730 -- Perform low level system finalization
23734 -- Return the proper exit status
23735 return (gnat_exit_status);
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
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
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;
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
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::
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
23809 @node Elaboration Code
23810 @section Elaboration Code
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
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
23823 Sqrt_Half : Float := Sqrt (0.5);
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.
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
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
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
23864 package Unit_2 is @dots{}
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
23880 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
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
23887 Sqrt_1 : Float := Sqrt (0.1);
23892 The elaboration code of the body of @code{Unit_1} also contains:
23894 @smallexample @c ada
23897 if expression_1 = 1 then
23898 Q := Unit_2.Func_2;
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
23912 Sqrt_2 : Float := Sqrt (0.1);
23917 The elaboration code of the body of @code{Unit_2} also contains:
23919 @smallexample @c ada
23922 if expression_2 = 2 then
23923 Q := Unit_1.Func_1;
23930 Now the question is, which of the following orders of elaboration is
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
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
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
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
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
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.
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
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:
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
24085 package Definitions is
24087 type m is new integer;
24089 type a is array (1 .. 10) of m;
24090 type b is array (1 .. 20) of m;
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
24103 @cindex pragma 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
24112 @item pragma Preelaborate
24113 @findex Preelaborate
24114 @cindex pragma Preelaborate
24115 This pragma places slightly less stringent restrictions on a unit than
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.
24136 unlike pragma @code{Pure} and pragma @code{Preelaborate},
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}.
24143 marks @code{Unit_1} as @code{Elaborate_Body},
24144 and not @code{Unit_2,} then the order of
24145 elaboration will be:
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:
24184 @item pragma Elaborate (unit)
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
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
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
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},
24218 not only that the body of @code{B} be elaborated before @code{A},
24220 body of @code{C}, because @code{B} @code{with}'s @code{C}.
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
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
24244 If this rule is not followed, then a program may be in one of four
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.
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
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
24301 @smallexample @c ada
24304 function One return Float;
24308 function One return Float is
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}:
24325 2. function One return Float;
24327 4. Q : Float := One;
24329 >>> warning: cannot call "One" before body is elaborated
24330 >>> warning: Program_Error will be raised at run time
24333 6. function One return Float is
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
24361 function One return Float;
24363 function One return Float is
24374 then all is well, no warning is generated, and no
24375 @code{Program_Error} exception
24377 Things are more complicated when a chain of subprograms is executed:
24379 @smallexample @c ada
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;
24391 function A return Integer is begin return 1; end;
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:
24413 2. function A return Integer;
24414 3. function B return Integer;
24415 4. function C return Integer;
24417 6. function B return Integer is begin return A; end;
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;
24426 9. X : Integer := C;
24428 11. function A return Integer is begin return 1; end;
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
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
24447 function B return Integer is
24449 if some-condition-depending-on-input-data then
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:
24479 Compile with the @option{-gnatws} switch set
24482 Suppress @code{Elaboration_Check} for the called subprogram
24485 Use pragma @code{Warnings_Off} to turn warnings off for the call
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
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
24517 function Sqrt (Arg : Float) return Float;
24520 package body Math is
24521 function Sqrt (Arg : Float) return Float is
24530 X : Float := Math.Sqrt (0.5);
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
24548 the spec of @code{Stuff} and the body of @code{Main}).
24549 In what order should the four separate sections of elaboration code
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
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}
24578 that is not a general rule that can be followed in all cases. Consider
24580 @smallexample @c ada
24583 package X is @dots{}
24585 package Y is @dots{}
24588 package body Y is @dots{}
24591 package body X is @dots{}
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},
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
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
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
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:
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.}
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
24662 If it is important to guarantee portability, then the compilations should
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
24675 m : integer := k.r;
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
24690 switch, then the compiler outputs a warning:
24697 3. m : integer := k.r;
24699 >>> warning: call to "r" may raise Program_Error
24700 >>> warning: missing pragma Elaborate_All for "k"
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);
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
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}
24783 When using the static mode with @option{-gnatwl}, any use of
24784 @code{pragma Elaborate} will generate a warning about possible
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
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
24824 type My_Int is new Integer;
24826 function Ident (M : My_Int) return My_Int;
24830 package body Decls is
24831 task body Lib_Task is
24837 function Ident (M : My_Int) return My_Int is
24845 procedure Put_Val (Arg : Decls.My_Int);
24849 package body Utils is
24850 procedure Put_Val (Arg : Decls.My_Int) is
24852 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24859 Decls.Lib_Task.Start;
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:
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.
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
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
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.
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.
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:
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
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
24951 problem in any other manner. So let us examine two ways to reorganize
24952 the program to avoid the potential elaboration problem.
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
24961 @smallexample @c ada
24969 package body Decls1 is
24970 task body Lib_Task is
24978 type My_Int is new Integer;
24979 function Ident (M : My_Int) return My_Int;
24983 package body Decls2 is
24984 function Ident (M : My_Int) return My_Int is
24992 procedure Put_Val (Arg : Decls2.My_Int);
24996 package body Utils is
24997 procedure Put_Val (Arg : Decls2.My_Int) is
24999 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
25006 Decls1.Lib_Task.Start;
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.
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
25030 task type Lib_Task_Type is
25034 type My_Int is new Integer;
25036 function Ident (M : My_Int) return My_Int;
25040 package body Decls is
25041 task body Lib_Task_Type is
25047 function Ident (M : My_Int) return My_Int is
25055 procedure Put_Val (Arg : Decls.My_Int);
25059 package body Utils is
25060 procedure Put_Val (Arg : Decls.My_Int) is
25062 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25068 Lib_Task : Decls.Lib_Task_Type;
25074 Declst.Lib_Task.Start;
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.
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
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:
25123 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
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.
25144 @node Mixing Elaboration Models
25145 @section Mixing Elaboration Models
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
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:
25168 The @code{with'ed} unit is itself compiled with dynamic elaboration
25169 checks (that is with the @option{-gnatE} switch.
25172 The @code{with'ed} unit is an internal GNAT implementation unit from
25173 the System, Interfaces, Ada, or GNAT hierarchies.
25176 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25179 The @code{with'ing} unit (that is the client) has an explicit pragma
25180 @code{Elaborate_All} for the @code{with'ed} unit.
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:
25191 warning: "x.ads" has dynamic elaboration checks and with's
25192 warning: "y.ads" which has static elaboration checks
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
25212 If the binder cannot find an acceptable order, it outputs detailed
25213 diagnostics. For example:
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)"
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.
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
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
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
25294 Place the pragma that names the called subprogram in the declarative part
25295 that contains the call.
25298 Place the pragma in the declarative part, without naming an entity. This
25299 disables warnings on all calls in the corresponding declarative region.
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
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.
25321 These five cases are listed in order of decreasing safety, and therefore
25322 require increasing programmer care in their application. Consider the
25325 @smallexample @c adanocomment
25327 function F1 return Integer;
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)
25339 package body Pack1 is
25340 function F1 return Integer is
25344 Val : integer := Pack2.Pure (11); -- Elab. call (1)
25347 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
25348 -- pragma Suppress(Elaboration_Check); -- (2)
25350 X1 := Pack2.F2 + 1; -- Elab. call (2)
25355 package body Pack2 is
25356 function F2 return Integer is
25360 function Pure (x : integer) return integer is
25362 return x ** 3 - 3 * x;
25366 with Pack1, Ada.Text_IO;
25369 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25372 In the absence of any pragmas, an attempt to bind this program produces
25373 the following diagnostics:
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)"
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.
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.
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.
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
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
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^}
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
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
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
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
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
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
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
25528 package Init_Constants is
25529 procedure P; -- require a body
25530 end Init_Constants;
25533 package body Init_Constants is
25534 procedure P is begin null; end;
25538 end Init_Constants;
25542 Z : Integer := Constants.X + Constants.Y;
25546 with Text_IO; use Text_IO;
25549 Put_Line (Calc.Z'Img);
25554 In this example, there is more than one valid order of elaboration. For
25555 example both the following are correct orders:
25558 Init_Constants spec
25561 Init_Constants body
25566 Init_Constants spec
25567 Init_Constants body
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}
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);
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
25628 gnatmake -f -q main
25631 gnatmake -f -q main -bargs -p
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 **********************************
25653 * Overflow Checking Modes in GNAT::
25654 * Specifying the Desired Mode::
25655 * Default Settings::
25656 * Implementation Notes::
25661 @section Background
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
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
25679 A trickier situation arises in examples like the following:
25681 @smallexample @c ada
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.
25700 raise an exception (@code{Constraint_Error}), or
25703 yield the correct mathematical result which is then used in
25704 subsequent operations.
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
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;
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;
25764 @smallexample @c ada
25765 Q (A => Integer'Last, B => 1, C => -1);
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
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:
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
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;
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
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.
25864 Note that these modes apply only to the evaluation of predefined
25865 arithmetic, membership, and comparison operators for signed integer
25868 For fixed-point arithmetic, checks can be suppressed. But if checks
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
25883 @c -------------------------
25884 @node Specifying the Desired Mode
25885 @section Specifying the Desired Mode
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]);
25898 where @code{MODE} is one of
25901 @item @code{STRICT}: intermediate overflows checked (using base type)
25902 @item @code{MINIMIZED}: minimize intermediate overflows
25903 @item @code{ELIMINATED}: eliminate intermediate overflows
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}
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);
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
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}':
25954 use base type for intermediate operations (@code{STRICT})
25956 minimize intermediate overflows (@code{MINIMIZED})
25958 eliminate intermediate overflows (@code{ELIMINATED})
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
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
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)
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
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
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
26065 @c *******************************
26066 @node Conditional Compilation
26067 @appendix Conditional Compilation
26068 @c *******************************
26069 @cindex Conditional compilation
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
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
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
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.
26102 * Use of Boolean Constants::
26103 * Debugging - A Special Case::
26104 * Conditionalizing Declarations::
26105 * Use of Alternative Implementations::
26109 @node Use of Boolean Constants
26110 @section Use of Boolean Constants
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
26119 FP_Initialize_Required : constant Boolean := True;
26121 if FP_Initialize_Required then
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
26136 @cindex Preprocessors (contrasted with conditional compilation)
26138 Typically the Boolean constants will be in a separate package,
26141 @smallexample @c ada
26144 FP_Initialize_Required : constant Boolean := True;
26145 Reset_Available : constant Boolean := False;
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
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
26168 @smallexample @c ada
26171 Put_Line ("got to the first stage!");
26179 @smallexample @c ada
26181 if Debugging and then Temperature > 999.0 then
26182 raise Temperature_Crazy;
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");
26205 @smallexample @c ada
26206 pragma Assert (Temperature <= 999.0);
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}
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
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!"));
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
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
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
26267 @dots{} -- some statements
26269 pragma Assert (Num_Cases < 10);
26276 @node Conditionalizing Declarations
26277 @section Conditionalizing Declarations
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
26289 if Small_Machine then
26291 X : Bit_String (1 .. 10);
26297 X : Large_Bit_String (1 .. 1000);
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
26317 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
26323 If @code{Bits_Per_Word} is set to 32, this generates either
26325 @smallexample @c ada
26328 Field1 at 0 range 0 .. 32;
26334 for the big endian case, or
26336 @smallexample @c ada
26339 Field1 at 0 range 10 .. 32;
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
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
26379 @dots{} neat Ada 2005 code
26381 @dots{} not quite as neat Ada 95 code
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;
26402 Then we have two files for the subunit @code{Insert}, with the two sets of
26404 If the package containing this is called @code{File_Queries}, then we might
26408 @item @file{file_queries-insert-2005.adb}
26409 @item @file{file_queries-insert-95.adb}
26413 and the build script renames the appropriate file to
26416 file_queries-insert.adb
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";
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
26446 which is the same for all architectures, and three bodies:
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
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}
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
26475 The same idea can also be implemented using tagged types and dispatching
26479 @node Preprocessing
26480 @section Preprocessing
26481 @cindex Preprocessing
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
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
26506 #if DEBUG or PRIORITY > 4 then
26507 bunch of declarations
26509 completely different bunch of declarations
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 *******************************
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:
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
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.
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::
26568 @c ---------------------------------------------------------------------------
26569 @node Basic Assembler Syntax
26570 @section Basic Assembler Syntax
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.
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}
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}
26613 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
26616 Intel: Implicit, deduced by assembler; for example @code{mov}
26618 @item Instruction repetition
26619 gcc / @emph{as}: Split into two lines; for example
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}
26633 @c ---------------------------------------------------------------------------
26634 @node A Simple Example of Inline Assembler
26635 @section A Simple Example of Inline Assembler
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
26645 with System.Machine_Code; use System.Machine_Code;
26646 procedure Nothing is
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
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:
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:
26675 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
26677 where the options are:
26681 compile only (no bind or link)
26683 generate assembler listing
26684 @item -fomit-frame-pointer
26685 do not set up separate stack frames
26687 do not add runtime checks
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
26697 .file "nothing.adb"
26699 ___gnu_compiled_ada:
26702 .globl __ada_nothing
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
26730 as @file{nothing.s}
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
26743 The examples in this section, showing how to access the processor flags,
26744 illustrate how to specify the destination operands for assembly language
26747 @smallexample @c ada
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;
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);
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:
26775 movl %eax, -40(%ebp)
26780 It would have been legal to write the Asm invocation as:
26783 Asm ("pushfl popl %%eax movl %%eax, %0")
26786 but in the generated assembler file, this would come out as:
26790 pushfl popl %eax movl %eax, -40(%ebp)
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:
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}:
26825 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26828 The output is defined by the @code{Asm_Output} attribute of the target type;
26829 the general format is
26831 Type'Asm_Output (constraint_string, variable_name)
26834 The constraint string directs the compiler how
26835 to store/access the associated variable. In the example
26837 Unsigned_32'Asm_Output ("=m", Flags);
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,
26843 Unsigned_32'Asm_Output ("=r", Flags);
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:
26861 global (i.e.@: can be stored anywhere)
26879 use one of eax, ebx, ecx or edx
26881 use one of eax, ebx, ecx, edx, esi or edi
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
26891 @smallexample @c ada
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));
26900 @code{%0} will be replaced in the expanded code by the appropriate operand,
26902 the compiler decided for the @code{Flags} variable.
26904 In general, you may have any number of output variables:
26907 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26909 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26910 of @code{Asm_Output} attributes
26914 @smallexample @c ada
26916 Asm ("movl %%eax, %0" & LF & HT &
26917 "movl %%ebx, %1" & LF & HT &
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
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
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;
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);
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:
26960 movl %eax,-40(%ebp)
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
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;
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);
26988 @c ---------------------------------------------------------------------------
26989 @node Input Variables in Inline Assembler
26990 @section Input Variables in Inline Assembler
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
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;
27008 Outputs => Unsigned_32'Asm_Output ("=a", Result),
27009 Inputs => Unsigned_32'Asm_Input ("a", Value));
27013 Value : Unsigned_32;
27017 Put_Line ("Value before is" & Value'Img);
27018 Value := Incr (Value);
27019 Put_Line ("Value after is" & Value'Img);
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:
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
27050 The resulting assembler file (with @option{-O2} optimization) contains:
27053 _increment__incr.1:
27066 @c ---------------------------------------------------------------------------
27067 @node Inlining Inline Assembler Code
27068 @section Inlining Inline Assembler Code
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
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;
27090 Outputs => Unsigned_32'Asm_Output ("=a", Result),
27091 Inputs => Unsigned_32'Asm_Input ("a", Value));
27094 pragma Inline (Increment);
27096 Value : Unsigned_32;
27100 Put_Line ("Value before is" & Value'Img);
27101 Value := Increment (Value);
27102 Put_Line ("Value after is" & Value'Img);
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:
27116 call _increment__incr.1
27121 the code for the function body directly appears:
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
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.
27146 * The Clobber Parameter::
27147 * The Volatile Parameter::
27150 @c ---------------------------------------------------------------------------
27151 @node The Clobber Parameter
27152 @subsection The @code{Clobber} Parameter
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.,
27160 the eax register). But more generally, the compiler needs an explicit
27161 identification of the registers that are used by the Inline Assembly
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:
27171 Asm ("movl %0, %%ebx" & LF & HT &
27173 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27174 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
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:
27186 Asm ("movl %0, %%ebx" & LF & HT &
27188 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27189 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
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:
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
27205 @c ---------------------------------------------------------------------------
27206 @node The Volatile Parameter
27207 @subsection The @code{Volatile} Parameter
27208 @cindex Volatile parameter
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
27221 Asm ("movl %0, %%ebx" & LF & HT &
27223 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27224 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
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
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
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.
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::
27260 @c Brief section is only in non-VMS version
27261 @c Full chapter is in VMS version
27262 * Compatibility with HP Ada 83::
27265 * Transitioning to 64-Bit GNAT for OpenVMS::
27269 @node Compatibility with Ada 83
27270 @section Compatibility with Ada 83
27271 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
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.
27284 following subsections treat the most likely issues to be encountered.
27287 * Legal Ada 83 programs that are illegal in Ada 95::
27288 * More deterministic semantics::
27289 * Changed semantics::
27290 * Other language compatibility issues::
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:
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.
27305 @smallexample @c ada
27306 for Char in 'A' .. 'Z' loop @dots{} end loop;
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;
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
27334 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
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.
27381 @node More deterministic semantics
27382 @subsection More deterministic semantics
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.
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.
27401 @node Changed semantics
27402 @subsection Changed semantics
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.
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.
27434 @node Other language compatibility issues
27435 @subsection Other language compatibility issues
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.
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.
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
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}.
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
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,
27505 The ambiguity may be resolved either by applying a type conversion to the
27506 expression, or by explicitly invoking the operation from package
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.
27515 @node Implementation-dependent characteristics
27516 @section Implementation-dependent characteristics
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.
27528 * Implementation-defined pragmas::
27529 * Implementation-defined attributes::
27531 * Elaboration order::
27532 * Target-specific aspects::
27535 @node Implementation-defined pragmas
27536 @subsection Implementation-defined pragmas
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
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
27569 @subsection Libraries
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:
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
27580 If the source code for the specs but not the bodies are
27581 available, then you can reimplement the bodies.
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.
27590 @node Elaboration order
27591 @subsection Elaboration order
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:
27609 Modify the program to eliminate the circularities, e.g.@: by moving
27610 elaboration-time code into explicitly-invoked procedures
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).
27620 @node Target-specific aspects
27621 @subsection Target-specific aspects
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
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.)
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.
27668 @node Representation Clauses
27669 @section Representation Clauses
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.
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;
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.
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
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.
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.
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.
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})
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#);
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)
27818 pragma Pure_Function (To_Address_Long);
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.
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.
27844 @node Transitioning to 64-Bit GNAT for OpenVMS
27845 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
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.
27854 * Introduction to transitioning::
27855 * Migration of 32 bit code::
27856 * Taking advantage of 64 bit addressing::
27857 * Technical details::
27860 @node Introduction to transitioning
27861 @subsection Introduction
27864 64-bit @value{EDITION} for Open VMS has been designed to meet
27869 Providing a full conforming implementation of Ada 95 and Ada 2005
27872 Allowing maximum backward compatibility, thus easing migration of existing
27876 Supplying a path for exploiting the full 64-bit address range
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).
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
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::
27923 @node Address types
27924 @subsubsection Address types
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:
27933 @code{System.Address} always has a size of 64 bits
27934 @cindex @code{System.Address} size
27935 @cindex @code{Address} size
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
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,
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
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
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
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:
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
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
28012 @cindex @option{-H32} (@command{gnatbind})
28013 @cindex @option{-H64} (@command{gnatbind})
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.
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.
28038 @node Unchecked conversions
28039 @subsubsection Unchecked conversions
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
28054 The following table shows the correspondence between pre-2006 versions of
28055 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
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
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
28077 @node Interfacing with C
28078 @subsubsection Interfacing with C
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
28109 @node 32/64-bit descriptors
28110 @subsubsection 32/64-bit descriptors
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
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
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
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::
28158 @node Making code 64 bit clean
28159 @subsubsection Making code 64-bit clean
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:
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.
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.
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}).
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
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
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
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
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
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
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
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.
28254 @c ************************************************
28256 @node Microsoft Windows Topics
28257 @appendix Microsoft Windows Topics
28263 This chapter describes topics that are specific to the Microsoft Windows
28264 platforms (NT, 2000, and XP Professional).
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::
28284 @node Using GNAT on Windows
28285 @section Using GNAT on Windows
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
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:
28300 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
28304 You can use any Dynamically Linked Library (DLL) in your Ada code (both
28305 relocatable and non-relocatable DLLs are supported).
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.
28313 You can include Windows resources in your Ada application.
28316 You can use or create COM/DCOM objects.
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.
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.
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.
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.
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.
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.
28359 @node Using a network installation of GNAT
28360 @section Using a network installation of GNAT
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
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
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.
28395 $ gnatmake winprog -largs -mwindows
28398 @node Temporary Files
28399 @section Temporary Files
28400 @cindex Temporary files
28403 It is possible to control where temporary files gets created by setting
28404 the @env{TMP} environment variable. The file will be created:
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.
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
28422 @node Mixed-Language Programming on Windows
28423 @section Mixed-Language Programming on Windows
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:
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}).
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.
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:
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[])
28467 /* Initialize the SEH context */
28468 __gnat_initialize (&SEH);
28472 /* Then call Ada services in the stand-alone library */
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
28488 This section pertain only to Win32. On Win64 there is a single native
28489 calling convention. All convention specifiers are ignored on this
28493 * C Calling Convention::
28494 * Stdcall Calling Convention::
28495 * Win32 Calling Convention::
28496 * DLL Calling Convention::
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:
28510 @code{C} (Microsoft defined)
28513 @code{Stdcall} (Microsoft defined)
28516 @code{Win32} (GNAT specific)
28519 @code{DLL} (GNAT specific)
28522 @node C Calling Convention
28523 @subsection @code{C} Calling Convention
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:
28539 int get_val (long);
28543 should be imported from Ada as follows:
28545 @smallexample @c ada
28547 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28548 pragma Import (C, Get_Val, External_Name => "get_val");
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
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:
28587 @b{APIENTRY} int get_val (long);
28591 should be imported from Ada as follows:
28593 @smallexample @c ada
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"
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
28608 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28609 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
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
28620 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28621 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
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}}.
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.
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:
28645 then, to access this variable from Ada you should write:
28647 @smallexample @c ada
28649 My_Var : Interfaces.C.int;
28650 pragma Import (Stdcall, My_Var);
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
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
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)
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:
28700 Your application is loaded into memory.
28703 The DLL @file{API.dll} is mapped into the address space of your
28704 application. This means that:
28708 The DLL will use the stack of the calling thread.
28711 The DLL will use the virtual address space of the calling process.
28714 The DLL will allocate memory from the virtual address space of the calling
28718 Handles (pointers) can be safely exchanged between routines in the DLL
28719 routines and routines in the application using the DLL.
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}.
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.
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
28758 * Creating an Ada Spec for the DLL Services::
28759 * Creating an Import Library::
28763 To use the services of a DLL, say @file{API.dll}, in your Ada application
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.
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.
28781 The actual DLL, @file{API.dll}.
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
28790 $ gnatmake my_ada_app -largs -lAPI
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:
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}
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
28813 @smallexample @c ada
28814 pragma Linker_Options ("-lAPI");
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
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:
28847 then the equivalent Ada spec could be:
28849 @smallexample @c ada
28852 with Interfaces.C.Strings;
28857 function Get (Str : C.Strings.Chars_Ptr) return C.int;
28860 pragma Import (C, Get);
28861 pragma Import (DLL, Some_Var);
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
28878 * The Definition File::
28879 * GNAT-Style Import Library::
28880 * Microsoft-Style Import Library::
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
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:
28906 @r{[}LIBRARY @var{name}@r{]}
28907 @r{[}DESCRIPTION @var{string}@r{]}
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.
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:
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.
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
28953 To create a static import library from @file{API.dll} with the GNAT tools
28954 you should proceed as follows:
28958 Create the definition file @file{API.def} (@pxref{The Definition File}).
28959 For that use the @code{dll2def} tool as follows:
28962 $ dll2def API.dll > API.def
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.
28974 Here are some hints to find the right @code{@@}@var{nn} suffix.
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).
28983 $ dumpbin /exports api.lib
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.
28993 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28994 (@pxref{Using gnatdll}) as follows:
28997 $ gnatdll -e API.def -d API.dll
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}).
29012 @node Microsoft-Style Import Library
29013 @subsubsection Microsoft-Style Import Library
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:
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).
29031 Build the actual import library using Microsoft's @code{lib} utility:
29034 $ lib -machine:IX86 -def:API.def -out:API.lib
29038 If you use the above command the definition file @file{API.def} must
29039 contain a line giving the name of the DLL:
29046 See the Microsoft documentation for further details about the usage of
29050 @node Building DLLs with GNAT Project files
29051 @section Building DLLs with GNAT Project files
29052 @cindex DLLs, building
29055 There is nothing specific to Windows in the build process.
29056 @pxref{Library Projects}.
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
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.
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:
29085 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
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:
29094 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
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:
29110 $ copy *.ads *.ali api.dll apilib
29111 $ attrib +R apilib\*.ali
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
29122 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
29125 @node Building DLLs with gnatdll
29126 @section Building DLLs with gnatdll
29127 @cindex DLLs, building
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::
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:
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.
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.
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.
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.
29177 You must provide a definition file listing the exported entities
29178 (@pxref{The Definition File}).
29181 Finally you must use @code{gnatdll} to produce the DLL and the import
29182 library (@pxref{Using gnatdll}).
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
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
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
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
29224 @smallexample @c ada
29227 with Interfaces.C; use Interfaces;
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.
29236 pragma Export (C, Initialize_API);
29237 pragma Export (C, Finalize_API);
29238 pragma Export (C, Count);
29239 pragma Export (C, Factorial);
29245 @smallexample @c ada
29248 package body API is
29249 function Factorial (Val : C.int) return C.int is
29252 Count := Count + 1;
29253 for K in 1 .. Val loop
29259 procedure Initialize_API is
29261 pragma Import (C, Adainit);
29264 end Initialize_API;
29266 procedure Finalize_API is
29267 procedure Adafinal;
29268 pragma Import (C, Adafinal);
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
29283 @smallexample @c ada
29287 Count : Integer := 0;
29288 function Factorial (Val : Integer) return Integer;
29290 procedure Initialize_API;
29291 procedure Finalize_API;
29292 -- Initialization and Finalization routines.
29298 @smallexample @c ada
29301 package body API is
29302 function Factorial (Val : Integer) return Integer is
29303 Fact : Integer := 1;
29305 Count := Count + 1;
29306 for K in 1 .. Val loop
29313 -- The remainder of this package body is unchanged.
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
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
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
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:
29382 extern int *_imp__count;
29383 #define count (*_imp__count)
29384 int factorial (int);
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
29402 Count : Integer := 0;
29404 -- Remainder of the package omitted.
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
29415 @smallexample @c ada
29420 pragma Import (DLL, Count);
29426 @node Creating the Definition File
29427 @subsection Creating the Definition File
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:
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:
29459 api__initialize_api
29464 @node Using gnatdll
29465 @subsection Using @code{gnatdll}
29469 * gnatdll Example::
29470 * gnatdll behind the Scenes::
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
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{]}
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.
29498 You may specify any of the following switches to @code{gnatdll}:
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
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.
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
29544 @cindex @option{-h} (@code{gnatdll})
29545 Help mode. Displays @code{gnatdll} switch usage information.
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)}).
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.
29569 @cindex @option{-n} (@code{gnatdll})
29570 No Import. Do not create the import library.
29573 @cindex @option{-q} (@code{gnatdll})
29574 Quiet mode. Do not display unnecessary messages.
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.
29585 @node gnatdll Example
29586 @subsubsection @code{gnatdll} Example
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
29593 $ gnatdll -d api.dll api.ali
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:
29602 $ gnatdll -d api.dll -n api.ali
29606 Alternatively if you want to create just the import library, type:
29609 $ gnatdll -d api.dll
29612 @node gnatdll behind the Scenes
29613 @subsubsection @code{gnatdll} behind the Scenes
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
29629 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
29630 the information necessary to generate relocation information for the
29636 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
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.
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.
29655 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29656 --output-exp api.exp
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}.
29668 $ gnatlink api -o api.jnk api.exp -mdll
29669 -Wl,--base-file,api.base
29674 @code{gnatdll} builds the new export table using the new base file and
29675 generates the DLL import library @file{libAPI.dll.a}.
29679 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29680 --output-exp api.exp --output-lib libAPI.a
29685 Finally @code{gnatdll} builds the relocatable DLL using the final export
29691 $ gnatlink api api.exp -o api.dll -mdll
29696 @node Using dlltool
29697 @subsubsection Using @code{dlltool}
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
29706 @c $ dlltool @ovar{switches}
29707 @c Expanding @ovar macro inline (explanation in macro def comments)
29708 $ dlltool @r{[}@var{switches}@r{]}
29712 @code{dlltool} switches include:
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}.
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.
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}.
29750 @cindex @option{-v} (@command{dlltool})
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}.
29758 @node GNAT and Windows Resources
29759 @section GNAT and Windows Resources
29760 @cindex Resources, windows
29763 * Building Resources::
29764 * Compiling Resources::
29765 * Using Resources::
29769 Resources are an easy way to add Windows specific objects to your
29770 application. The objects that can be added as resources include:
29779 @item string tables
29789 @item version information
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
29803 FILEVERSION 1,0,0,0
29804 PRODUCTVERSION 1,0,0,0
29806 BLOCK "StringFileInfo"
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"
29821 BLOCK "VarFileInfo"
29823 VALUE "Translation", 0x809, 1252
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
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
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
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
29859 @cindex Resources, compiling
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:
29867 $ windres -i myres.rc -o myres.o
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:
29884 $ windres -i myres.res -o myres.o
29887 @node Using Resources
29888 @subsection Using Resources
29889 @cindex Resources, using
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}
29898 $ gnatmake myprog -largs myres.o
29901 @node Debugging a DLL
29902 @section Debugging a DLL
29903 @cindex DLL debugging
29906 * Program and DLL Both Built with GCC/GNAT::
29907 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
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:
29917 The program and the DLL are built with @code{GCC/GNAT}.
29919 The program is built with foreign tools and the DLL is built with
29922 The program is built with @code{GCC/GNAT} and the DLL is built with
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
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
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:
29949 @item Launch @code{GDB} on the main program.
29955 @item Start the program and stop at the beginning of the main procedure
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
29970 (gdb) break ada_dll
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}).
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:
29991 @item Launch @code{GDB} on the main program.
29997 @item Load DLL symbols
30000 (gdb) add-sym api.dll
30003 @item Set a breakpoint inside the DLL
30006 (gdb) break ada_dll.adb:45
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
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
30026 * Debugging the DLL Directly::
30027 * Attaching to a Running Process::
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.
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
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
30054 Find out the executable starting address
30057 $ objdump --file-header main.exe
30060 The starting address is reported on the last line. For example:
30063 main.exe: file format pei-i386
30064 architecture: i386, flags 0x0000010a:
30065 EXEC_P, HAS_DEBUG, D_PAGED
30066 start address 0x00401010
30070 Launch the debugger on the executable.
30077 Set a breakpoint at the starting address, and launch the program.
30080 $ (gdb) break *0x00401010
30084 The program will stop at the given address.
30087 Set a breakpoint on a DLL subroutine.
30090 (gdb) break ada_dll.adb:45
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).
30097 (gdb) set language ada
30098 (gdb) break ada_dll
30102 Continue the program.
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}).
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
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.
30131 @item Launch the main program @file{main.exe}.
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.
30146 @item Attach to the running process to be debugged.
30152 @item Load the process debugging information.
30155 (gdb) symbol-file main.exe
30158 @item Break somewhere in the DLL.
30161 (gdb) break ada_dll
30164 @item Continue process execution.
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}
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:
30198 @item using @option{-Xlinker} linker option
30201 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
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
30210 $ gnatlink hello -Wl,--stack=0x1000000
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.
30219 @node Setting Heap Size from gnatlink
30220 @section Setting Heap Size from @command{gnatlink}
30223 Under Windows systems, it is possible to specify the program heap size from
30224 @command{gnatlink} using either:
30228 @item using @option{-Xlinker} linker option
30231 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
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
30240 $ gnatlink hello -Wl,--heap=0x1000000
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.
30249 @node Mac OS Topics
30250 @appendix Mac OS Topics
30254 This chapter describes topics that are specific to Apple's OS X
30258 * Codesigning the Debugger::
30261 @node Codesigning the Debugger
30262 @section Codesigning the Debugger
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:
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))
30276 Codesigning requires a certificate. The following procedure explains
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
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
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)
30313 Once a certificate has been created, the debugger can be codesigned
30314 as follow. In a Terminal, run the following command...
30317 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
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.
30326 @c **********************************
30327 @c * GNU Free Documentation License *
30328 @c **********************************
30330 @c GNU Free Documentation License
30332 @node Index,,GNU Free Documentation License, Top
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