1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2012, 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::
218 * GNU Free Documentation License::
221 --- The Detailed Node Listing ---
225 * What This Guide Contains::
226 * What You Should Know before Reading This Guide::
227 * Related Information::
230 Getting Started with GNAT
233 * Running a Simple Ada Program::
234 * Running a Program with Multiple Units::
235 * Using the gnatmake Utility::
237 * Editing with Emacs::
240 * Introduction to GPS::
243 The GNAT Compilation Model
245 * Source Representation::
246 * Foreign Language Representation::
247 * File Naming Rules::
248 * Using Other File Names::
249 * Alternative File Naming Schemes::
250 * Generating Object Files::
251 * Source Dependencies::
252 * The Ada Library Information Files::
253 * Binding an Ada Program::
254 * Mixed Language Programming::
256 * Building Mixed Ada & C++ Programs::
257 * Comparison between GNAT and C/C++ Compilation Models::
259 * Comparison between GNAT and Conventional Ada Library Models::
261 * Placement of temporary files::
264 Foreign Language Representation
267 * Other 8-Bit Codes::
268 * Wide Character Encodings::
270 Compiling Ada Programs With gcc
272 * Compiling Programs::
274 * Search Paths and the Run-Time Library (RTL)::
275 * Order of Compilation Issues::
280 * Output and Error Message Control::
281 * Warning Message Control::
282 * Debugging and Assertion Control::
283 * Validity Checking::
286 * Using gcc for Syntax Checking::
287 * Using gcc for Semantic Checking::
288 * Compiling Different Versions of Ada::
289 * Character Set Control::
290 * File Naming Control::
291 * Subprogram Inlining Control::
292 * Auxiliary Output Control::
293 * Debugging Control::
294 * Exception Handling Control::
295 * Units to Sources Mapping Files::
296 * Integrated Preprocessing::
301 Binding Ada Programs With gnatbind
304 * Switches for gnatbind::
305 * Command-Line Access::
306 * Search Paths for gnatbind::
307 * Examples of gnatbind Usage::
309 Switches for gnatbind
311 * Consistency-Checking Modes::
312 * Binder Error Message Control::
313 * Elaboration Control::
315 * Binding with Non-Ada Main Programs::
316 * Binding Programs with No Main Subprogram::
318 Linking Using gnatlink
321 * Switches for gnatlink::
323 The GNAT Make Program gnatmake
326 * Switches for gnatmake::
327 * Mode Switches for gnatmake::
328 * Notes on the Command Line::
329 * How gnatmake Works::
330 * Examples of gnatmake Usage::
332 Improving Performance
333 * Performance Considerations::
334 * Text_IO Suggestions::
335 * Reducing Size of Ada Executables with gnatelim::
336 * Reducing Size of Executables with unused subprogram/data elimination::
338 Performance Considerations
339 * Controlling Run-Time Checks::
340 * Use of Restrictions::
341 * Optimization Levels::
342 * Debugging Optimized Code::
343 * Inlining of Subprograms::
344 * Vectorization of loops::
345 * Other Optimization Switches::
346 * Optimization and Strict Aliasing::
348 * Coverage Analysis::
351 Reducing Size of Ada Executables with gnatelim
354 * Processing Precompiled Libraries::
355 * Correcting the List of Eliminate Pragmas::
356 * Making Your Executables Smaller::
357 * Summary of the gnatelim Usage Cycle::
359 Reducing Size of Executables with unused subprogram/data elimination
360 * About unused subprogram/data elimination::
361 * Compilation options::
363 Renaming Files Using gnatchop
365 * Handling Files with Multiple Units::
366 * Operating gnatchop in Compilation Mode::
367 * Command Line for gnatchop::
368 * Switches for gnatchop::
369 * Examples of gnatchop Usage::
371 Configuration Pragmas
373 * Handling of Configuration Pragmas::
374 * The Configuration Pragmas Files::
376 Handling Arbitrary File Naming Conventions Using gnatname
378 * Arbitrary File Naming Conventions::
380 * Switches for gnatname::
381 * Examples of gnatname Usage::
383 The Cross-Referencing Tools gnatxref and gnatfind
385 * Switches for gnatxref::
386 * Switches for gnatfind::
387 * Project Files for gnatxref and gnatfind::
388 * Regular Expressions in gnatfind and gnatxref::
389 * Examples of gnatxref Usage::
390 * Examples of gnatfind Usage::
392 The GNAT Pretty-Printer gnatpp
394 * Switches for gnatpp::
397 The GNAT Metrics Tool gnatmetric
399 * Switches for gnatmetric::
401 File Name Krunching Using gnatkr
406 * Examples of gnatkr Usage::
408 Preprocessing Using gnatprep
409 * Preprocessing Symbols::
411 * Switches for gnatprep::
412 * Form of Definitions File::
413 * Form of Input Text for gnatprep::
415 The GNAT Library Browser gnatls
418 * Switches for gnatls::
419 * Examples of gnatls Usage::
421 Cleaning Up Using gnatclean
423 * Running gnatclean::
424 * Switches for gnatclean::
425 @c * Examples of gnatclean Usage::
431 * Introduction to Libraries in GNAT::
432 * General Ada Libraries::
433 * Stand-alone Ada Libraries::
434 * Rebuilding the GNAT Run-Time Library::
436 Using the GNU make Utility
438 * Using gnatmake in a Makefile::
439 * Automatically Creating a List of Directories::
440 * Generating the Command Line Switches::
441 * Overcoming Command Line Length Limits::
444 Memory Management Issues
446 * Some Useful Memory Pools::
447 * The GNAT Debug Pool Facility::
452 Stack Related Facilities
454 * Stack Overflow Checking::
455 * Static Stack Usage Analysis::
456 * Dynamic Stack Usage Analysis::
458 Some Useful Memory Pools
460 The GNAT Debug Pool Facility
466 * Switches for gnatmem::
467 * Example of gnatmem Usage::
470 Verifying Properties Using gnatcheck
472 Sample Bodies Using gnatstub
475 * Switches for gnatstub::
477 Creating Unit Tests Using gnattest
480 * Switches for gnattest::
481 * Project Attributes for gnattest::
483 * Setting Up and Tearing Down the Testing Environment::
484 * Regenerating Tests::
485 * Default Test Behavior::
486 * Testing Primitive Operations of Tagged Types::
487 * Testing Inheritance::
488 * Tagged Types Substitutability Testing::
489 * Testing with Contracts::
492 * Support for other platforms/run-times::
494 * Current Limitations::
496 Other Utility Programs
498 * Using Other Utility Programs with GNAT::
499 * The External Symbol Naming Scheme of GNAT::
500 * Converting Ada Files to html with gnathtml::
503 Code Coverage and Profiling
505 * Code Coverage of Ada Programs using gcov::
506 * Profiling an Ada Program using gprof::
509 Running and Debugging Ada Programs
511 * The GNAT Debugger GDB::
513 * Introduction to GDB Commands::
514 * Using Ada Expressions::
515 * Calling User-Defined Subprograms::
516 * Using the Next Command in a Function::
519 * Debugging Generic Units::
520 * Remote Debugging using gdbserver::
521 * GNAT Abnormal Termination or Failure to Terminate::
522 * Naming Conventions for GNAT Source Files::
523 * Getting Internal Debugging Information::
531 Compatibility with HP Ada
533 * Ada Language Compatibility::
534 * Differences in the Definition of Package System::
535 * Language-Related Features::
536 * The Package STANDARD::
537 * The Package SYSTEM::
538 * Tasking and Task-Related Features::
539 * Pragmas and Pragma-Related Features::
540 * Library of Predefined Units::
542 * Main Program Definition::
543 * Implementation-Defined Attributes::
544 * Compiler and Run-Time Interfacing::
545 * Program Compilation and Library Management::
547 * Implementation Limits::
548 * Tools and Utilities::
550 Language-Related Features
552 * Integer Types and Representations::
553 * Floating-Point Types and Representations::
554 * Pragmas Float_Representation and Long_Float::
555 * Fixed-Point Types and Representations::
556 * Record and Array Component Alignment::
558 * Other Representation Clauses::
560 Tasking and Task-Related Features
562 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
563 * Assigning Task IDs::
564 * Task IDs and Delays::
565 * Task-Related Pragmas::
566 * Scheduling and Task Priority::
568 * External Interrupts::
570 Pragmas and Pragma-Related Features
572 * Restrictions on the Pragma INLINE::
573 * Restrictions on the Pragma INTERFACE::
574 * Restrictions on the Pragma SYSTEM_NAME::
576 Library of Predefined Units
578 * Changes to DECLIB::
582 * Shared Libraries and Options Files::
586 Platform-Specific Information for the Run-Time Libraries
588 * Summary of Run-Time Configurations::
589 * Specifying a Run-Time Library::
590 * Choosing the Scheduling Policy::
591 * Solaris-Specific Considerations::
592 * Linux-Specific Considerations::
593 * AIX-Specific Considerations::
594 * RTX-Specific Considerations::
595 * HP-UX-Specific Considerations::
597 Example of Binder Output File
599 Elaboration Order Handling in GNAT
602 * Checking the Elaboration Order::
603 * Controlling the Elaboration Order::
604 * Controlling Elaboration in GNAT - Internal Calls::
605 * Controlling Elaboration in GNAT - External Calls::
606 * Default Behavior in GNAT - Ensuring Safety::
607 * Treatment of Pragma Elaborate::
608 * Elaboration Issues for Library Tasks::
609 * Mixing Elaboration Models::
610 * What to Do If the Default Elaboration Behavior Fails::
611 * Elaboration for Dispatching Calls::
612 * Summary of Procedures for Elaboration Control::
613 * Other Elaboration Order Considerations::
615 Overflow Check Handling in GNAT
617 * Overflow Checking Modes in GNAT::
618 * Specifying the Desired Mode::
620 * Implementation Notes::
622 Conditional Compilation
623 * Use of Boolean Constants::
624 * Debugging - A Special Case::
625 * Conditionalizing Declarations::
626 * Use of Alternative Implementations::
631 * Basic Assembler Syntax::
632 * A Simple Example of Inline Assembler::
633 * Output Variables in Inline Assembler::
634 * Input Variables in Inline Assembler::
635 * Inlining Inline Assembler Code::
636 * Other Asm Functionality::
638 Compatibility and Porting Guide
640 * Compatibility with Ada 83::
641 * Compatibility between Ada 95 and Ada 2005::
642 * Implementation-dependent characteristics::
644 @c This brief section is only in the non-VMS version
645 @c The complete chapter on HP Ada issues is in the VMS version
646 * Compatibility with HP Ada 83::
648 * Compatibility with Other Ada Systems::
649 * Representation Clauses::
651 * Transitioning to 64-Bit GNAT for OpenVMS::
655 Microsoft Windows Topics
657 * Using GNAT on Windows::
658 * CONSOLE and WINDOWS subsystems::
660 * Mixed-Language Programming on Windows::
661 * Windows Calling Conventions::
662 * Introduction to Dynamic Link Libraries (DLLs)::
663 * Using DLLs with GNAT::
664 * Building DLLs with GNAT::
665 * GNAT and Windows Resources::
667 * Setting Stack Size from gnatlink::
668 * Setting Heap Size from gnatlink::
675 @node About This Guide
676 @unnumbered About This Guide
680 This guide describes the use of @value{EDITION},
681 a compiler and software development toolset for the full Ada
682 programming language, implemented on OpenVMS for HP's Alpha and
683 Integrity server (I64) platforms.
686 This guide describes the use of @value{EDITION},
687 a compiler and software development
688 toolset for the full Ada programming language.
690 It documents the features of the compiler and tools, and explains
691 how to use them to build Ada applications.
693 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
694 Ada 83 compatibility mode.
695 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
696 but you can override with a compiler switch
697 (@pxref{Compiling Different Versions of Ada})
698 to explicitly specify the language version.
699 Throughout this manual, references to ``Ada'' without a year suffix
700 apply to both the Ada 95 and Ada 2005 versions of the language.
704 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
705 ``GNAT'' in the remainder of this document.
712 * What This Guide Contains::
713 * What You Should Know before Reading This Guide::
714 * Related Information::
718 @node What This Guide Contains
719 @unnumberedsec What This Guide Contains
722 This guide contains the following chapters:
726 @ref{Getting Started with GNAT}, describes how to get started compiling
727 and running Ada programs with the GNAT Ada programming environment.
729 @ref{The GNAT Compilation Model}, describes the compilation model used
733 @ref{Compiling Using gcc}, describes how to compile
734 Ada programs with @command{gcc}, the Ada compiler.
737 @ref{Binding Using gnatbind}, describes how to
738 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
742 @ref{Linking Using gnatlink},
743 describes @command{gnatlink}, a
744 program that provides for linking using the GNAT run-time library to
745 construct a program. @command{gnatlink} can also incorporate foreign language
746 object units into the executable.
749 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
750 utility that automatically determines the set of sources
751 needed by an Ada compilation unit, and executes the necessary compilations
755 @ref{Improving Performance}, shows various techniques for making your
756 Ada program run faster or take less space.
757 It discusses the effect of the compiler's optimization switch and
758 also describes the @command{gnatelim} tool and unused subprogram/data
762 @ref{Renaming Files Using gnatchop}, describes
763 @code{gnatchop}, a utility that allows you to preprocess a file that
764 contains Ada source code, and split it into one or more new files, one
765 for each compilation unit.
768 @ref{Configuration Pragmas}, describes the configuration pragmas
772 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
773 shows how to override the default GNAT file naming conventions,
774 either for an individual unit or globally.
777 @ref{GNAT Project Manager}, describes how to use project files
778 to organize large projects.
781 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
782 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
783 way to navigate through sources.
786 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
787 version of an Ada source file with control over casing, indentation,
788 comment placement, and other elements of program presentation style.
791 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
792 metrics for an Ada source file, such as the number of types and subprograms,
793 and assorted complexity measures.
796 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
797 file name krunching utility, used to handle shortened
798 file names on operating systems with a limit on the length of names.
801 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
802 preprocessor utility that allows a single source file to be used to
803 generate multiple or parameterized source files by means of macro
807 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
808 utility that displays information about compiled units, including dependences
809 on the corresponding sources files, and consistency of compilations.
812 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
813 to delete files that are produced by the compiler, binder and linker.
817 @ref{GNAT and Libraries}, describes the process of creating and using
818 Libraries with GNAT. It also describes how to recompile the GNAT run-time
822 @ref{Using the GNU make Utility}, describes some techniques for using
823 the GNAT toolset in Makefiles.
827 @ref{Memory Management Issues}, describes some useful predefined storage pools
828 and in particular the GNAT Debug Pool facility, which helps detect incorrect
831 It also describes @command{gnatmem}, a utility that monitors dynamic
832 allocation and deallocation and helps detect ``memory leaks''.
836 @ref{Stack Related Facilities}, describes some useful tools associated with
837 stack checking and analysis.
840 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
841 a utility that checks Ada code against a set of rules.
844 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
845 a utility that generates empty but compilable bodies for library units.
848 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
849 a utility that generates unit testing templates for library units.
852 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
853 facilities used in GNAT to declare dimensioned objects, and to verify that
854 uses of these objects are consistent with their given physical dimensions
855 (so that meters cannot be assigned to kilograms, and so on).
858 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
859 generate automatically Ada bindings from C and C++ headers.
862 @ref{Other Utility Programs}, discusses several other GNAT utilities,
863 including @code{gnathtml}.
867 @ref{Code Coverage and Profiling}, describes how to perform a structural
868 coverage and profile the execution of Ada programs.
872 @ref{Running and Debugging Ada Programs}, describes how to run and debug
877 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
878 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
879 developed by Digital Equipment Corporation and currently supported by HP.}
880 for OpenVMS Alpha. This product was formerly known as DEC Ada,
883 historical compatibility reasons, the relevant libraries still use the
888 @ref{Platform-Specific Information for the Run-Time Libraries},
889 describes the various run-time
890 libraries supported by GNAT on various platforms and explains how to
891 choose a particular library.
894 @ref{Example of Binder Output File}, shows the source code for the binder
895 output file for a sample program.
898 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
899 you deal with elaboration order issues.
902 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
903 you deal with arithmetic overflow issues.
906 @ref{Conditional Compilation}, describes how to model conditional compilation,
907 both with Ada in general and with GNAT facilities in particular.
910 @ref{Inline Assembler}, shows how to use the inline assembly facility
914 @ref{Compatibility and Porting Guide}, contains sections on compatibility
915 of GNAT with other Ada development environments (including Ada 83 systems),
916 to assist in porting code from those environments.
920 @ref{Microsoft Windows Topics}, presents information relevant to the
921 Microsoft Windows platform.
925 @c *************************************************
926 @node What You Should Know before Reading This Guide
927 @c *************************************************
928 @unnumberedsec What You Should Know before Reading This Guide
930 @cindex Ada 95 Language Reference Manual
931 @cindex Ada 2005 Language Reference Manual
933 This guide assumes a basic familiarity with the Ada 95 language, as
934 described in the International Standard ANSI/ISO/IEC-8652:1995, January
936 It does not require knowledge of the new features introduced by Ada 2005,
937 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
939 Both reference manuals are included in the GNAT documentation
942 @node Related Information
943 @unnumberedsec Related Information
946 For further information about related tools, refer to the following
951 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
952 Reference Manual}, which contains all reference material for the GNAT
953 implementation of Ada.
957 @cite{Using the GNAT Programming Studio}, which describes the GPS
958 Integrated Development Environment.
961 @cite{GNAT Programming Studio Tutorial}, which introduces the
962 main GPS features through examples.
966 @cite{Ada 95 Reference Manual}, which contains reference
967 material for the Ada 95 programming language.
970 @cite{Ada 2005 Reference Manual}, which contains reference
971 material for the Ada 2005 programming language.
974 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
976 in the GNU:[DOCS] directory,
978 for all details on the use of the GNU source-level debugger.
981 @xref{Top,, The extensible self-documenting text editor, emacs,
984 located in the GNU:[DOCS] directory if the EMACS kit is installed,
986 for full information on the extensible editor and programming
993 @unnumberedsec Conventions
995 @cindex Typographical conventions
998 Following are examples of the typographical and graphic conventions used
1003 @code{Functions}, @command{utility program names}, @code{standard names},
1007 @option{Option flags}
1010 @file{File names}, @samp{button names}, and @samp{field names}.
1013 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1020 @r{[}optional information or parameters@r{]}
1023 Examples are described by text
1025 and then shown this way.
1030 Commands that are entered by the user are preceded in this manual by the
1031 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1032 uses this sequence as a prompt, then the commands will appear exactly as
1033 you see them in the manual. If your system uses some other prompt, then
1034 the command will appear with the @code{$} replaced by whatever prompt
1035 character you are using.
1038 Full file names are shown with the ``@code{/}'' character
1039 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1040 If you are using GNAT on a Windows platform, please note that
1041 the ``@code{\}'' character should be used instead.
1044 @c ****************************
1045 @node Getting Started with GNAT
1046 @chapter Getting Started with GNAT
1049 This chapter describes some simple ways of using GNAT to build
1050 executable Ada programs.
1052 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1053 show how to use the command line environment.
1054 @ref{Introduction to GPS}, provides a brief
1055 introduction to the GNAT Programming Studio, a visually-oriented
1056 Integrated Development Environment for GNAT.
1057 GPS offers a graphical ``look and feel'', support for development in
1058 other programming languages, comprehensive browsing features, and
1059 many other capabilities.
1060 For information on GPS please refer to
1061 @cite{Using the GNAT Programming Studio}.
1066 * Running a Simple Ada Program::
1067 * Running a Program with Multiple Units::
1068 * Using the gnatmake Utility::
1070 * Editing with Emacs::
1073 * Introduction to GPS::
1078 @section Running GNAT
1081 Three steps are needed to create an executable file from an Ada source
1086 The source file(s) must be compiled.
1088 The file(s) must be bound using the GNAT binder.
1090 All appropriate object files must be linked to produce an executable.
1094 All three steps are most commonly handled by using the @command{gnatmake}
1095 utility program that, given the name of the main program, automatically
1096 performs the necessary compilation, binding and linking steps.
1098 @node Running a Simple Ada Program
1099 @section Running a Simple Ada Program
1102 Any text editor may be used to prepare an Ada program.
1104 used, the optional Ada mode may be helpful in laying out the program.)
1106 program text is a normal text file. We will assume in our initial
1107 example that you have used your editor to prepare the following
1108 standard format text file:
1110 @smallexample @c ada
1112 with Ada.Text_IO; use Ada.Text_IO;
1115 Put_Line ("Hello WORLD!");
1121 This file should be named @file{hello.adb}.
1122 With the normal default file naming conventions, GNAT requires
1124 contain a single compilation unit whose file name is the
1126 with periods replaced by hyphens; the
1127 extension is @file{ads} for a
1128 spec and @file{adb} for a body.
1129 You can override this default file naming convention by use of the
1130 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1131 Alternatively, if you want to rename your files according to this default
1132 convention, which is probably more convenient if you will be using GNAT
1133 for all your compilations, then the @code{gnatchop} utility
1134 can be used to generate correctly-named source files
1135 (@pxref{Renaming Files Using gnatchop}).
1137 You can compile the program using the following command (@code{$} is used
1138 as the command prompt in the examples in this document):
1145 @command{gcc} is the command used to run the compiler. This compiler is
1146 capable of compiling programs in several languages, including Ada and
1147 C. It assumes that you have given it an Ada program if the file extension is
1148 either @file{.ads} or @file{.adb}, and it will then call
1149 the GNAT compiler to compile the specified file.
1152 The @option{-c} switch is required. It tells @command{gcc} to only do a
1153 compilation. (For C programs, @command{gcc} can also do linking, but this
1154 capability is not used directly for Ada programs, so the @option{-c}
1155 switch must always be present.)
1158 This compile command generates a file
1159 @file{hello.o}, which is the object
1160 file corresponding to your Ada program. It also generates
1161 an ``Ada Library Information'' file @file{hello.ali},
1162 which contains additional information used to check
1163 that an Ada program is consistent.
1164 To build an executable file,
1165 use @code{gnatbind} to bind the program
1166 and @command{gnatlink} to link it. The
1167 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1168 @file{ALI} file, but the default extension of @file{.ali} can
1169 be omitted. This means that in the most common case, the argument
1170 is simply the name of the main program:
1178 A simpler method of carrying out these steps is to use
1180 a master program that invokes all the required
1181 compilation, binding and linking tools in the correct order. In particular,
1182 @command{gnatmake} automatically recompiles any sources that have been
1183 modified since they were last compiled, or sources that depend
1184 on such modified sources, so that ``version skew'' is avoided.
1185 @cindex Version skew (avoided by @command{gnatmake})
1188 $ gnatmake hello.adb
1192 The result is an executable program called @file{hello}, which can be
1200 assuming that the current directory is on the search path
1201 for executable programs.
1204 and, if all has gone well, you will see
1211 appear in response to this command.
1213 @c ****************************************
1214 @node Running a Program with Multiple Units
1215 @section Running a Program with Multiple Units
1218 Consider a slightly more complicated example that has three files: a
1219 main program, and the spec and body of a package:
1221 @smallexample @c ada
1224 package Greetings is
1229 with Ada.Text_IO; use Ada.Text_IO;
1230 package body Greetings is
1233 Put_Line ("Hello WORLD!");
1236 procedure Goodbye is
1238 Put_Line ("Goodbye WORLD!");
1255 Following the one-unit-per-file rule, place this program in the
1256 following three separate files:
1260 spec of package @code{Greetings}
1263 body of package @code{Greetings}
1266 body of main program
1270 To build an executable version of
1271 this program, we could use four separate steps to compile, bind, and link
1272 the program, as follows:
1276 $ gcc -c greetings.adb
1282 Note that there is no required order of compilation when using GNAT.
1283 In particular it is perfectly fine to compile the main program first.
1284 Also, it is not necessary to compile package specs in the case where
1285 there is an accompanying body; you only need to compile the body. If you want
1286 to submit these files to the compiler for semantic checking and not code
1287 generation, then use the
1288 @option{-gnatc} switch:
1291 $ gcc -c greetings.ads -gnatc
1295 Although the compilation can be done in separate steps as in the
1296 above example, in practice it is almost always more convenient
1297 to use the @command{gnatmake} tool. All you need to know in this case
1298 is the name of the main program's source file. The effect of the above four
1299 commands can be achieved with a single one:
1302 $ gnatmake gmain.adb
1306 In the next section we discuss the advantages of using @command{gnatmake} in
1309 @c *****************************
1310 @node Using the gnatmake Utility
1311 @section Using the @command{gnatmake} Utility
1314 If you work on a program by compiling single components at a time using
1315 @command{gcc}, you typically keep track of the units you modify. In order to
1316 build a consistent system, you compile not only these units, but also any
1317 units that depend on the units you have modified.
1318 For example, in the preceding case,
1319 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1320 you edit @file{greetings.ads}, you must recompile both
1321 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1322 units that depend on @file{greetings.ads}.
1324 @code{gnatbind} will warn you if you forget one of these compilation
1325 steps, so that it is impossible to generate an inconsistent program as a
1326 result of forgetting to do a compilation. Nevertheless it is tedious and
1327 error-prone to keep track of dependencies among units.
1328 One approach to handle the dependency-bookkeeping is to use a
1329 makefile. However, makefiles present maintenance problems of their own:
1330 if the dependencies change as you change the program, you must make
1331 sure that the makefile is kept up-to-date manually, which is also an
1332 error-prone process.
1334 The @command{gnatmake} utility takes care of these details automatically.
1335 Invoke it using either one of the following forms:
1338 $ gnatmake gmain.adb
1339 $ gnatmake ^gmain^GMAIN^
1343 The argument is the name of the file containing the main program;
1344 you may omit the extension. @command{gnatmake}
1345 examines the environment, automatically recompiles any files that need
1346 recompiling, and binds and links the resulting set of object files,
1347 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1348 In a large program, it
1349 can be extremely helpful to use @command{gnatmake}, because working out by hand
1350 what needs to be recompiled can be difficult.
1352 Note that @command{gnatmake}
1353 takes into account all the Ada rules that
1354 establish dependencies among units. These include dependencies that result
1355 from inlining subprogram bodies, and from
1356 generic instantiation. Unlike some other
1357 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1358 found by the compiler on a previous compilation, which may possibly
1359 be wrong when sources change. @command{gnatmake} determines the exact set of
1360 dependencies from scratch each time it is run.
1363 @node Editing with Emacs
1364 @section Editing with Emacs
1368 Emacs is an extensible self-documenting text editor that is available in a
1369 separate VMSINSTAL kit.
1371 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1372 click on the Emacs Help menu and run the Emacs Tutorial.
1373 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1374 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1376 Documentation on Emacs and other tools is available in Emacs under the
1377 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1378 use the middle mouse button to select a topic (e.g.@: Emacs).
1380 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1381 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1382 get to the Emacs manual.
1383 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1386 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1387 which is sufficiently extensible to provide for a complete programming
1388 environment and shell for the sophisticated user.
1392 @node Introduction to GPS
1393 @section Introduction to GPS
1394 @cindex GPS (GNAT Programming Studio)
1395 @cindex GNAT Programming Studio (GPS)
1397 Although the command line interface (@command{gnatmake}, etc.) alone
1398 is sufficient, a graphical Interactive Development
1399 Environment can make it easier for you to compose, navigate, and debug
1400 programs. This section describes the main features of GPS
1401 (``GNAT Programming Studio''), the GNAT graphical IDE.
1402 You will see how to use GPS to build and debug an executable, and
1403 you will also learn some of the basics of the GNAT ``project'' facility.
1405 GPS enables you to do much more than is presented here;
1406 e.g., you can produce a call graph, interface to a third-party
1407 Version Control System, and inspect the generated assembly language
1409 Indeed, GPS also supports languages other than Ada.
1410 Such additional information, and an explanation of all of the GPS menu
1411 items. may be found in the on-line help, which includes
1412 a user's guide and a tutorial (these are also accessible from the GNAT
1416 * Building a New Program with GPS::
1417 * Simple Debugging with GPS::
1420 @node Building a New Program with GPS
1421 @subsection Building a New Program with GPS
1423 GPS invokes the GNAT compilation tools using information
1424 contained in a @emph{project} (also known as a @emph{project file}):
1425 a collection of properties such
1426 as source directories, identities of main subprograms, tool switches, etc.,
1427 and their associated values.
1428 See @ref{GNAT Project Manager} for details.
1429 In order to run GPS, you will need to either create a new project
1430 or else open an existing one.
1432 This section will explain how you can use GPS to create a project,
1433 to associate Ada source files with a project, and to build and run
1437 @item @emph{Creating a project}
1439 Invoke GPS, either from the command line or the platform's IDE.
1440 After it starts, GPS will display a ``Welcome'' screen with three
1445 @code{Start with default project in directory}
1448 @code{Create new project with wizard}
1451 @code{Open existing project}
1455 Select @code{Create new project with wizard} and press @code{OK}.
1456 A new window will appear. In the text box labeled with
1457 @code{Enter the name of the project to create}, type @file{sample}
1458 as the project name.
1459 In the next box, browse to choose the directory in which you
1460 would like to create the project file.
1461 After selecting an appropriate directory, press @code{Forward}.
1463 A window will appear with the title
1464 @code{Version Control System Configuration}.
1465 Simply press @code{Forward}.
1467 A window will appear with the title
1468 @code{Please select the source directories for this project}.
1469 The directory that you specified for the project file will be selected
1470 by default as the one to use for sources; simply press @code{Forward}.
1472 A window will appear with the title
1473 @code{Please select the build directory for this project}.
1474 The directory that you specified for the project file will be selected
1475 by default for object files and executables;
1476 simply press @code{Forward}.
1478 A window will appear with the title
1479 @code{Please select the main units for this project}.
1480 You will supply this information later, after creating the source file.
1481 Simply press @code{Forward} for now.
1483 A window will appear with the title
1484 @code{Please select the switches to build the project}.
1485 Press @code{Apply}. This will create a project file named
1486 @file{sample.prj} in the directory that you had specified.
1488 @item @emph{Creating and saving the source file}
1490 After you create the new project, a GPS window will appear, which is
1491 partitioned into two main sections:
1495 A @emph{Workspace area}, initially greyed out, which you will use for
1496 creating and editing source files
1499 Directly below, a @emph{Messages area}, which initially displays a
1500 ``Welcome'' message.
1501 (If the Messages area is not visible, drag its border upward to expand it.)
1505 Select @code{File} on the menu bar, and then the @code{New} command.
1506 The Workspace area will become white, and you can now
1507 enter the source program explicitly.
1508 Type the following text
1510 @smallexample @c ada
1512 with Ada.Text_IO; use Ada.Text_IO;
1515 Put_Line("Hello from GPS!");
1521 Select @code{File}, then @code{Save As}, and enter the source file name
1523 The file will be saved in the same directory you specified as the
1524 location of the default project file.
1526 @item @emph{Updating the project file}
1528 You need to add the new source file to the project.
1530 the @code{Project} menu and then @code{Edit project properties}.
1531 Click the @code{Main files} tab on the left, and then the
1533 Choose @file{hello.adb} from the list, and press @code{Open}.
1534 The project settings window will reflect this action.
1537 @item @emph{Building and running the program}
1539 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1540 and select @file{hello.adb}.
1541 The Messages window will display the resulting invocations of @command{gcc},
1542 @command{gnatbind}, and @command{gnatlink}
1543 (reflecting the default switch settings from the
1544 project file that you created) and then a ``successful compilation/build''
1547 To run the program, choose the @code{Build} menu, then @code{Run}, and
1548 select @command{hello}.
1549 An @emph{Arguments Selection} window will appear.
1550 There are no command line arguments, so just click @code{OK}.
1552 The Messages window will now display the program's output (the string
1553 @code{Hello from GPS}), and at the bottom of the GPS window a status
1554 update is displayed (@code{Run: hello}).
1555 Close the GPS window (or select @code{File}, then @code{Exit}) to
1556 terminate this GPS session.
1559 @node Simple Debugging with GPS
1560 @subsection Simple Debugging with GPS
1562 This section illustrates basic debugging techniques (setting breakpoints,
1563 examining/modifying variables, single stepping).
1566 @item @emph{Opening a project}
1568 Start GPS and select @code{Open existing project}; browse to
1569 specify the project file @file{sample.prj} that you had created in the
1572 @item @emph{Creating a source file}
1574 Select @code{File}, then @code{New}, and type in the following program:
1576 @smallexample @c ada
1578 with Ada.Text_IO; use Ada.Text_IO;
1579 procedure Example is
1580 Line : String (1..80);
1583 Put_Line("Type a line of text at each prompt; an empty line to exit");
1587 Put_Line (Line (1..N) );
1595 Select @code{File}, then @code{Save as}, and enter the file name
1598 @item @emph{Updating the project file}
1600 Add @code{Example} as a new main unit for the project:
1603 Select @code{Project}, then @code{Edit Project Properties}.
1606 Select the @code{Main files} tab, click @code{Add}, then
1607 select the file @file{example.adb} from the list, and
1609 You will see the file name appear in the list of main units
1615 @item @emph{Building/running the executable}
1617 To build the executable
1618 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1620 Run the program to see its effect (in the Messages area).
1621 Each line that you enter is displayed; an empty line will
1622 cause the loop to exit and the program to terminate.
1624 @item @emph{Debugging the program}
1626 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1627 which are required for debugging, are on by default when you create
1629 Thus unless you intentionally remove these settings, you will be able
1630 to debug any program that you develop using GPS.
1633 @item @emph{Initializing}
1635 Select @code{Debug}, then @code{Initialize}, then @file{example}
1637 @item @emph{Setting a breakpoint}
1639 After performing the initialization step, you will observe a small
1640 icon to the right of each line number.
1641 This serves as a toggle for breakpoints; clicking the icon will
1642 set a breakpoint at the corresponding line (the icon will change to
1643 a red circle with an ``x''), and clicking it again
1644 will remove the breakpoint / reset the icon.
1646 For purposes of this example, set a breakpoint at line 10 (the
1647 statement @code{Put_Line@ (Line@ (1..N));}
1649 @item @emph{Starting program execution}
1651 Select @code{Debug}, then @code{Run}. When the
1652 @code{Program Arguments} window appears, click @code{OK}.
1653 A console window will appear; enter some line of text,
1654 e.g.@: @code{abcde}, at the prompt.
1655 The program will pause execution when it gets to the
1656 breakpoint, and the corresponding line is highlighted.
1658 @item @emph{Examining a variable}
1660 Move the mouse over one of the occurrences of the variable @code{N}.
1661 You will see the value (5) displayed, in ``tool tip'' fashion.
1662 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1663 You will see information about @code{N} appear in the @code{Debugger Data}
1664 pane, showing the value as 5.
1666 @item @emph{Assigning a new value to a variable}
1668 Right click on the @code{N} in the @code{Debugger Data} pane, and
1669 select @code{Set value of N}.
1670 When the input window appears, enter the value @code{4} and click
1672 This value does not automatically appear in the @code{Debugger Data}
1673 pane; to see it, right click again on the @code{N} in the
1674 @code{Debugger Data} pane and select @code{Update value}.
1675 The new value, 4, will appear in red.
1677 @item @emph{Single stepping}
1679 Select @code{Debug}, then @code{Next}.
1680 This will cause the next statement to be executed, in this case the
1681 call of @code{Put_Line} with the string slice.
1682 Notice in the console window that the displayed string is simply
1683 @code{abcd} and not @code{abcde} which you had entered.
1684 This is because the upper bound of the slice is now 4 rather than 5.
1686 @item @emph{Removing a breakpoint}
1688 Toggle the breakpoint icon at line 10.
1690 @item @emph{Resuming execution from a breakpoint}
1692 Select @code{Debug}, then @code{Continue}.
1693 The program will reach the next iteration of the loop, and
1694 wait for input after displaying the prompt.
1695 This time, just hit the @kbd{Enter} key.
1696 The value of @code{N} will be 0, and the program will terminate.
1697 The console window will disappear.
1702 @node The GNAT Compilation Model
1703 @chapter The GNAT Compilation Model
1704 @cindex GNAT compilation model
1705 @cindex Compilation model
1708 * Source Representation::
1709 * Foreign Language Representation::
1710 * File Naming Rules::
1711 * Using Other File Names::
1712 * Alternative File Naming Schemes::
1713 * Generating Object Files::
1714 * Source Dependencies::
1715 * The Ada Library Information Files::
1716 * Binding an Ada Program::
1717 * Mixed Language Programming::
1719 * Building Mixed Ada & C++ Programs::
1720 * Comparison between GNAT and C/C++ Compilation Models::
1722 * Comparison between GNAT and Conventional Ada Library Models::
1724 * Placement of temporary files::
1729 This chapter describes the compilation model used by GNAT. Although
1730 similar to that used by other languages, such as C and C++, this model
1731 is substantially different from the traditional Ada compilation models,
1732 which are based on a library. The model is initially described without
1733 reference to the library-based model. If you have not previously used an
1734 Ada compiler, you need only read the first part of this chapter. The
1735 last section describes and discusses the differences between the GNAT
1736 model and the traditional Ada compiler models. If you have used other
1737 Ada compilers, this section will help you to understand those
1738 differences, and the advantages of the GNAT model.
1740 @node Source Representation
1741 @section Source Representation
1745 Ada source programs are represented in standard text files, using
1746 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1747 7-bit ASCII set, plus additional characters used for
1748 representing foreign languages (@pxref{Foreign Language Representation}
1749 for support of non-USA character sets). The format effector characters
1750 are represented using their standard ASCII encodings, as follows:
1755 Vertical tab, @code{16#0B#}
1759 Horizontal tab, @code{16#09#}
1763 Carriage return, @code{16#0D#}
1767 Line feed, @code{16#0A#}
1771 Form feed, @code{16#0C#}
1775 Source files are in standard text file format. In addition, GNAT will
1776 recognize a wide variety of stream formats, in which the end of
1777 physical lines is marked by any of the following sequences:
1778 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1779 in accommodating files that are imported from other operating systems.
1781 @cindex End of source file
1782 @cindex Source file, end
1784 The end of a source file is normally represented by the physical end of
1785 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1786 recognized as signalling the end of the source file. Again, this is
1787 provided for compatibility with other operating systems where this
1788 code is used to represent the end of file.
1790 Each file contains a single Ada compilation unit, including any pragmas
1791 associated with the unit. For example, this means you must place a
1792 package declaration (a package @dfn{spec}) and the corresponding body in
1793 separate files. An Ada @dfn{compilation} (which is a sequence of
1794 compilation units) is represented using a sequence of files. Similarly,
1795 you will place each subunit or child unit in a separate file.
1797 @node Foreign Language Representation
1798 @section Foreign Language Representation
1801 GNAT supports the standard character sets defined in Ada as well as
1802 several other non-standard character sets for use in localized versions
1803 of the compiler (@pxref{Character Set Control}).
1806 * Other 8-Bit Codes::
1807 * Wide Character Encodings::
1815 The basic character set is Latin-1. This character set is defined by ISO
1816 standard 8859, part 1. The lower half (character codes @code{16#00#}
1817 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1818 half is used to represent additional characters. These include extended letters
1819 used by European languages, such as French accents, the vowels with umlauts
1820 used in German, and the extra letter A-ring used in Swedish.
1822 @findex Ada.Characters.Latin_1
1823 For a complete list of Latin-1 codes and their encodings, see the source
1824 file of library unit @code{Ada.Characters.Latin_1} in file
1825 @file{a-chlat1.ads}.
1826 You may use any of these extended characters freely in character or
1827 string literals. In addition, the extended characters that represent
1828 letters can be used in identifiers.
1830 @node Other 8-Bit Codes
1831 @subsection Other 8-Bit Codes
1834 GNAT also supports several other 8-bit coding schemes:
1837 @item ISO 8859-2 (Latin-2)
1840 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1843 @item ISO 8859-3 (Latin-3)
1846 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1849 @item ISO 8859-4 (Latin-4)
1852 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1855 @item ISO 8859-5 (Cyrillic)
1858 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1859 lowercase equivalence.
1861 @item ISO 8859-15 (Latin-9)
1864 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1865 lowercase equivalence
1867 @item IBM PC (code page 437)
1868 @cindex code page 437
1869 This code page is the normal default for PCs in the U.S. It corresponds
1870 to the original IBM PC character set. This set has some, but not all, of
1871 the extended Latin-1 letters, but these letters do not have the same
1872 encoding as Latin-1. In this mode, these letters are allowed in
1873 identifiers with uppercase and lowercase equivalence.
1875 @item IBM PC (code page 850)
1876 @cindex code page 850
1877 This code page is a modification of 437 extended to include all the
1878 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1879 mode, all these letters are allowed in identifiers with uppercase and
1880 lowercase equivalence.
1882 @item Full Upper 8-bit
1883 Any character in the range 80-FF allowed in identifiers, and all are
1884 considered distinct. In other words, there are no uppercase and lowercase
1885 equivalences in this range. This is useful in conjunction with
1886 certain encoding schemes used for some foreign character sets (e.g.,
1887 the typical method of representing Chinese characters on the PC).
1890 No upper-half characters in the range 80-FF are allowed in identifiers.
1891 This gives Ada 83 compatibility for identifier names.
1895 For precise data on the encodings permitted, and the uppercase and lowercase
1896 equivalences that are recognized, see the file @file{csets.adb} in
1897 the GNAT compiler sources. You will need to obtain a full source release
1898 of GNAT to obtain this file.
1900 @node Wide Character Encodings
1901 @subsection Wide Character Encodings
1904 GNAT allows wide character codes to appear in character and string
1905 literals, and also optionally in identifiers, by means of the following
1906 possible encoding schemes:
1911 In this encoding, a wide character is represented by the following five
1919 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1920 characters (using uppercase letters) of the wide character code. For
1921 example, ESC A345 is used to represent the wide character with code
1923 This scheme is compatible with use of the full Wide_Character set.
1925 @item Upper-Half Coding
1926 @cindex Upper-Half Coding
1927 The wide character with encoding @code{16#abcd#} where the upper bit is on
1928 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1929 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1930 character, but is not required to be in the upper half. This method can
1931 be also used for shift-JIS or EUC, where the internal coding matches the
1934 @item Shift JIS Coding
1935 @cindex Shift JIS Coding
1936 A wide character is represented by a two-character sequence,
1938 @code{16#cd#}, with the restrictions described for upper-half encoding as
1939 described above. The internal character code is the corresponding JIS
1940 character according to the standard algorithm for Shift-JIS
1941 conversion. Only characters defined in the JIS code set table can be
1942 used with this encoding method.
1946 A wide character is represented by a two-character sequence
1948 @code{16#cd#}, with both characters being in the upper half. The internal
1949 character code is the corresponding JIS character according to the EUC
1950 encoding algorithm. Only characters defined in the JIS code set table
1951 can be used with this encoding method.
1954 A wide character is represented using
1955 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1956 10646-1/Am.2. Depending on the character value, the representation
1957 is a one, two, or three byte sequence:
1962 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1963 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1964 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1969 where the @var{xxx} bits correspond to the left-padded bits of the
1970 16-bit character value. Note that all lower half ASCII characters
1971 are represented as ASCII bytes and all upper half characters and
1972 other wide characters are represented as sequences of upper-half
1973 (The full UTF-8 scheme allows for encoding 31-bit characters as
1974 6-byte sequences, but in this implementation, all UTF-8 sequences
1975 of four or more bytes length will be treated as illegal).
1976 @item Brackets Coding
1977 In this encoding, a wide character is represented by the following eight
1985 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1986 characters (using uppercase letters) of the wide character code. For
1987 example, [``A345''] is used to represent the wide character with code
1988 @code{16#A345#}. It is also possible (though not required) to use the
1989 Brackets coding for upper half characters. For example, the code
1990 @code{16#A3#} can be represented as @code{[``A3'']}.
1992 This scheme is compatible with use of the full Wide_Character set,
1993 and is also the method used for wide character encoding in the standard
1994 ACVC (Ada Compiler Validation Capability) test suite distributions.
1999 Note: Some of these coding schemes do not permit the full use of the
2000 Ada character set. For example, neither Shift JIS, nor EUC allow the
2001 use of the upper half of the Latin-1 set.
2003 @node File Naming Rules
2004 @section File Naming Rules
2007 The default file name is determined by the name of the unit that the
2008 file contains. The name is formed by taking the full expanded name of
2009 the unit and replacing the separating dots with hyphens and using
2010 ^lowercase^uppercase^ for all letters.
2012 An exception arises if the file name generated by the above rules starts
2013 with one of the characters
2015 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2018 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2020 and the second character is a
2021 minus. In this case, the character ^tilde^dollar sign^ is used in place
2022 of the minus. The reason for this special rule is to avoid clashes with
2023 the standard names for child units of the packages System, Ada,
2024 Interfaces, and GNAT, which use the prefixes
2026 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2029 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2033 The file extension is @file{.ads} for a spec and
2034 @file{.adb} for a body. The following list shows some
2035 examples of these rules.
2042 @item arith_functions.ads
2043 Arith_Functions (package spec)
2044 @item arith_functions.adb
2045 Arith_Functions (package body)
2047 Func.Spec (child package spec)
2049 Func.Spec (child package body)
2051 Sub (subunit of Main)
2052 @item ^a~bad.adb^A$BAD.ADB^
2053 A.Bad (child package body)
2057 Following these rules can result in excessively long
2058 file names if corresponding
2059 unit names are long (for example, if child units or subunits are
2060 heavily nested). An option is available to shorten such long file names
2061 (called file name ``krunching''). This may be particularly useful when
2062 programs being developed with GNAT are to be used on operating systems
2063 with limited file name lengths. @xref{Using gnatkr}.
2065 Of course, no file shortening algorithm can guarantee uniqueness over
2066 all possible unit names; if file name krunching is used, it is your
2067 responsibility to ensure no name clashes occur. Alternatively you
2068 can specify the exact file names that you want used, as described
2069 in the next section. Finally, if your Ada programs are migrating from a
2070 compiler with a different naming convention, you can use the gnatchop
2071 utility to produce source files that follow the GNAT naming conventions.
2072 (For details @pxref{Renaming Files Using gnatchop}.)
2074 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2075 systems, case is not significant. So for example on @code{Windows XP}
2076 if the canonical name is @code{main-sub.adb}, you can use the file name
2077 @code{Main-Sub.adb} instead. However, case is significant for other
2078 operating systems, so for example, if you want to use other than
2079 canonically cased file names on a Unix system, you need to follow
2080 the procedures described in the next section.
2082 @node Using Other File Names
2083 @section Using Other File Names
2087 In the previous section, we have described the default rules used by
2088 GNAT to determine the file name in which a given unit resides. It is
2089 often convenient to follow these default rules, and if you follow them,
2090 the compiler knows without being explicitly told where to find all
2093 However, in some cases, particularly when a program is imported from
2094 another Ada compiler environment, it may be more convenient for the
2095 programmer to specify which file names contain which units. GNAT allows
2096 arbitrary file names to be used by means of the Source_File_Name pragma.
2097 The form of this pragma is as shown in the following examples:
2098 @cindex Source_File_Name pragma
2100 @smallexample @c ada
2102 pragma Source_File_Name (My_Utilities.Stacks,
2103 Spec_File_Name => "myutilst_a.ada");
2104 pragma Source_File_name (My_Utilities.Stacks,
2105 Body_File_Name => "myutilst.ada");
2110 As shown in this example, the first argument for the pragma is the unit
2111 name (in this example a child unit). The second argument has the form
2112 of a named association. The identifier
2113 indicates whether the file name is for a spec or a body;
2114 the file name itself is given by a string literal.
2116 The source file name pragma is a configuration pragma, which means that
2117 normally it will be placed in the @file{gnat.adc}
2118 file used to hold configuration
2119 pragmas that apply to a complete compilation environment.
2120 For more details on how the @file{gnat.adc} file is created and used
2121 see @ref{Handling of Configuration Pragmas}.
2122 @cindex @file{gnat.adc}
2125 GNAT allows completely arbitrary file names to be specified using the
2126 source file name pragma. However, if the file name specified has an
2127 extension other than @file{.ads} or @file{.adb} it is necessary to use
2128 a special syntax when compiling the file. The name in this case must be
2129 preceded by the special sequence @option{-x} followed by a space and the name
2130 of the language, here @code{ada}, as in:
2133 $ gcc -c -x ada peculiar_file_name.sim
2138 @command{gnatmake} handles non-standard file names in the usual manner (the
2139 non-standard file name for the main program is simply used as the
2140 argument to gnatmake). Note that if the extension is also non-standard,
2141 then it must be included in the @command{gnatmake} command, it may not
2144 @node Alternative File Naming Schemes
2145 @section Alternative File Naming Schemes
2146 @cindex File naming schemes, alternative
2149 In the previous section, we described the use of the @code{Source_File_Name}
2150 pragma to allow arbitrary names to be assigned to individual source files.
2151 However, this approach requires one pragma for each file, and especially in
2152 large systems can result in very long @file{gnat.adc} files, and also create
2153 a maintenance problem.
2155 GNAT also provides a facility for specifying systematic file naming schemes
2156 other than the standard default naming scheme previously described. An
2157 alternative scheme for naming is specified by the use of
2158 @code{Source_File_Name} pragmas having the following format:
2159 @cindex Source_File_Name pragma
2161 @smallexample @c ada
2162 pragma Source_File_Name (
2163 Spec_File_Name => FILE_NAME_PATTERN
2164 @r{[},Casing => CASING_SPEC@r{]}
2165 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2167 pragma Source_File_Name (
2168 Body_File_Name => FILE_NAME_PATTERN
2169 @r{[},Casing => CASING_SPEC@r{]}
2170 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2172 pragma Source_File_Name (
2173 Subunit_File_Name => FILE_NAME_PATTERN
2174 @r{[},Casing => CASING_SPEC@r{]}
2175 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2177 FILE_NAME_PATTERN ::= STRING_LITERAL
2178 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2182 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2183 It contains a single asterisk character, and the unit name is substituted
2184 systematically for this asterisk. The optional parameter
2185 @code{Casing} indicates
2186 whether the unit name is to be all upper-case letters, all lower-case letters,
2187 or mixed-case. If no
2188 @code{Casing} parameter is used, then the default is all
2189 ^lower-case^upper-case^.
2191 The optional @code{Dot_Replacement} string is used to replace any periods
2192 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2193 argument is used then separating dots appear unchanged in the resulting
2195 Although the above syntax indicates that the
2196 @code{Casing} argument must appear
2197 before the @code{Dot_Replacement} argument, but it
2198 is also permissible to write these arguments in the opposite order.
2200 As indicated, it is possible to specify different naming schemes for
2201 bodies, specs, and subunits. Quite often the rule for subunits is the
2202 same as the rule for bodies, in which case, there is no need to give
2203 a separate @code{Subunit_File_Name} rule, and in this case the
2204 @code{Body_File_name} rule is used for subunits as well.
2206 The separate rule for subunits can also be used to implement the rather
2207 unusual case of a compilation environment (e.g.@: a single directory) which
2208 contains a subunit and a child unit with the same unit name. Although
2209 both units cannot appear in the same partition, the Ada Reference Manual
2210 allows (but does not require) the possibility of the two units coexisting
2211 in the same environment.
2213 The file name translation works in the following steps:
2218 If there is a specific @code{Source_File_Name} pragma for the given unit,
2219 then this is always used, and any general pattern rules are ignored.
2222 If there is a pattern type @code{Source_File_Name} pragma that applies to
2223 the unit, then the resulting file name will be used if the file exists. If
2224 more than one pattern matches, the latest one will be tried first, and the
2225 first attempt resulting in a reference to a file that exists will be used.
2228 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2229 for which the corresponding file exists, then the standard GNAT default
2230 naming rules are used.
2235 As an example of the use of this mechanism, consider a commonly used scheme
2236 in which file names are all lower case, with separating periods copied
2237 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2238 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2241 @smallexample @c ada
2242 pragma Source_File_Name
2243 (Spec_File_Name => "*.1.ada");
2244 pragma Source_File_Name
2245 (Body_File_Name => "*.2.ada");
2249 The default GNAT scheme is actually implemented by providing the following
2250 default pragmas internally:
2252 @smallexample @c ada
2253 pragma Source_File_Name
2254 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2255 pragma Source_File_Name
2256 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2260 Our final example implements a scheme typically used with one of the
2261 Ada 83 compilers, where the separator character for subunits was ``__''
2262 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2263 by adding @file{.ADA}, and subunits by
2264 adding @file{.SEP}. All file names were
2265 upper case. Child units were not present of course since this was an
2266 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2267 the same double underscore separator for child units.
2269 @smallexample @c ada
2270 pragma Source_File_Name
2271 (Spec_File_Name => "*_.ADA",
2272 Dot_Replacement => "__",
2273 Casing = Uppercase);
2274 pragma Source_File_Name
2275 (Body_File_Name => "*.ADA",
2276 Dot_Replacement => "__",
2277 Casing = Uppercase);
2278 pragma Source_File_Name
2279 (Subunit_File_Name => "*.SEP",
2280 Dot_Replacement => "__",
2281 Casing = Uppercase);
2284 @node Generating Object Files
2285 @section Generating Object Files
2288 An Ada program consists of a set of source files, and the first step in
2289 compiling the program is to generate the corresponding object files.
2290 These are generated by compiling a subset of these source files.
2291 The files you need to compile are the following:
2295 If a package spec has no body, compile the package spec to produce the
2296 object file for the package.
2299 If a package has both a spec and a body, compile the body to produce the
2300 object file for the package. The source file for the package spec need
2301 not be compiled in this case because there is only one object file, which
2302 contains the code for both the spec and body of the package.
2305 For a subprogram, compile the subprogram body to produce the object file
2306 for the subprogram. The spec, if one is present, is as usual in a
2307 separate file, and need not be compiled.
2311 In the case of subunits, only compile the parent unit. A single object
2312 file is generated for the entire subunit tree, which includes all the
2316 Compile child units independently of their parent units
2317 (though, of course, the spec of all the ancestor unit must be present in order
2318 to compile a child unit).
2322 Compile generic units in the same manner as any other units. The object
2323 files in this case are small dummy files that contain at most the
2324 flag used for elaboration checking. This is because GNAT always handles generic
2325 instantiation by means of macro expansion. However, it is still necessary to
2326 compile generic units, for dependency checking and elaboration purposes.
2330 The preceding rules describe the set of files that must be compiled to
2331 generate the object files for a program. Each object file has the same
2332 name as the corresponding source file, except that the extension is
2335 You may wish to compile other files for the purpose of checking their
2336 syntactic and semantic correctness. For example, in the case where a
2337 package has a separate spec and body, you would not normally compile the
2338 spec. However, it is convenient in practice to compile the spec to make
2339 sure it is error-free before compiling clients of this spec, because such
2340 compilations will fail if there is an error in the spec.
2342 GNAT provides an option for compiling such files purely for the
2343 purposes of checking correctness; such compilations are not required as
2344 part of the process of building a program. To compile a file in this
2345 checking mode, use the @option{-gnatc} switch.
2347 @node Source Dependencies
2348 @section Source Dependencies
2351 A given object file clearly depends on the source file which is compiled
2352 to produce it. Here we are using @dfn{depends} in the sense of a typical
2353 @code{make} utility; in other words, an object file depends on a source
2354 file if changes to the source file require the object file to be
2356 In addition to this basic dependency, a given object may depend on
2357 additional source files as follows:
2361 If a file being compiled @code{with}'s a unit @var{X}, the object file
2362 depends on the file containing the spec of unit @var{X}. This includes
2363 files that are @code{with}'ed implicitly either because they are parents
2364 of @code{with}'ed child units or they are run-time units required by the
2365 language constructs used in a particular unit.
2368 If a file being compiled instantiates a library level generic unit, the
2369 object file depends on both the spec and body files for this generic
2373 If a file being compiled instantiates a generic unit defined within a
2374 package, the object file depends on the body file for the package as
2375 well as the spec file.
2379 @cindex @option{-gnatn} switch
2380 If a file being compiled contains a call to a subprogram for which
2381 pragma @code{Inline} applies and inlining is activated with the
2382 @option{-gnatn} switch, the object file depends on the file containing the
2383 body of this subprogram as well as on the file containing the spec. Note
2384 that for inlining to actually occur as a result of the use of this switch,
2385 it is necessary to compile in optimizing mode.
2387 @cindex @option{-gnatN} switch
2388 The use of @option{-gnatN} activates inlining optimization
2389 that is performed by the front end of the compiler. This inlining does
2390 not require that the code generation be optimized. Like @option{-gnatn},
2391 the use of this switch generates additional dependencies.
2393 When using a gcc-based back end (in practice this means using any version
2394 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2395 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2396 Historically front end inlining was more extensive than the gcc back end
2397 inlining, but that is no longer the case.
2400 If an object file @file{O} depends on the proper body of a subunit through
2401 inlining or instantiation, it depends on the parent unit of the subunit.
2402 This means that any modification of the parent unit or one of its subunits
2403 affects the compilation of @file{O}.
2406 The object file for a parent unit depends on all its subunit body files.
2409 The previous two rules meant that for purposes of computing dependencies and
2410 recompilation, a body and all its subunits are treated as an indivisible whole.
2413 These rules are applied transitively: if unit @code{A} @code{with}'s
2414 unit @code{B}, whose elaboration calls an inlined procedure in package
2415 @code{C}, the object file for unit @code{A} will depend on the body of
2416 @code{C}, in file @file{c.adb}.
2418 The set of dependent files described by these rules includes all the
2419 files on which the unit is semantically dependent, as dictated by the
2420 Ada language standard. However, it is a superset of what the
2421 standard describes, because it includes generic, inline, and subunit
2424 An object file must be recreated by recompiling the corresponding source
2425 file if any of the source files on which it depends are modified. For
2426 example, if the @code{make} utility is used to control compilation,
2427 the rule for an Ada object file must mention all the source files on
2428 which the object file depends, according to the above definition.
2429 The determination of the necessary
2430 recompilations is done automatically when one uses @command{gnatmake}.
2433 @node The Ada Library Information Files
2434 @section The Ada Library Information Files
2435 @cindex Ada Library Information files
2436 @cindex @file{ALI} files
2439 Each compilation actually generates two output files. The first of these
2440 is the normal object file that has a @file{.o} extension. The second is a
2441 text file containing full dependency information. It has the same
2442 name as the source file, but an @file{.ali} extension.
2443 This file is known as the Ada Library Information (@file{ALI}) file.
2444 The following information is contained in the @file{ALI} file.
2448 Version information (indicates which version of GNAT was used to compile
2449 the unit(s) in question)
2452 Main program information (including priority and time slice settings,
2453 as well as the wide character encoding used during compilation).
2456 List of arguments used in the @command{gcc} command for the compilation
2459 Attributes of the unit, including configuration pragmas used, an indication
2460 of whether the compilation was successful, exception model used etc.
2463 A list of relevant restrictions applying to the unit (used for consistency)
2467 Categorization information (e.g.@: use of pragma @code{Pure}).
2470 Information on all @code{with}'ed units, including presence of
2471 @code{Elaborate} or @code{Elaborate_All} pragmas.
2474 Information from any @code{Linker_Options} pragmas used in the unit
2477 Information on the use of @code{Body_Version} or @code{Version}
2478 attributes in the unit.
2481 Dependency information. This is a list of files, together with
2482 time stamp and checksum information. These are files on which
2483 the unit depends in the sense that recompilation is required
2484 if any of these units are modified.
2487 Cross-reference data. Contains information on all entities referenced
2488 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2489 provide cross-reference information.
2494 For a full detailed description of the format of the @file{ALI} file,
2495 see the source of the body of unit @code{Lib.Writ}, contained in file
2496 @file{lib-writ.adb} in the GNAT compiler sources.
2498 @node Binding an Ada Program
2499 @section Binding an Ada Program
2502 When using languages such as C and C++, once the source files have been
2503 compiled the only remaining step in building an executable program
2504 is linking the object modules together. This means that it is possible to
2505 link an inconsistent version of a program, in which two units have
2506 included different versions of the same header.
2508 The rules of Ada do not permit such an inconsistent program to be built.
2509 For example, if two clients have different versions of the same package,
2510 it is illegal to build a program containing these two clients.
2511 These rules are enforced by the GNAT binder, which also determines an
2512 elaboration order consistent with the Ada rules.
2514 The GNAT binder is run after all the object files for a program have
2515 been created. It is given the name of the main program unit, and from
2516 this it determines the set of units required by the program, by reading the
2517 corresponding ALI files. It generates error messages if the program is
2518 inconsistent or if no valid order of elaboration exists.
2520 If no errors are detected, the binder produces a main program, in Ada by
2521 default, that contains calls to the elaboration procedures of those
2522 compilation unit that require them, followed by
2523 a call to the main program. This Ada program is compiled to generate the
2524 object file for the main program. The name of
2525 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2526 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2529 Finally, the linker is used to build the resulting executable program,
2530 using the object from the main program from the bind step as well as the
2531 object files for the Ada units of the program.
2533 @node Mixed Language Programming
2534 @section Mixed Language Programming
2535 @cindex Mixed Language Programming
2538 This section describes how to develop a mixed-language program,
2539 specifically one that comprises units in both Ada and C.
2542 * Interfacing to C::
2543 * Calling Conventions::
2546 @node Interfacing to C
2547 @subsection Interfacing to C
2549 Interfacing Ada with a foreign language such as C involves using
2550 compiler directives to import and/or export entity definitions in each
2551 language---using @code{extern} statements in C, for instance, and the
2552 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2553 A full treatment of these topics is provided in Appendix B, section 1
2554 of the Ada Reference Manual.
2556 There are two ways to build a program using GNAT that contains some Ada
2557 sources and some foreign language sources, depending on whether or not
2558 the main subprogram is written in Ada. Here is a source example with
2559 the main subprogram in Ada:
2565 void print_num (int num)
2567 printf ("num is %d.\n", num);
2573 /* num_from_Ada is declared in my_main.adb */
2574 extern int num_from_Ada;
2578 return num_from_Ada;
2582 @smallexample @c ada
2584 procedure My_Main is
2586 -- Declare then export an Integer entity called num_from_Ada
2587 My_Num : Integer := 10;
2588 pragma Export (C, My_Num, "num_from_Ada");
2590 -- Declare an Ada function spec for Get_Num, then use
2591 -- C function get_num for the implementation.
2592 function Get_Num return Integer;
2593 pragma Import (C, Get_Num, "get_num");
2595 -- Declare an Ada procedure spec for Print_Num, then use
2596 -- C function print_num for the implementation.
2597 procedure Print_Num (Num : Integer);
2598 pragma Import (C, Print_Num, "print_num");
2601 Print_Num (Get_Num);
2607 To build this example, first compile the foreign language files to
2608 generate object files:
2610 ^gcc -c file1.c^gcc -c FILE1.C^
2611 ^gcc -c file2.c^gcc -c FILE2.C^
2615 Then, compile the Ada units to produce a set of object files and ALI
2618 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2622 Run the Ada binder on the Ada main program:
2624 gnatbind my_main.ali
2628 Link the Ada main program, the Ada objects and the other language
2631 gnatlink my_main.ali file1.o file2.o
2635 The last three steps can be grouped in a single command:
2637 gnatmake my_main.adb -largs file1.o file2.o
2640 @cindex Binder output file
2642 If the main program is in a language other than Ada, then you may have
2643 more than one entry point into the Ada subsystem. You must use a special
2644 binder option to generate callable routines that initialize and
2645 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2646 Calls to the initialization and finalization routines must be inserted
2647 in the main program, or some other appropriate point in the code. The
2648 call to initialize the Ada units must occur before the first Ada
2649 subprogram is called, and the call to finalize the Ada units must occur
2650 after the last Ada subprogram returns. The binder will place the
2651 initialization and finalization subprograms into the
2652 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2653 sources. To illustrate, we have the following example:
2657 extern void adainit (void);
2658 extern void adafinal (void);
2659 extern int add (int, int);
2660 extern int sub (int, int);
2662 int main (int argc, char *argv[])
2668 /* Should print "21 + 7 = 28" */
2669 printf ("%d + %d = %d\n", a, b, add (a, b));
2670 /* Should print "21 - 7 = 14" */
2671 printf ("%d - %d = %d\n", a, b, sub (a, b));
2677 @smallexample @c ada
2680 function Add (A, B : Integer) return Integer;
2681 pragma Export (C, Add, "add");
2685 package body Unit1 is
2686 function Add (A, B : Integer) return Integer is
2694 function Sub (A, B : Integer) return Integer;
2695 pragma Export (C, Sub, "sub");
2699 package body Unit2 is
2700 function Sub (A, B : Integer) return Integer is
2709 The build procedure for this application is similar to the last
2710 example's. First, compile the foreign language files to generate object
2713 ^gcc -c main.c^gcc -c main.c^
2717 Next, compile the Ada units to produce a set of object files and ALI
2720 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2721 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2725 Run the Ada binder on every generated ALI file. Make sure to use the
2726 @option{-n} option to specify a foreign main program:
2728 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2732 Link the Ada main program, the Ada objects and the foreign language
2733 objects. You need only list the last ALI file here:
2735 gnatlink unit2.ali main.o -o exec_file
2738 This procedure yields a binary executable called @file{exec_file}.
2742 Depending on the circumstances (for example when your non-Ada main object
2743 does not provide symbol @code{main}), you may also need to instruct the
2744 GNAT linker not to include the standard startup objects by passing the
2745 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2747 @node Calling Conventions
2748 @subsection Calling Conventions
2749 @cindex Foreign Languages
2750 @cindex Calling Conventions
2751 GNAT follows standard calling sequence conventions and will thus interface
2752 to any other language that also follows these conventions. The following
2753 Convention identifiers are recognized by GNAT:
2756 @cindex Interfacing to Ada
2757 @cindex Other Ada compilers
2758 @cindex Convention Ada
2760 This indicates that the standard Ada calling sequence will be
2761 used and all Ada data items may be passed without any limitations in the
2762 case where GNAT is used to generate both the caller and callee. It is also
2763 possible to mix GNAT generated code and code generated by another Ada
2764 compiler. In this case, the data types should be restricted to simple
2765 cases, including primitive types. Whether complex data types can be passed
2766 depends on the situation. Probably it is safe to pass simple arrays, such
2767 as arrays of integers or floats. Records may or may not work, depending
2768 on whether both compilers lay them out identically. Complex structures
2769 involving variant records, access parameters, tasks, or protected types,
2770 are unlikely to be able to be passed.
2772 Note that in the case of GNAT running
2773 on a platform that supports HP Ada 83, a higher degree of compatibility
2774 can be guaranteed, and in particular records are layed out in an identical
2775 manner in the two compilers. Note also that if output from two different
2776 compilers is mixed, the program is responsible for dealing with elaboration
2777 issues. Probably the safest approach is to write the main program in the
2778 version of Ada other than GNAT, so that it takes care of its own elaboration
2779 requirements, and then call the GNAT-generated adainit procedure to ensure
2780 elaboration of the GNAT components. Consult the documentation of the other
2781 Ada compiler for further details on elaboration.
2783 However, it is not possible to mix the tasking run time of GNAT and
2784 HP Ada 83, All the tasking operations must either be entirely within
2785 GNAT compiled sections of the program, or entirely within HP Ada 83
2786 compiled sections of the program.
2788 @cindex Interfacing to Assembly
2789 @cindex Convention Assembler
2791 Specifies assembler as the convention. In practice this has the
2792 same effect as convention Ada (but is not equivalent in the sense of being
2793 considered the same convention).
2795 @cindex Convention Asm
2798 Equivalent to Assembler.
2800 @cindex Interfacing to COBOL
2801 @cindex Convention COBOL
2804 Data will be passed according to the conventions described
2805 in section B.4 of the Ada Reference Manual.
2808 @cindex Interfacing to C
2809 @cindex Convention C
2811 Data will be passed according to the conventions described
2812 in section B.3 of the Ada Reference Manual.
2814 A note on interfacing to a C ``varargs'' function:
2815 @findex C varargs function
2816 @cindex Interfacing to C varargs function
2817 @cindex varargs function interfaces
2821 In C, @code{varargs} allows a function to take a variable number of
2822 arguments. There is no direct equivalent in this to Ada. One
2823 approach that can be used is to create a C wrapper for each
2824 different profile and then interface to this C wrapper. For
2825 example, to print an @code{int} value using @code{printf},
2826 create a C function @code{printfi} that takes two arguments, a
2827 pointer to a string and an int, and calls @code{printf}.
2828 Then in the Ada program, use pragma @code{Import} to
2829 interface to @code{printfi}.
2832 It may work on some platforms to directly interface to
2833 a @code{varargs} function by providing a specific Ada profile
2834 for a particular call. However, this does not work on
2835 all platforms, since there is no guarantee that the
2836 calling sequence for a two argument normal C function
2837 is the same as for calling a @code{varargs} C function with
2838 the same two arguments.
2841 @cindex Convention Default
2846 @cindex Convention External
2853 @cindex Interfacing to C++
2854 @cindex Convention C++
2855 @item C_Plus_Plus (or CPP)
2856 This stands for C++. For most purposes this is identical to C.
2857 See the separate description of the specialized GNAT pragmas relating to
2858 C++ interfacing for further details.
2862 @cindex Interfacing to Fortran
2863 @cindex Convention Fortran
2865 Data will be passed according to the conventions described
2866 in section B.5 of the Ada Reference Manual.
2869 This applies to an intrinsic operation, as defined in the Ada
2870 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2871 this means that the body of the subprogram is provided by the compiler itself,
2872 usually by means of an efficient code sequence, and that the user does not
2873 supply an explicit body for it. In an application program, the pragma may
2874 be applied to the following sets of names:
2878 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2879 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2880 two formal parameters. The
2881 first one must be a signed integer type or a modular type with a binary
2882 modulus, and the second parameter must be of type Natural.
2883 The return type must be the same as the type of the first argument. The size
2884 of this type can only be 8, 16, 32, or 64.
2887 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2888 The corresponding operator declaration must have parameters and result type
2889 that have the same root numeric type (for example, all three are long_float
2890 types). This simplifies the definition of operations that use type checking
2891 to perform dimensional checks:
2893 @smallexample @c ada
2894 type Distance is new Long_Float;
2895 type Time is new Long_Float;
2896 type Velocity is new Long_Float;
2897 function "/" (D : Distance; T : Time)
2899 pragma Import (Intrinsic, "/");
2903 This common idiom is often programmed with a generic definition and an
2904 explicit body. The pragma makes it simpler to introduce such declarations.
2905 It incurs no overhead in compilation time or code size, because it is
2906 implemented as a single machine instruction.
2909 General subprogram entities, to bind an Ada subprogram declaration to
2910 a compiler builtin by name with back-ends where such interfaces are
2911 available. A typical example is the set of ``__builtin'' functions
2912 exposed by the GCC back-end, as in the following example:
2914 @smallexample @c ada
2915 function builtin_sqrt (F : Float) return Float;
2916 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2919 Most of the GCC builtins are accessible this way, and as for other
2920 import conventions (e.g. C), it is the user's responsibility to ensure
2921 that the Ada subprogram profile matches the underlying builtin
2929 @cindex Convention Stdcall
2931 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2932 and specifies that the @code{Stdcall} calling sequence will be used,
2933 as defined by the NT API. Nevertheless, to ease building
2934 cross-platform bindings this convention will be handled as a @code{C} calling
2935 convention on non-Windows platforms.
2938 @cindex Convention DLL
2940 This is equivalent to @code{Stdcall}.
2943 @cindex Convention Win32
2945 This is equivalent to @code{Stdcall}.
2949 @cindex Convention Stubbed
2951 This is a special convention that indicates that the compiler
2952 should provide a stub body that raises @code{Program_Error}.
2956 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2957 that can be used to parameterize conventions and allow additional synonyms
2958 to be specified. For example if you have legacy code in which the convention
2959 identifier Fortran77 was used for Fortran, you can use the configuration
2962 @smallexample @c ada
2963 pragma Convention_Identifier (Fortran77, Fortran);
2967 And from now on the identifier Fortran77 may be used as a convention
2968 identifier (for example in an @code{Import} pragma) with the same
2972 @node Building Mixed Ada & C++ Programs
2973 @section Building Mixed Ada and C++ Programs
2976 A programmer inexperienced with mixed-language development may find that
2977 building an application containing both Ada and C++ code can be a
2978 challenge. This section gives a few
2979 hints that should make this task easier. The first section addresses
2980 the differences between interfacing with C and interfacing with C++.
2982 looks into the delicate problem of linking the complete application from
2983 its Ada and C++ parts. The last section gives some hints on how the GNAT
2984 run-time library can be adapted in order to allow inter-language dispatching
2985 with a new C++ compiler.
2988 * Interfacing to C++::
2989 * Linking a Mixed C++ & Ada Program::
2990 * A Simple Example::
2991 * Interfacing with C++ constructors::
2992 * Interfacing with C++ at the Class Level::
2995 @node Interfacing to C++
2996 @subsection Interfacing to C++
2999 GNAT supports interfacing with the G++ compiler (or any C++ compiler
3000 generating code that is compatible with the G++ Application Binary
3001 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
3004 Interfacing can be done at 3 levels: simple data, subprograms, and
3005 classes. In the first two cases, GNAT offers a specific @code{Convention
3006 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
3007 Usually, C++ mangles the names of subprograms. To generate proper mangled
3008 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
3009 This problem can also be addressed manually in two ways:
3013 by modifying the C++ code in order to force a C convention using
3014 the @code{extern "C"} syntax.
3017 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3018 Link_Name argument of the pragma import.
3022 Interfacing at the class level can be achieved by using the GNAT specific
3023 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
3024 gnat_rm, GNAT Reference Manual}, for additional information.
3026 @node Linking a Mixed C++ & Ada Program
3027 @subsection Linking a Mixed C++ & Ada Program
3030 Usually the linker of the C++ development system must be used to link
3031 mixed applications because most C++ systems will resolve elaboration
3032 issues (such as calling constructors on global class instances)
3033 transparently during the link phase. GNAT has been adapted to ease the
3034 use of a foreign linker for the last phase. Three cases can be
3039 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3040 The C++ linker can simply be called by using the C++ specific driver
3043 Note that if the C++ code uses inline functions, you will need to
3044 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3045 order to provide an existing function implementation that the Ada code can
3049 $ g++ -c -fkeep-inline-functions file1.C
3050 $ g++ -c -fkeep-inline-functions file2.C
3051 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3055 Using GNAT and G++ from two different GCC installations: If both
3056 compilers are on the @env{PATH}, the previous method may be used. It is
3057 important to note that environment variables such as
3058 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3059 @env{GCC_ROOT} will affect both compilers
3060 at the same time and may make one of the two compilers operate
3061 improperly if set during invocation of the wrong compiler. It is also
3062 very important that the linker uses the proper @file{libgcc.a} GCC
3063 library -- that is, the one from the C++ compiler installation. The
3064 implicit link command as suggested in the @command{gnatmake} command
3065 from the former example can be replaced by an explicit link command with
3066 the full-verbosity option in order to verify which library is used:
3069 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3071 If there is a problem due to interfering environment variables, it can
3072 be worked around by using an intermediate script. The following example
3073 shows the proper script to use when GNAT has not been installed at its
3074 default location and g++ has been installed at its default location:
3082 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3086 Using a non-GNU C++ compiler: The commands previously described can be
3087 used to insure that the C++ linker is used. Nonetheless, you need to add
3088 a few more parameters to the link command line, depending on the exception
3091 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3092 to the libgcc libraries are required:
3097 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3098 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3101 Where CC is the name of the non-GNU C++ compiler.
3103 If the @code{zero cost} exception mechanism is used, and the platform
3104 supports automatic registration of exception tables (e.g.@: Solaris),
3105 paths to more objects are required:
3110 CC `gcc -print-file-name=crtbegin.o` $* \
3111 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3112 `gcc -print-file-name=crtend.o`
3113 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3116 If the @code{zero cost} exception mechanism is used, and the platform
3117 doesn't support automatic registration of exception tables (e.g.@: HP-UX
3118 or AIX), the simple approach described above will not work and
3119 a pre-linking phase using GNAT will be necessary.
3123 Another alternative is to use the @command{gprbuild} multi-language builder
3124 which has a large knowledge base and knows how to link Ada and C++ code
3125 together automatically in most cases.
3127 @node A Simple Example
3128 @subsection A Simple Example
3130 The following example, provided as part of the GNAT examples, shows how
3131 to achieve procedural interfacing between Ada and C++ in both
3132 directions. The C++ class A has two methods. The first method is exported
3133 to Ada by the means of an extern C wrapper function. The second method
3134 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3135 a limited record with a layout comparable to the C++ class. The Ada
3136 subprogram, in turn, calls the C++ method. So, starting from the C++
3137 main program, the process passes back and forth between the two
3141 Here are the compilation commands:
3143 $ gnatmake -c simple_cpp_interface
3146 $ gnatbind -n simple_cpp_interface
3147 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3148 -lstdc++ ex7.o cpp_main.o
3152 Here are the corresponding sources:
3160 void adainit (void);
3161 void adafinal (void);
3162 void method1 (A *t);
3184 class A : public Origin @{
3186 void method1 (void);
3187 void method2 (int v);
3197 extern "C" @{ void ada_method2 (A *t, int v);@}
3199 void A::method1 (void)
3202 printf ("in A::method1, a_value = %d \n",a_value);
3206 void A::method2 (int v)
3208 ada_method2 (this, v);
3209 printf ("in A::method2, a_value = %d \n",a_value);
3216 printf ("in A::A, a_value = %d \n",a_value);
3220 @smallexample @c ada
3222 package body Simple_Cpp_Interface is
3224 procedure Ada_Method2 (This : in out A; V : Integer) is
3230 end Simple_Cpp_Interface;
3233 package Simple_Cpp_Interface is
3236 Vptr : System.Address;
3240 pragma Convention (C, A);
3242 procedure Method1 (This : in out A);
3243 pragma Import (C, Method1);
3245 procedure Ada_Method2 (This : in out A; V : Integer);
3246 pragma Export (C, Ada_Method2);
3248 end Simple_Cpp_Interface;
3251 @node Interfacing with C++ constructors
3252 @subsection Interfacing with C++ constructors
3255 In order to interface with C++ constructors GNAT provides the
3256 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3257 gnat_rm, GNAT Reference Manual}, for additional information).
3258 In this section we present some common uses of C++ constructors
3259 in mixed-languages programs in GNAT.
3261 Let us assume that we need to interface with the following
3269 @b{virtual} int Get_Value ();
3270 Root(); // Default constructor
3271 Root(int v); // 1st non-default constructor
3272 Root(int v, int w); // 2nd non-default constructor
3276 For this purpose we can write the following package spec (further
3277 information on how to build this spec is available in
3278 @ref{Interfacing with C++ at the Class Level} and
3279 @ref{Generating Ada Bindings for C and C++ headers}).
3281 @smallexample @c ada
3282 with Interfaces.C; use Interfaces.C;
3284 type Root is tagged limited record
3288 pragma Import (CPP, Root);
3290 function Get_Value (Obj : Root) return int;
3291 pragma Import (CPP, Get_Value);
3293 function Constructor return Root;
3294 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3296 function Constructor (v : Integer) return Root;
3297 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3299 function Constructor (v, w : Integer) return Root;
3300 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3304 On the Ada side the constructor is represented by a function (whose
3305 name is arbitrary) that returns the classwide type corresponding to
3306 the imported C++ class. Although the constructor is described as a
3307 function, it is typically a procedure with an extra implicit argument
3308 (the object being initialized) at the implementation level. GNAT
3309 issues the appropriate call, whatever it is, to get the object
3310 properly initialized.
3312 Constructors can only appear in the following contexts:
3316 On the right side of an initialization of an object of type @var{T}.
3318 On the right side of an initialization of a record component of type @var{T}.
3320 In an Ada 2005 limited aggregate.
3322 In an Ada 2005 nested limited aggregate.
3324 In an Ada 2005 limited aggregate that initializes an object built in
3325 place by an extended return statement.
3329 In a declaration of an object whose type is a class imported from C++,
3330 either the default C++ constructor is implicitly called by GNAT, or
3331 else the required C++ constructor must be explicitly called in the
3332 expression that initializes the object. For example:
3334 @smallexample @c ada
3336 Obj2 : Root := Constructor;
3337 Obj3 : Root := Constructor (v => 10);
3338 Obj4 : Root := Constructor (30, 40);
3341 The first two declarations are equivalent: in both cases the default C++
3342 constructor is invoked (in the former case the call to the constructor is
3343 implicit, and in the latter case the call is explicit in the object
3344 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3345 that takes an integer argument, and @code{Obj4} is initialized by the
3346 non-default C++ constructor that takes two integers.
3348 Let us derive the imported C++ class in the Ada side. For example:
3350 @smallexample @c ada
3351 type DT is new Root with record
3352 C_Value : Natural := 2009;
3356 In this case the components DT inherited from the C++ side must be
3357 initialized by a C++ constructor, and the additional Ada components
3358 of type DT are initialized by GNAT. The initialization of such an
3359 object is done either by default, or by means of a function returning
3360 an aggregate of type DT, or by means of an extension aggregate.
3362 @smallexample @c ada
3364 Obj6 : DT := Function_Returning_DT (50);
3365 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3368 The declaration of @code{Obj5} invokes the default constructors: the
3369 C++ default constructor of the parent type takes care of the initialization
3370 of the components inherited from Root, and GNAT takes care of the default
3371 initialization of the additional Ada components of type DT (that is,
3372 @code{C_Value} is initialized to value 2009). The order of invocation of
3373 the constructors is consistent with the order of elaboration required by
3374 Ada and C++. That is, the constructor of the parent type is always called
3375 before the constructor of the derived type.
3377 Let us now consider a record that has components whose type is imported
3378 from C++. For example:
3380 @smallexample @c ada
3381 type Rec1 is limited record
3382 Data1 : Root := Constructor (10);
3383 Value : Natural := 1000;
3386 type Rec2 (D : Integer := 20) is limited record
3388 Data2 : Root := Constructor (D, 30);
3392 The initialization of an object of type @code{Rec2} will call the
3393 non-default C++ constructors specified for the imported components.
3396 @smallexample @c ada
3400 Using Ada 2005 we can use limited aggregates to initialize an object
3401 invoking C++ constructors that differ from those specified in the type
3402 declarations. For example:
3404 @smallexample @c ada
3405 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3410 The above declaration uses an Ada 2005 limited aggregate to
3411 initialize @code{Obj9}, and the C++ constructor that has two integer
3412 arguments is invoked to initialize the @code{Data1} component instead
3413 of the constructor specified in the declaration of type @code{Rec1}. In
3414 Ada 2005 the box in the aggregate indicates that unspecified components
3415 are initialized using the expression (if any) available in the component
3416 declaration. That is, in this case discriminant @code{D} is initialized
3417 to value @code{20}, @code{Value} is initialized to value 1000, and the
3418 non-default C++ constructor that handles two integers takes care of
3419 initializing component @code{Data2} with values @code{20,30}.
3421 In Ada 2005 we can use the extended return statement to build the Ada
3422 equivalent to C++ non-default constructors. For example:
3424 @smallexample @c ada
3425 function Constructor (V : Integer) return Rec2 is
3427 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3430 -- Further actions required for construction of
3431 -- objects of type Rec2
3437 In this example the extended return statement construct is used to
3438 build in place the returned object whose components are initialized
3439 by means of a limited aggregate. Any further action associated with
3440 the constructor can be placed inside the construct.
3442 @node Interfacing with C++ at the Class Level
3443 @subsection Interfacing with C++ at the Class Level
3445 In this section we demonstrate the GNAT features for interfacing with
3446 C++ by means of an example making use of Ada 2005 abstract interface
3447 types. This example consists of a classification of animals; classes
3448 have been used to model our main classification of animals, and
3449 interfaces provide support for the management of secondary
3450 classifications. We first demonstrate a case in which the types and
3451 constructors are defined on the C++ side and imported from the Ada
3452 side, and latter the reverse case.
3454 The root of our derivation will be the @code{Animal} class, with a
3455 single private attribute (the @code{Age} of the animal) and two public
3456 primitives to set and get the value of this attribute.
3461 @b{virtual} void Set_Age (int New_Age);
3462 @b{virtual} int Age ();
3468 Abstract interface types are defined in C++ by means of classes with pure
3469 virtual functions and no data members. In our example we will use two
3470 interfaces that provide support for the common management of @code{Carnivore}
3471 and @code{Domestic} animals:
3474 @b{class} Carnivore @{
3476 @b{virtual} int Number_Of_Teeth () = 0;
3479 @b{class} Domestic @{
3481 @b{virtual void} Set_Owner (char* Name) = 0;
3485 Using these declarations, we can now say that a @code{Dog} is an animal that is
3486 both Carnivore and Domestic, that is:
3489 @b{class} Dog : Animal, Carnivore, Domestic @{
3491 @b{virtual} int Number_Of_Teeth ();
3492 @b{virtual} void Set_Owner (char* Name);
3494 Dog(); // Constructor
3501 In the following examples we will assume that the previous declarations are
3502 located in a file named @code{animals.h}. The following package demonstrates
3503 how to import these C++ declarations from the Ada side:
3505 @smallexample @c ada
3506 with Interfaces.C.Strings; use Interfaces.C.Strings;
3508 type Carnivore is interface;
3509 pragma Convention (C_Plus_Plus, Carnivore);
3510 function Number_Of_Teeth (X : Carnivore)
3511 return Natural is abstract;
3513 type Domestic is interface;
3514 pragma Convention (C_Plus_Plus, Set_Owner);
3516 (X : in out Domestic;
3517 Name : Chars_Ptr) is abstract;
3519 type Animal is tagged record
3522 pragma Import (C_Plus_Plus, Animal);
3524 procedure Set_Age (X : in out Animal; Age : Integer);
3525 pragma Import (C_Plus_Plus, Set_Age);
3527 function Age (X : Animal) return Integer;
3528 pragma Import (C_Plus_Plus, Age);
3530 type Dog is new Animal and Carnivore and Domestic with record
3531 Tooth_Count : Natural;
3532 Owner : String (1 .. 30);
3534 pragma Import (C_Plus_Plus, Dog);
3536 function Number_Of_Teeth (A : Dog) return Integer;
3537 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3539 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3540 pragma Import (C_Plus_Plus, Set_Owner);
3542 function New_Dog return Dog;
3543 pragma CPP_Constructor (New_Dog);
3544 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3548 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3549 interfacing with these C++ classes is easy. The only requirement is that all
3550 the primitives and components must be declared exactly in the same order in
3553 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3554 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3555 the arguments to the called primitives will be the same as for C++. For the
3556 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3557 to indicate that they have been defined on the C++ side; this is required
3558 because the dispatch table associated with these tagged types will be built
3559 in the C++ side and therefore will not contain the predefined Ada primitives
3560 which Ada would otherwise expect.
3562 As the reader can see there is no need to indicate the C++ mangled names
3563 associated with each subprogram because it is assumed that all the calls to
3564 these primitives will be dispatching calls. The only exception is the
3565 constructor, which must be registered with the compiler by means of
3566 @code{pragma CPP_Constructor} and needs to provide its associated C++
3567 mangled name because the Ada compiler generates direct calls to it.
3569 With the above packages we can now declare objects of type Dog on the Ada side
3570 and dispatch calls to the corresponding subprograms on the C++ side. We can
3571 also extend the tagged type Dog with further fields and primitives, and
3572 override some of its C++ primitives on the Ada side. For example, here we have
3573 a type derivation defined on the Ada side that inherits all the dispatching
3574 primitives of the ancestor from the C++ side.
3577 @b{with} Animals; @b{use} Animals;
3578 @b{package} Vaccinated_Animals @b{is}
3579 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3580 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3581 @b{end} Vaccinated_Animals;
3584 It is important to note that, because of the ABI compatibility, the programmer
3585 does not need to add any further information to indicate either the object
3586 layout or the dispatch table entry associated with each dispatching operation.
3588 Now let us define all the types and constructors on the Ada side and export
3589 them to C++, using the same hierarchy of our previous example:
3591 @smallexample @c ada
3592 with Interfaces.C.Strings;
3593 use Interfaces.C.Strings;
3595 type Carnivore is interface;
3596 pragma Convention (C_Plus_Plus, Carnivore);
3597 function Number_Of_Teeth (X : Carnivore)
3598 return Natural is abstract;
3600 type Domestic is interface;
3601 pragma Convention (C_Plus_Plus, Set_Owner);
3603 (X : in out Domestic;
3604 Name : Chars_Ptr) is abstract;
3606 type Animal is tagged record
3609 pragma Convention (C_Plus_Plus, Animal);
3611 procedure Set_Age (X : in out Animal; Age : Integer);
3612 pragma Export (C_Plus_Plus, Set_Age);
3614 function Age (X : Animal) return Integer;
3615 pragma Export (C_Plus_Plus, Age);
3617 type Dog is new Animal and Carnivore and Domestic with record
3618 Tooth_Count : Natural;
3619 Owner : String (1 .. 30);
3621 pragma Convention (C_Plus_Plus, Dog);
3623 function Number_Of_Teeth (A : Dog) return Integer;
3624 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3626 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3627 pragma Export (C_Plus_Plus, Set_Owner);
3629 function New_Dog return Dog'Class;
3630 pragma Export (C_Plus_Plus, New_Dog);
3634 Compared with our previous example the only difference is the use of
3635 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3636 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3637 nothing else to be done; as explained above, the only requirement is that all
3638 the primitives and components are declared in exactly the same order.
3640 For completeness, let us see a brief C++ main program that uses the
3641 declarations available in @code{animals.h} (presented in our first example) to
3642 import and use the declarations from the Ada side, properly initializing and
3643 finalizing the Ada run-time system along the way:
3646 @b{#include} "animals.h"
3647 @b{#include} <iostream>
3648 @b{using namespace} std;
3650 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3651 void Check_Domestic (Domestic *obj) @{@dots{}@}
3652 void Check_Animal (Animal *obj) @{@dots{}@}
3653 void Check_Dog (Dog *obj) @{@dots{}@}
3656 void adainit (void);
3657 void adafinal (void);
3663 Dog *obj = new_dog(); // Ada constructor
3664 Check_Carnivore (obj); // Check secondary DT
3665 Check_Domestic (obj); // Check secondary DT
3666 Check_Animal (obj); // Check primary DT
3667 Check_Dog (obj); // Check primary DT
3672 adainit (); test(); adafinal ();
3677 @node Comparison between GNAT and C/C++ Compilation Models
3678 @section Comparison between GNAT and C/C++ Compilation Models
3681 The GNAT model of compilation is close to the C and C++ models. You can
3682 think of Ada specs as corresponding to header files in C. As in C, you
3683 don't need to compile specs; they are compiled when they are used. The
3684 Ada @code{with} is similar in effect to the @code{#include} of a C
3687 One notable difference is that, in Ada, you may compile specs separately
3688 to check them for semantic and syntactic accuracy. This is not always
3689 possible with C headers because they are fragments of programs that have
3690 less specific syntactic or semantic rules.
3692 The other major difference is the requirement for running the binder,
3693 which performs two important functions. First, it checks for
3694 consistency. In C or C++, the only defense against assembling
3695 inconsistent programs lies outside the compiler, in a makefile, for
3696 example. The binder satisfies the Ada requirement that it be impossible
3697 to construct an inconsistent program when the compiler is used in normal
3700 @cindex Elaboration order control
3701 The other important function of the binder is to deal with elaboration
3702 issues. There are also elaboration issues in C++ that are handled
3703 automatically. This automatic handling has the advantage of being
3704 simpler to use, but the C++ programmer has no control over elaboration.
3705 Where @code{gnatbind} might complain there was no valid order of
3706 elaboration, a C++ compiler would simply construct a program that
3707 malfunctioned at run time.
3710 @node Comparison between GNAT and Conventional Ada Library Models
3711 @section Comparison between GNAT and Conventional Ada Library Models
3714 This section is intended for Ada programmers who have
3715 used an Ada compiler implementing the traditional Ada library
3716 model, as described in the Ada Reference Manual.
3718 @cindex GNAT library
3719 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3720 source files themselves acts as the library. Compiling Ada programs does
3721 not generate any centralized information, but rather an object file and
3722 a ALI file, which are of interest only to the binder and linker.
3723 In a traditional system, the compiler reads information not only from
3724 the source file being compiled, but also from the centralized library.
3725 This means that the effect of a compilation depends on what has been
3726 previously compiled. In particular:
3730 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3731 to the version of the unit most recently compiled into the library.
3734 Inlining is effective only if the necessary body has already been
3735 compiled into the library.
3738 Compiling a unit may obsolete other units in the library.
3742 In GNAT, compiling one unit never affects the compilation of any other
3743 units because the compiler reads only source files. Only changes to source
3744 files can affect the results of a compilation. In particular:
3748 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3749 to the source version of the unit that is currently accessible to the
3754 Inlining requires the appropriate source files for the package or
3755 subprogram bodies to be available to the compiler. Inlining is always
3756 effective, independent of the order in which units are complied.
3759 Compiling a unit never affects any other compilations. The editing of
3760 sources may cause previous compilations to be out of date if they
3761 depended on the source file being modified.
3765 The most important result of these differences is that order of compilation
3766 is never significant in GNAT. There is no situation in which one is
3767 required to do one compilation before another. What shows up as order of
3768 compilation requirements in the traditional Ada library becomes, in
3769 GNAT, simple source dependencies; in other words, there is only a set
3770 of rules saying what source files must be present when a file is
3774 @node Placement of temporary files
3775 @section Placement of temporary files
3776 @cindex Temporary files (user control over placement)
3779 GNAT creates temporary files in the directory designated by the environment
3780 variable @env{TMPDIR}.
3781 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3782 for detailed information on how environment variables are resolved.
3783 For most users the easiest way to make use of this feature is to simply
3784 define @env{TMPDIR} as a job level logical name).
3785 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3786 for compiler temporary files, then you can include something like the
3787 following command in your @file{LOGIN.COM} file:
3790 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3794 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3795 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3796 designated by @env{TEMP}.
3797 If none of these environment variables are defined then GNAT uses the
3798 directory designated by the logical name @code{SYS$SCRATCH:}
3799 (by default the user's home directory). If all else fails
3800 GNAT uses the current directory for temporary files.
3803 @c *************************
3804 @node Compiling Using gcc
3805 @chapter Compiling Using @command{gcc}
3808 This chapter discusses how to compile Ada programs using the @command{gcc}
3809 command. It also describes the set of switches
3810 that can be used to control the behavior of the compiler.
3812 * Compiling Programs::
3813 * Switches for gcc::
3814 * Search Paths and the Run-Time Library (RTL)::
3815 * Order of Compilation Issues::
3819 @node Compiling Programs
3820 @section Compiling Programs
3823 The first step in creating an executable program is to compile the units
3824 of the program using the @command{gcc} command. You must compile the
3829 the body file (@file{.adb}) for a library level subprogram or generic
3833 the spec file (@file{.ads}) for a library level package or generic
3834 package that has no body
3837 the body file (@file{.adb}) for a library level package
3838 or generic package that has a body
3843 You need @emph{not} compile the following files
3848 the spec of a library unit which has a body
3855 because they are compiled as part of compiling related units. GNAT
3857 when the corresponding body is compiled, and subunits when the parent is
3860 @cindex cannot generate code
3861 If you attempt to compile any of these files, you will get one of the
3862 following error messages (where @var{fff} is the name of the file you
3866 cannot generate code for file @var{fff} (package spec)
3867 to check package spec, use -gnatc
3869 cannot generate code for file @var{fff} (missing subunits)
3870 to check parent unit, use -gnatc
3872 cannot generate code for file @var{fff} (subprogram spec)
3873 to check subprogram spec, use -gnatc
3875 cannot generate code for file @var{fff} (subunit)
3876 to check subunit, use -gnatc
3880 As indicated by the above error messages, if you want to submit
3881 one of these files to the compiler to check for correct semantics
3882 without generating code, then use the @option{-gnatc} switch.
3884 The basic command for compiling a file containing an Ada unit is
3887 @c $ gcc -c @ovar{switches} @file{file name}
3888 @c Expanding @ovar macro inline (explanation in macro def comments)
3889 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3893 where @var{file name} is the name of the Ada file (usually
3895 @file{.ads} for a spec or @file{.adb} for a body).
3898 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3900 The result of a successful compilation is an object file, which has the
3901 same name as the source file but an extension of @file{.o} and an Ada
3902 Library Information (ALI) file, which also has the same name as the
3903 source file, but with @file{.ali} as the extension. GNAT creates these
3904 two output files in the current directory, but you may specify a source
3905 file in any directory using an absolute or relative path specification
3906 containing the directory information.
3909 @command{gcc} is actually a driver program that looks at the extensions of
3910 the file arguments and loads the appropriate compiler. For example, the
3911 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3912 These programs are in directories known to the driver program (in some
3913 configurations via environment variables you set), but need not be in
3914 your path. The @command{gcc} driver also calls the assembler and any other
3915 utilities needed to complete the generation of the required object
3918 It is possible to supply several file names on the same @command{gcc}
3919 command. This causes @command{gcc} to call the appropriate compiler for
3920 each file. For example, the following command lists three separate
3921 files to be compiled:
3924 $ gcc -c x.adb y.adb z.c
3928 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3929 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3930 The compiler generates three object files @file{x.o}, @file{y.o} and
3931 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3932 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3935 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3938 @node Switches for gcc
3939 @section Switches for @command{gcc}
3942 The @command{gcc} command accepts switches that control the
3943 compilation process. These switches are fully described in this section.
3944 First we briefly list all the switches, in alphabetical order, then we
3945 describe the switches in more detail in functionally grouped sections.
3947 More switches exist for GCC than those documented here, especially
3948 for specific targets. However, their use is not recommended as
3949 they may change code generation in ways that are incompatible with
3950 the Ada run-time library, or can cause inconsistencies between
3954 * Output and Error Message Control::
3955 * Warning Message Control::
3956 * Debugging and Assertion Control::
3957 * Validity Checking::
3960 * Using gcc for Syntax Checking::
3961 * Using gcc for Semantic Checking::
3962 * Compiling Different Versions of Ada::
3963 * Character Set Control::
3964 * File Naming Control::
3965 * Subprogram Inlining Control::
3966 * Auxiliary Output Control::
3967 * Debugging Control::
3968 * Exception Handling Control::
3969 * Units to Sources Mapping Files::
3970 * Integrated Preprocessing::
3971 * Code Generation Control::
3980 @cindex @option{-b} (@command{gcc})
3981 @item -b @var{target}
3982 Compile your program to run on @var{target}, which is the name of a
3983 system configuration. You must have a GNAT cross-compiler built if
3984 @var{target} is not the same as your host system.
3987 @cindex @option{-B} (@command{gcc})
3988 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3989 from @var{dir} instead of the default location. Only use this switch
3990 when multiple versions of the GNAT compiler are available.
3991 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3992 GNU Compiler Collection (GCC)}, for further details. You would normally
3993 use the @option{-b} or @option{-V} switch instead.
3996 @cindex @option{-c} (@command{gcc})
3997 Compile. Always use this switch when compiling Ada programs.
3999 Note: for some other languages when using @command{gcc}, notably in
4000 the case of C and C++, it is possible to use
4001 use @command{gcc} without a @option{-c} switch to
4002 compile and link in one step. In the case of GNAT, you
4003 cannot use this approach, because the binder must be run
4004 and @command{gcc} cannot be used to run the GNAT binder.
4008 @cindex @option{-fno-inline} (@command{gcc})
4009 Suppresses all inlining, even if other optimization or inlining
4010 switches are set. This includes suppression of inlining that
4011 results from the use of the pragma @code{Inline_Always}.
4012 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4013 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4014 effect if this switch is present.
4016 @item -fno-inline-functions
4017 @cindex @option{-fno-inline-functions} (@command{gcc})
4018 Suppresses automatic inlining of subprograms, which is enabled
4019 if @option{-O3} is used.
4021 @item -fno-inline-small-functions
4022 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4023 Suppresses automatic inlining of small subprograms, which is enabled
4024 if @option{-O2} is used.
4026 @item -fno-inline-functions-called-once
4027 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4028 Suppresses inlining of subprograms local to the unit and called once
4029 from within it, which is enabled if @option{-O1} is used.
4032 @cindex @option{-fno-ivopts} (@command{gcc})
4033 Suppresses high-level loop induction variable optimizations, which are
4034 enabled if @option{-O1} is used. These optimizations are generally
4035 profitable but, for some specific cases of loops with numerous uses
4036 of the iteration variable that follow a common pattern, they may end
4037 up destroying the regularity that could be exploited at a lower level
4038 and thus producing inferior code.
4040 @item -fno-strict-aliasing
4041 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4042 Causes the compiler to avoid assumptions regarding non-aliasing
4043 of objects of different types. See
4044 @ref{Optimization and Strict Aliasing} for details.
4047 @cindex @option{-fstack-check} (@command{gcc})
4048 Activates stack checking.
4049 See @ref{Stack Overflow Checking} for details.
4052 @cindex @option{-fstack-usage} (@command{gcc})
4053 Makes the compiler output stack usage information for the program, on a
4054 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4056 @item -fcallgraph-info@r{[}=su@r{]}
4057 @cindex @option{-fcallgraph-info} (@command{gcc})
4058 Makes the compiler output callgraph information for the program, on a
4059 per-file basis. The information is generated in the VCG format. It can
4060 be decorated with stack-usage per-node information.
4063 @cindex @option{-fdump-scos} (@command{gcc})
4064 Generate SCO (Source Coverage Obligation) information in the ALI file.
4065 This information is used by advanced coverage tools. See unit @file{SCOs}
4066 in the compiler sources for details in files @file{scos.ads} and
4070 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4071 Generate debugging information. This information is stored in the object
4072 file and copied from there to the final executable file by the linker,
4073 where it can be read by the debugger. You must use the
4074 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4077 @cindex @option{-gnat83} (@command{gcc})
4078 Enforce Ada 83 restrictions.
4081 @cindex @option{-gnat95} (@command{gcc})
4082 Enforce Ada 95 restrictions.
4085 @cindex @option{-gnat05} (@command{gcc})
4086 Allow full Ada 2005 features.
4089 @cindex @option{-gnat2005} (@command{gcc})
4090 Allow full Ada 2005 features (same as @option{-gnat05})
4093 @cindex @option{-gnat12} (@command{gcc})
4096 @cindex @option{-gnat2012} (@command{gcc})
4097 Allow full Ada 2012 features (same as @option{-gnat12})
4100 @cindex @option{-gnata} (@command{gcc})
4101 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4102 activated. Note that these pragmas can also be controlled using the
4103 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4104 It also activates pragmas @code{Check}, @code{Precondition}, and
4105 @code{Postcondition}. Note that these pragmas can also be controlled
4106 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
4107 also activates all assertions defined in the RM as aspects: preconditions,
4108 postconditions, type invariants and (sub)type predicates. In all Ada modes,
4109 corresponding pragmas for type invariants and (sub)type predicates are
4113 @cindex @option{-gnatA} (@command{gcc})
4114 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4118 @cindex @option{-gnatb} (@command{gcc})
4119 Generate brief messages to @file{stderr} even if verbose mode set.
4122 @cindex @option{-gnatB} (@command{gcc})
4123 Assume no invalid (bad) values except for 'Valid attribute use
4124 (@pxref{Validity Checking}).
4127 @cindex @option{-gnatc} (@command{gcc})
4128 Check syntax and semantics only (no code generation attempted).
4131 @cindex @option{-gnatC} (@command{gcc})
4132 Generate CodePeer information (no code generation attempted).
4133 This switch will generate an intermediate representation suitable for
4134 use by CodePeer (@file{.scil} files). This switch is not compatible with
4135 code generation (it will, among other things, disable some switches such
4136 as -gnatn, and enable others such as -gnata).
4139 @cindex @option{-gnatd} (@command{gcc})
4140 Specify debug options for the compiler. The string of characters after
4141 the @option{-gnatd} specify the specific debug options. The possible
4142 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4143 compiler source file @file{debug.adb} for details of the implemented
4144 debug options. Certain debug options are relevant to applications
4145 programmers, and these are documented at appropriate points in this
4150 @cindex @option{-gnatD[nn]} (@command{gcc})
4153 @item /XDEBUG /LXDEBUG=nnn
4155 Create expanded source files for source level debugging. This switch
4156 also suppress generation of cross-reference information
4157 (see @option{-gnatx}).
4159 @item -gnatec=@var{path}
4160 @cindex @option{-gnatec} (@command{gcc})
4161 Specify a configuration pragma file
4163 (the equal sign is optional)
4165 (@pxref{The Configuration Pragmas Files}).
4167 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4168 @cindex @option{-gnateD} (@command{gcc})
4169 Defines a symbol, associated with @var{value}, for preprocessing.
4170 (@pxref{Integrated Preprocessing}).
4173 @cindex @option{-gnateE} (@command{gcc})
4174 Generate extra information in exception messages. In particular, display
4175 extra column information and the value and range associated with index and
4176 range check failures, and extra column information for access checks.
4177 In cases where the compiler is able to determine at compile time that
4178 a check will fail, it gives a warning, and the extra information is not
4179 produced at run time.
4182 @cindex @option{-gnatef} (@command{gcc})
4183 Display full source path name in brief error messages.
4186 @cindex @option{-gnateG} (@command{gcc})
4187 Save result of preprocessing in a text file.
4189 @item -gnatei@var{nnn}
4190 @cindex @option{-gnatei} (@command{gcc})
4191 Set maximum number of instantiations during compilation of a single unit to
4192 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
4193 the rare case when a single unit legitimately exceeds this limit.
4195 @item -gnateI@var{nnn}
4196 @cindex @option{-gnateI} (@command{gcc})
4197 Indicates that the source is a multi-unit source and that the index of the
4198 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4199 to be a valid index in the multi-unit source.
4201 @item -gnatem=@var{path}
4202 @cindex @option{-gnatem} (@command{gcc})
4203 Specify a mapping file
4205 (the equal sign is optional)
4207 (@pxref{Units to Sources Mapping Files}).
4209 @item -gnatep=@var{file}
4210 @cindex @option{-gnatep} (@command{gcc})
4211 Specify a preprocessing data file
4213 (the equal sign is optional)
4215 (@pxref{Integrated Preprocessing}).
4218 @cindex @option{-gnateP} (@command{gcc})
4219 Turn categorization dependency errors into warnings.
4220 Ada requires that units that WITH one another have compatible categories, for
4221 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4222 these errors become warnings (which can be ignored, or suppressed in the usual
4223 manner). This can be useful in some specialized circumstances such as the
4224 temporary use of special test software.
4227 @cindex @option{-gnateS} (@command{gcc})
4228 Synonym of @option{-fdump-scos}, kept for backards compatibility.
4231 @cindex @option{-gnatE} (@command{gcc})
4232 Full dynamic elaboration checks.
4235 @cindex @option{-gnatf} (@command{gcc})
4236 Full errors. Multiple errors per line, all undefined references, do not
4237 attempt to suppress cascaded errors.
4240 @cindex @option{-gnatF} (@command{gcc})
4241 Externals names are folded to all uppercase.
4243 @item ^-gnatg^/GNAT_INTERNAL^
4244 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4245 Internal GNAT implementation mode. This should not be used for
4246 applications programs, it is intended only for use by the compiler
4247 and its run-time library. For documentation, see the GNAT sources.
4248 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4249 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4250 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4251 so that all standard warnings and all standard style options are turned on.
4252 All warnings and style messages are treated as errors.
4256 @cindex @option{-gnatG[nn]} (@command{gcc})
4259 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4261 List generated expanded code in source form.
4263 @item ^-gnath^/HELP^
4264 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4265 Output usage information. The output is written to @file{stdout}.
4267 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4268 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4269 Identifier character set
4271 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4273 For details of the possible selections for @var{c},
4274 see @ref{Character Set Control}.
4276 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4277 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4278 Ignore representation clauses. When this switch is used,
4279 representation clauses are treated as comments. This is useful
4280 when initially porting code where you want to ignore rep clause
4281 problems, and also for compiling foreign code (particularly
4282 for use with ASIS). The representation clauses that are ignored
4283 are: enumeration_representation_clause, record_representation_clause,
4284 and attribute_definition_clause for the following attributes:
4285 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4286 Object_Size, Size, Small, Stream_Size, and Value_Size.
4287 Note that this option should be used only for compiling -- the
4288 code is likely to malfunction at run time.
4291 @cindex @option{-gnatjnn} (@command{gcc})
4292 Reformat error messages to fit on nn character lines
4294 @item -gnatk=@var{n}
4295 @cindex @option{-gnatk} (@command{gcc})
4296 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4299 @cindex @option{-gnatl} (@command{gcc})
4300 Output full source listing with embedded error messages.
4303 @cindex @option{-gnatL} (@command{gcc})
4304 Used in conjunction with -gnatG or -gnatD to intersperse original
4305 source lines (as comment lines with line numbers) in the expanded
4308 @item -gnatm=@var{n}
4309 @cindex @option{-gnatm} (@command{gcc})
4310 Limit number of detected error or warning messages to @var{n}
4311 where @var{n} is in the range 1..999999. The default setting if
4312 no switch is given is 9999. If the number of warnings reaches this
4313 limit, then a message is output and further warnings are suppressed,
4314 but the compilation is continued. If the number of error messages
4315 reaches this limit, then a message is output and the compilation
4316 is abandoned. The equal sign here is optional. A value of zero
4317 means that no limit applies.
4320 @cindex @option{-gnatn} (@command{gcc})
4321 Activate inlining for subprograms for which pragma @code{Inline} is
4322 specified. This inlining is performed by the GCC back-end. An optional
4323 digit sets the inlining level: 1 for moderate inlining across modules
4324 or 2 for full inlining across modules. If no inlining level is specified,
4325 the compiler will pick it based on the optimization level.
4328 @cindex @option{-gnatN} (@command{gcc})
4329 Activate front end inlining for subprograms for which
4330 pragma @code{Inline} is specified. This inlining is performed
4331 by the front end and will be visible in the
4332 @option{-gnatG} output.
4334 When using a gcc-based back end (in practice this means using any version
4335 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4336 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4337 Historically front end inlining was more extensive than the gcc back end
4338 inlining, but that is no longer the case.
4341 @cindex @option{-gnato??} (@command{gcc})
4342 Set default overflow checking mode. Here `@code{??}' is two digits, a
4343 single digit, or nothing. Each digit is one of the digits `@code{0}'
4348 suppress overflow checks (@code{SUPPRESSED})
4350 all intermediate overflows checked (@code{CHECKED})
4352 minimize intermediate overflows (@code{MINIMIZED})
4354 eliminate intermediate overflows (@code{ELIMINATED})
4357 If only one digit appears then it applies to all
4358 cases; if two digits are given, then the first applies outside
4359 assertions, and the second within assertions.
4361 If no digits follow the @option{-gnato}, then it is equivalent to
4363 causing all intermediate overflows to be checked.
4365 The default if no option @option{-gnato} is given is that overflows are not
4366 checked, which is equivalent to @option{-gnato00}.
4367 Note that division by zero is a separate check that is not
4368 controlled by this switch (division by zero checking is on by default).
4370 See also @ref{Specifying the Desired Mode}.
4373 @cindex @option{-gnatp} (@command{gcc})
4374 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4375 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4378 @cindex @option{-gnat-p} (@command{gcc})
4379 Cancel effect of previous @option{-gnatp} switch.
4382 @cindex @option{-gnatP} (@command{gcc})
4383 Enable polling. This is required on some systems (notably Windows NT) to
4384 obtain asynchronous abort and asynchronous transfer of control capability.
4385 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4389 @cindex @option{-gnatq} (@command{gcc})
4390 Don't quit. Try semantics, even if parse errors.
4393 @cindex @option{-gnatQ} (@command{gcc})
4394 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4397 @cindex @option{-gnatr} (@command{gcc})
4398 Treat pragma Restrictions as Restriction_Warnings.
4400 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4401 @cindex @option{-gnatR} (@command{gcc})
4402 Output representation information for declared types and objects.
4405 @cindex @option{-gnats} (@command{gcc})
4409 @cindex @option{-gnatS} (@command{gcc})
4410 Print package Standard.
4413 @cindex @option{-gnatt} (@command{gcc})
4414 Generate tree output file.
4416 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4417 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4418 All compiler tables start at @var{nnn} times usual starting size.
4421 @cindex @option{-gnatu} (@command{gcc})
4422 List units for this compilation.
4425 @cindex @option{-gnatU} (@command{gcc})
4426 Tag all error messages with the unique string ``error:''
4429 @cindex @option{-gnatv} (@command{gcc})
4430 Verbose mode. Full error output with source lines to @file{stdout}.
4433 @cindex @option{-gnatV} (@command{gcc})
4434 Control level of validity checking (@pxref{Validity Checking}).
4436 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4437 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4439 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4440 the exact warnings that
4441 are enabled or disabled (@pxref{Warning Message Control}).
4443 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4444 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4445 Wide character encoding method
4447 (@var{e}=n/h/u/s/e/8).
4450 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4454 @cindex @option{-gnatx} (@command{gcc})
4455 Suppress generation of cross-reference information.
4458 @cindex @option{-gnatX} (@command{gcc})
4459 Enable GNAT implementation extensions and latest Ada version.
4461 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4462 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4463 Enable built-in style checks (@pxref{Style Checking}).
4465 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4466 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4467 Distribution stub generation and compilation
4469 (@var{m}=r/c for receiver/caller stubs).
4472 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4473 to be generated and compiled).
4476 @item ^-I^/SEARCH=^@var{dir}
4477 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4479 Direct GNAT to search the @var{dir} directory for source files needed by
4480 the current compilation
4481 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4483 @item ^-I-^/NOCURRENT_DIRECTORY^
4484 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4486 Except for the source file named in the command line, do not look for source
4487 files in the directory containing the source file named in the command line
4488 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4492 @cindex @option{-mbig-switch} (@command{gcc})
4493 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4494 This standard gcc switch causes the compiler to use larger offsets in its
4495 jump table representation for @code{case} statements.
4496 This may result in less efficient code, but is sometimes necessary
4497 (for example on HP-UX targets)
4498 @cindex HP-UX and @option{-mbig-switch} option
4499 in order to compile large and/or nested @code{case} statements.
4502 @cindex @option{-o} (@command{gcc})
4503 This switch is used in @command{gcc} to redirect the generated object file
4504 and its associated ALI file. Beware of this switch with GNAT, because it may
4505 cause the object file and ALI file to have different names which in turn
4506 may confuse the binder and the linker.
4510 @cindex @option{-nostdinc} (@command{gcc})
4511 Inhibit the search of the default location for the GNAT Run Time
4512 Library (RTL) source files.
4515 @cindex @option{-nostdlib} (@command{gcc})
4516 Inhibit the search of the default location for the GNAT Run Time
4517 Library (RTL) ALI files.
4521 @c Expanding @ovar macro inline (explanation in macro def comments)
4522 @item -O@r{[}@var{n}@r{]}
4523 @cindex @option{-O} (@command{gcc})
4524 @var{n} controls the optimization level.
4528 No optimization, the default setting if no @option{-O} appears
4531 Normal optimization, the default if you specify @option{-O} without
4532 an operand. A good compromise between code quality and compilation
4536 Extensive optimization, may improve execution time, possibly at the cost of
4537 substantially increased compilation time.
4540 Same as @option{-O2}, and also includes inline expansion for small subprograms
4544 Optimize space usage
4548 See also @ref{Optimization Levels}.
4553 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4554 Equivalent to @option{/OPTIMIZE=NONE}.
4555 This is the default behavior in the absence of an @option{/OPTIMIZE}
4558 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4559 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4560 Selects the level of optimization for your program. The supported
4561 keywords are as follows:
4564 Perform most optimizations, including those that
4566 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4567 without keyword options.
4570 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4573 Perform some optimizations, but omit ones that are costly.
4576 Same as @code{SOME}.
4579 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4580 automatic inlining of small subprograms within a unit
4583 Try to unroll loops. This keyword may be specified together with
4584 any keyword above other than @code{NONE}. Loop unrolling
4585 usually, but not always, improves the performance of programs.
4588 Optimize space usage
4592 See also @ref{Optimization Levels}.
4596 @item -pass-exit-codes
4597 @cindex @option{-pass-exit-codes} (@command{gcc})
4598 Catch exit codes from the compiler and use the most meaningful as
4602 @item --RTS=@var{rts-path}
4603 @cindex @option{--RTS} (@command{gcc})
4604 Specifies the default location of the runtime library. Same meaning as the
4605 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4608 @cindex @option{^-S^/ASM^} (@command{gcc})
4609 ^Used in place of @option{-c} to^Used to^
4610 cause the assembler source file to be
4611 generated, using @file{^.s^.S^} as the extension,
4612 instead of the object file.
4613 This may be useful if you need to examine the generated assembly code.
4615 @item ^-fverbose-asm^/VERBOSE_ASM^
4616 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4617 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4618 to cause the generated assembly code file to be annotated with variable
4619 names, making it significantly easier to follow.
4622 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4623 Show commands generated by the @command{gcc} driver. Normally used only for
4624 debugging purposes or if you need to be sure what version of the
4625 compiler you are executing.
4629 @cindex @option{-V} (@command{gcc})
4630 Execute @var{ver} version of the compiler. This is the @command{gcc}
4631 version, not the GNAT version.
4634 @item ^-w^/NO_BACK_END_WARNINGS^
4635 @cindex @option{-w} (@command{gcc})
4636 Turn off warnings generated by the back end of the compiler. Use of
4637 this switch also causes the default for front end warnings to be set
4638 to suppress (as though @option{-gnatws} had appeared at the start of
4644 @c Combining qualifiers does not work on VMS
4645 You may combine a sequence of GNAT switches into a single switch. For
4646 example, the combined switch
4648 @cindex Combining GNAT switches
4654 is equivalent to specifying the following sequence of switches:
4657 -gnato -gnatf -gnati3
4662 The following restrictions apply to the combination of switches
4667 The switch @option{-gnatc} if combined with other switches must come
4668 first in the string.
4671 The switch @option{-gnats} if combined with other switches must come
4672 first in the string.
4676 ^^@option{/DISTRIBUTION_STUBS=},^
4677 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4678 switches, and only one of them may appear in the command line.
4681 The switch @option{-gnat-p} may not be combined with any other switch.
4685 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4686 switch), then all further characters in the switch are interpreted
4687 as style modifiers (see description of @option{-gnaty}).
4690 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4691 switch), then all further characters in the switch are interpreted
4692 as debug flags (see description of @option{-gnatd}).
4695 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4696 switch), then all further characters in the switch are interpreted
4697 as warning mode modifiers (see description of @option{-gnatw}).
4700 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4701 switch), then all further characters in the switch are interpreted
4702 as validity checking options (@pxref{Validity Checking}).
4705 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4706 a combined list of options.
4710 @node Output and Error Message Control
4711 @subsection Output and Error Message Control
4715 The standard default format for error messages is called ``brief format''.
4716 Brief format messages are written to @file{stderr} (the standard error
4717 file) and have the following form:
4720 e.adb:3:04: Incorrect spelling of keyword "function"
4721 e.adb:4:20: ";" should be "is"
4725 The first integer after the file name is the line number in the file,
4726 and the second integer is the column number within the line.
4728 @code{GPS} can parse the error messages
4729 and point to the referenced character.
4731 The following switches provide control over the error message
4737 @cindex @option{-gnatv} (@command{gcc})
4740 The v stands for verbose.
4742 The effect of this setting is to write long-format error
4743 messages to @file{stdout} (the standard output file.
4744 The same program compiled with the
4745 @option{-gnatv} switch would generate:
4749 3. funcion X (Q : Integer)
4751 >>> Incorrect spelling of keyword "function"
4754 >>> ";" should be "is"
4759 The vertical bar indicates the location of the error, and the @samp{>>>}
4760 prefix can be used to search for error messages. When this switch is
4761 used the only source lines output are those with errors.
4764 @cindex @option{-gnatl} (@command{gcc})
4766 The @code{l} stands for list.
4768 This switch causes a full listing of
4769 the file to be generated. In the case where a body is
4770 compiled, the corresponding spec is also listed, along
4771 with any subunits. Typical output from compiling a package
4772 body @file{p.adb} might look like:
4774 @smallexample @c ada
4778 1. package body p is
4780 3. procedure a is separate;
4791 2. pragma Elaborate_Body
4815 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4816 standard output is redirected, a brief summary is written to
4817 @file{stderr} (standard error) giving the number of error messages and
4818 warning messages generated.
4820 @item ^-gnatl^/OUTPUT_FILE^=file
4821 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4822 This has the same effect as @option{-gnatl} except that the output is
4823 written to a file instead of to standard output. If the given name
4824 @file{fname} does not start with a period, then it is the full name
4825 of the file to be written. If @file{fname} is an extension, it is
4826 appended to the name of the file being compiled. For example, if
4827 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4828 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4831 @cindex @option{-gnatU} (@command{gcc})
4832 This switch forces all error messages to be preceded by the unique
4833 string ``error:''. This means that error messages take a few more
4834 characters in space, but allows easy searching for and identification
4838 @cindex @option{-gnatb} (@command{gcc})
4840 The @code{b} stands for brief.
4842 This switch causes GNAT to generate the
4843 brief format error messages to @file{stderr} (the standard error
4844 file) as well as the verbose
4845 format message or full listing (which as usual is written to
4846 @file{stdout} (the standard output file).
4848 @item -gnatm=@var{n}
4849 @cindex @option{-gnatm} (@command{gcc})
4851 The @code{m} stands for maximum.
4853 @var{n} is a decimal integer in the
4854 range of 1 to 999999 and limits the number of error or warning
4855 messages to be generated. For example, using
4856 @option{-gnatm2} might yield
4859 e.adb:3:04: Incorrect spelling of keyword "function"
4860 e.adb:5:35: missing ".."
4861 fatal error: maximum number of errors detected
4862 compilation abandoned
4866 The default setting if
4867 no switch is given is 9999. If the number of warnings reaches this
4868 limit, then a message is output and further warnings are suppressed,
4869 but the compilation is continued. If the number of error messages
4870 reaches this limit, then a message is output and the compilation
4871 is abandoned. A value of zero means that no limit applies.
4874 Note that the equal sign is optional, so the switches
4875 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4878 @cindex @option{-gnatf} (@command{gcc})
4879 @cindex Error messages, suppressing
4881 The @code{f} stands for full.
4883 Normally, the compiler suppresses error messages that are likely to be
4884 redundant. This switch causes all error
4885 messages to be generated. In particular, in the case of
4886 references to undefined variables. If a given variable is referenced
4887 several times, the normal format of messages is
4889 e.adb:7:07: "V" is undefined (more references follow)
4893 where the parenthetical comment warns that there are additional
4894 references to the variable @code{V}. Compiling the same program with the
4895 @option{-gnatf} switch yields
4898 e.adb:7:07: "V" is undefined
4899 e.adb:8:07: "V" is undefined
4900 e.adb:8:12: "V" is undefined
4901 e.adb:8:16: "V" is undefined
4902 e.adb:9:07: "V" is undefined
4903 e.adb:9:12: "V" is undefined
4907 The @option{-gnatf} switch also generates additional information for
4908 some error messages. Some examples are:
4912 Details on possibly non-portable unchecked conversion
4914 List possible interpretations for ambiguous calls
4916 Additional details on incorrect parameters
4920 @cindex @option{-gnatjnn} (@command{gcc})
4921 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4922 with continuation lines are treated as though the continuation lines were
4923 separate messages (and so a warning with two continuation lines counts as
4924 three warnings, and is listed as three separate messages).
4926 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4927 messages are output in a different manner. A message and all its continuation
4928 lines are treated as a unit, and count as only one warning or message in the
4929 statistics totals. Furthermore, the message is reformatted so that no line
4930 is longer than nn characters.
4933 @cindex @option{-gnatq} (@command{gcc})
4935 The @code{q} stands for quit (really ``don't quit'').
4937 In normal operation mode, the compiler first parses the program and
4938 determines if there are any syntax errors. If there are, appropriate
4939 error messages are generated and compilation is immediately terminated.
4941 GNAT to continue with semantic analysis even if syntax errors have been
4942 found. This may enable the detection of more errors in a single run. On
4943 the other hand, the semantic analyzer is more likely to encounter some
4944 internal fatal error when given a syntactically invalid tree.
4947 @cindex @option{-gnatQ} (@command{gcc})
4948 In normal operation mode, the @file{ALI} file is not generated if any
4949 illegalities are detected in the program. The use of @option{-gnatQ} forces
4950 generation of the @file{ALI} file. This file is marked as being in
4951 error, so it cannot be used for binding purposes, but it does contain
4952 reasonably complete cross-reference information, and thus may be useful
4953 for use by tools (e.g., semantic browsing tools or integrated development
4954 environments) that are driven from the @file{ALI} file. This switch
4955 implies @option{-gnatq}, since the semantic phase must be run to get a
4956 meaningful ALI file.
4958 In addition, if @option{-gnatt} is also specified, then the tree file is
4959 generated even if there are illegalities. It may be useful in this case
4960 to also specify @option{-gnatq} to ensure that full semantic processing
4961 occurs. The resulting tree file can be processed by ASIS, for the purpose
4962 of providing partial information about illegal units, but if the error
4963 causes the tree to be badly malformed, then ASIS may crash during the
4966 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4967 being in error, @command{gnatmake} will attempt to recompile the source when it
4968 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4970 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4971 since ALI files are never generated if @option{-gnats} is set.
4975 @node Warning Message Control
4976 @subsection Warning Message Control
4977 @cindex Warning messages
4979 In addition to error messages, which correspond to illegalities as defined
4980 in the Ada Reference Manual, the compiler detects two kinds of warning
4983 First, the compiler considers some constructs suspicious and generates a
4984 warning message to alert you to a possible error. Second, if the
4985 compiler detects a situation that is sure to raise an exception at
4986 run time, it generates a warning message. The following shows an example
4987 of warning messages:
4989 e.adb:4:24: warning: creation of object may raise Storage_Error
4990 e.adb:10:17: warning: static value out of range
4991 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4995 GNAT considers a large number of situations as appropriate
4996 for the generation of warning messages. As always, warnings are not
4997 definite indications of errors. For example, if you do an out-of-range
4998 assignment with the deliberate intention of raising a
4999 @code{Constraint_Error} exception, then the warning that may be
5000 issued does not indicate an error. Some of the situations for which GNAT
5001 issues warnings (at least some of the time) are given in the following
5002 list. This list is not complete, and new warnings are often added to
5003 subsequent versions of GNAT. The list is intended to give a general idea
5004 of the kinds of warnings that are generated.
5008 Possible infinitely recursive calls
5011 Out-of-range values being assigned
5014 Possible order of elaboration problems
5017 Assertions (pragma Assert) that are sure to fail
5023 Address clauses with possibly unaligned values, or where an attempt is
5024 made to overlay a smaller variable with a larger one.
5027 Fixed-point type declarations with a null range
5030 Direct_IO or Sequential_IO instantiated with a type that has access values
5033 Variables that are never assigned a value
5036 Variables that are referenced before being initialized
5039 Task entries with no corresponding @code{accept} statement
5042 Duplicate accepts for the same task entry in a @code{select}
5045 Objects that take too much storage
5048 Unchecked conversion between types of differing sizes
5051 Missing @code{return} statement along some execution path in a function
5054 Incorrect (unrecognized) pragmas
5057 Incorrect external names
5060 Allocation from empty storage pool
5063 Potentially blocking operation in protected type
5066 Suspicious parenthesization of expressions
5069 Mismatching bounds in an aggregate
5072 Attempt to return local value by reference
5075 Premature instantiation of a generic body
5078 Attempt to pack aliased components
5081 Out of bounds array subscripts
5084 Wrong length on string assignment
5087 Violations of style rules if style checking is enabled
5090 Unused @code{with} clauses
5093 @code{Bit_Order} usage that does not have any effect
5096 @code{Standard.Duration} used to resolve universal fixed expression
5099 Dereference of possibly null value
5102 Declaration that is likely to cause storage error
5105 Internal GNAT unit @code{with}'ed by application unit
5108 Values known to be out of range at compile time
5111 Unreferenced labels and variables
5114 Address overlays that could clobber memory
5117 Unexpected initialization when address clause present
5120 Bad alignment for address clause
5123 Useless type conversions
5126 Redundant assignment statements and other redundant constructs
5129 Useless exception handlers
5132 Accidental hiding of name by child unit
5135 Access before elaboration detected at compile time
5138 A range in a @code{for} loop that is known to be null or might be null
5143 The following section lists compiler switches that are available
5144 to control the handling of warning messages. It is also possible
5145 to exercise much finer control over what warnings are issued and
5146 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5147 gnat_rm, GNAT Reference manual}.
5152 @emph{Activate most optional warnings.}
5153 @cindex @option{-gnatwa} (@command{gcc})
5154 This switch activates most optional warning messages. See the remaining list
5155 in this section for details on optional warning messages that can be
5156 individually controlled. The warnings that are not turned on by this
5158 @option{-gnatwd} (implicit dereferencing),
5159 @option{-gnatwh} (hiding),
5160 @option{-gnatw.h} (holes (gaps) in record layouts)
5161 @option{-gnatw.i} (overlapping actuals),
5162 @option{-gnatwl} (elaboration warnings),
5163 @option{-gnatw.l} (inherited aspects),
5164 @option{-gnatw.o} (warn on values set by out parameters ignored),
5165 @option{-gnatwt} (tracking of deleted conditional code)
5166 and @option{-gnatw.u} (unordered enumeration),
5167 All other optional warnings are turned on.
5170 @emph{Suppress all optional errors.}
5171 @cindex @option{-gnatwA} (@command{gcc})
5172 This switch suppresses all optional warning messages, see remaining list
5173 in this section for details on optional warning messages that can be
5174 individually controlled. Note that unlike switch @option{-gnatws}, the
5175 use of switch @option{-gnatwA} does not suppress warnings that are
5176 normally given unconditionally and cannot be individually controlled
5177 (for example, the warning about a missing exit path in a function).
5178 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5179 the use of switch @option{-gnatwA} can be individually turned back
5180 on. For example the use of switch @option{-gnatwA} followed by
5181 switch @option{-gnatwd} will suppress all optional warnings except
5182 the warnings for implicit dereferencing.
5185 @emph{Activate warnings on failing assertions.}
5186 @cindex @option{-gnatw.a} (@command{gcc})
5187 @cindex Assert failures
5188 This switch activates warnings for assertions where the compiler can tell at
5189 compile time that the assertion will fail. Note that this warning is given
5190 even if assertions are disabled. The default is that such warnings are
5194 @emph{Suppress warnings on failing assertions.}
5195 @cindex @option{-gnatw.A} (@command{gcc})
5196 @cindex Assert failures
5197 This switch suppresses warnings for assertions where the compiler can tell at
5198 compile time that the assertion will fail.
5201 @emph{Activate warnings on bad fixed values.}
5202 @cindex @option{-gnatwb} (@command{gcc})
5203 @cindex Bad fixed values
5204 @cindex Fixed-point Small value
5206 This switch activates warnings for static fixed-point expressions whose
5207 value is not an exact multiple of Small. Such values are implementation
5208 dependent, since an implementation is free to choose either of the multiples
5209 that surround the value. GNAT always chooses the closer one, but this is not
5210 required behavior, and it is better to specify a value that is an exact
5211 multiple, ensuring predictable execution. The default is that such warnings
5215 @emph{Suppress warnings on bad fixed values.}
5216 @cindex @option{-gnatwB} (@command{gcc})
5217 This switch suppresses warnings for static fixed-point expressions whose
5218 value is not an exact multiple of Small.
5221 @emph{Activate warnings on biased representation.}
5222 @cindex @option{-gnatw.b} (@command{gcc})
5223 @cindex Biased representation
5224 This switch activates warnings when a size clause, value size clause, component
5225 clause, or component size clause forces the use of biased representation for an
5226 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5227 to represent 10/11). The default is that such warnings are generated.
5230 @emph{Suppress warnings on biased representation.}
5231 @cindex @option{-gnatwB} (@command{gcc})
5232 This switch suppresses warnings for representation clauses that force the use
5233 of biased representation.
5236 @emph{Activate warnings on conditionals.}
5237 @cindex @option{-gnatwc} (@command{gcc})
5238 @cindex Conditionals, constant
5239 This switch activates warnings for conditional expressions used in
5240 tests that are known to be True or False at compile time. The default
5241 is that such warnings are not generated.
5242 Note that this warning does
5243 not get issued for the use of boolean variables or constants whose
5244 values are known at compile time, since this is a standard technique
5245 for conditional compilation in Ada, and this would generate too many
5246 false positive warnings.
5248 This warning option also activates a special test for comparisons using
5249 the operators ``>='' and`` <=''.
5250 If the compiler can tell that only the equality condition is possible,
5251 then it will warn that the ``>'' or ``<'' part of the test
5252 is useless and that the operator could be replaced by ``=''.
5253 An example would be comparing a @code{Natural} variable <= 0.
5255 This warning option also generates warnings if
5256 one or both tests is optimized away in a membership test for integer
5257 values if the result can be determined at compile time. Range tests on
5258 enumeration types are not included, since it is common for such tests
5259 to include an end point.
5261 This warning can also be turned on using @option{-gnatwa}.
5264 @emph{Suppress warnings on conditionals.}
5265 @cindex @option{-gnatwC} (@command{gcc})
5266 This switch suppresses warnings for conditional expressions used in
5267 tests that are known to be True or False at compile time.
5270 @emph{Activate warnings on missing component clauses.}
5271 @cindex @option{-gnatw.c} (@command{gcc})
5272 @cindex Component clause, missing
5273 This switch activates warnings for record components where a record
5274 representation clause is present and has component clauses for the
5275 majority, but not all, of the components. A warning is given for each
5276 component for which no component clause is present.
5278 This warning can also be turned on using @option{-gnatwa}.
5281 @emph{Suppress warnings on missing component clauses.}
5282 @cindex @option{-gnatwC} (@command{gcc})
5283 This switch suppresses warnings for record components that are
5284 missing a component clause in the situation described above.
5287 @emph{Activate warnings on implicit dereferencing.}
5288 @cindex @option{-gnatwd} (@command{gcc})
5289 If this switch is set, then the use of a prefix of an access type
5290 in an indexed component, slice, or selected component without an
5291 explicit @code{.all} will generate a warning. With this warning
5292 enabled, access checks occur only at points where an explicit
5293 @code{.all} appears in the source code (assuming no warnings are
5294 generated as a result of this switch). The default is that such
5295 warnings are not generated.
5296 Note that @option{-gnatwa} does not affect the setting of
5297 this warning option.
5300 @emph{Suppress warnings on implicit dereferencing.}
5301 @cindex @option{-gnatwD} (@command{gcc})
5302 @cindex Implicit dereferencing
5303 @cindex Dereferencing, implicit
5304 This switch suppresses warnings for implicit dereferences in
5305 indexed components, slices, and selected components.
5308 @emph{Treat warnings and style checks as errors.}
5309 @cindex @option{-gnatwe} (@command{gcc})
5310 @cindex Warnings, treat as error
5311 This switch causes warning messages and style check messages to be
5313 The warning string still appears, but the warning messages are counted
5314 as errors, and prevent the generation of an object file. Note that this
5315 is the only -gnatw switch that affects the handling of style check messages.
5318 @emph{Activate every optional warning}
5319 @cindex @option{-gnatw.e} (@command{gcc})
5320 @cindex Warnings, activate every optional warning
5321 This switch activates all optional warnings, including those which
5322 are not activated by @code{-gnatwa}. The use of this switch is not
5323 recommended for normal use. If you turn this switch on, it is almost
5324 certain that you will get large numbers of useless warnings. The
5325 warnings that are excluded from @code{-gnatwa} are typically highly
5326 specialized warnings that are suitable for use only in code that has
5327 been specifically designed according to specialized coding rules.
5330 @emph{Activate warnings on unreferenced formals.}
5331 @cindex @option{-gnatwf} (@command{gcc})
5332 @cindex Formals, unreferenced
5333 This switch causes a warning to be generated if a formal parameter
5334 is not referenced in the body of the subprogram. This warning can
5335 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5336 default is that these warnings are not generated.
5339 @emph{Suppress warnings on unreferenced formals.}
5340 @cindex @option{-gnatwF} (@command{gcc})
5341 This switch suppresses warnings for unreferenced formal
5342 parameters. Note that the
5343 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5344 effect of warning on unreferenced entities other than subprogram
5348 @emph{Activate warnings on unrecognized pragmas.}
5349 @cindex @option{-gnatwg} (@command{gcc})
5350 @cindex Pragmas, unrecognized
5351 This switch causes a warning to be generated if an unrecognized
5352 pragma is encountered. Apart from issuing this warning, the
5353 pragma is ignored and has no effect. This warning can
5354 also be turned on using @option{-gnatwa}. The default
5355 is that such warnings are issued (satisfying the Ada Reference
5356 Manual requirement that such warnings appear).
5359 @emph{Suppress warnings on unrecognized pragmas.}
5360 @cindex @option{-gnatwG} (@command{gcc})
5361 This switch suppresses warnings for unrecognized pragmas.
5364 @emph{Activate warnings on hiding.}
5365 @cindex @option{-gnatwh} (@command{gcc})
5366 @cindex Hiding of Declarations
5367 This switch activates warnings on hiding declarations.
5368 A declaration is considered hiding
5369 if it is for a non-overloadable entity, and it declares an entity with the
5370 same name as some other entity that is directly or use-visible. The default
5371 is that such warnings are not generated.
5372 Note that @option{-gnatwa} does not affect the setting of this warning option.
5375 @emph{Suppress warnings on hiding.}
5376 @cindex @option{-gnatwH} (@command{gcc})
5377 This switch suppresses warnings on hiding declarations.
5380 @emph{Activate warnings on holes/gaps in records.}
5381 @cindex @option{-gnatw.h} (@command{gcc})
5382 @cindex Record Representation (gaps)
5383 This switch activates warnings on component clauses in record
5384 representation clauses that leave holes (gaps) in the record layout.
5385 If this warning option is active, then record representation clauses
5386 should specify a contiguous layout, adding unused fill fields if needed.
5387 Note that @option{-gnatwa} does not affect the setting of this warning option.
5390 @emph{Suppress warnings on holes/gaps in records.}
5391 @cindex @option{-gnatw.H} (@command{gcc})
5392 This switch suppresses warnings on component clauses in record
5393 representation clauses that leave holes (haps) in the record layout.
5396 @emph{Activate warnings on implementation units.}
5397 @cindex @option{-gnatwi} (@command{gcc})
5398 This switch activates warnings for a @code{with} of an internal GNAT
5399 implementation unit, defined as any unit from the @code{Ada},
5400 @code{Interfaces}, @code{GNAT},
5401 ^^@code{DEC},^ or @code{System}
5402 hierarchies that is not
5403 documented in either the Ada Reference Manual or the GNAT
5404 Programmer's Reference Manual. Such units are intended only
5405 for internal implementation purposes and should not be @code{with}'ed
5406 by user programs. The default is that such warnings are generated
5407 This warning can also be turned on using @option{-gnatwa}.
5410 @emph{Disable warnings on implementation units.}
5411 @cindex @option{-gnatwI} (@command{gcc})
5412 This switch disables warnings for a @code{with} of an internal GNAT
5413 implementation unit.
5416 @emph{Activate warnings on overlapping actuals.}
5417 @cindex @option{-gnatw.i} (@command{gcc})
5418 This switch enables a warning on statically detectable overlapping actuals in
5419 a subprogram call, when one of the actuals is an in-out parameter, and the
5420 types of the actuals are not by-copy types. The warning is off by default,
5421 and is not included under -gnatwa.
5424 @emph{Disable warnings on overlapping actuals.}
5425 @cindex @option{-gnatw.I} (@command{gcc})
5426 This switch disables warnings on overlapping actuals in a call..
5429 @emph{Activate warnings on obsolescent features (Annex J).}
5430 @cindex @option{-gnatwj} (@command{gcc})
5431 @cindex Features, obsolescent
5432 @cindex Obsolescent features
5433 If this warning option is activated, then warnings are generated for
5434 calls to subprograms marked with @code{pragma Obsolescent} and
5435 for use of features in Annex J of the Ada Reference Manual. In the
5436 case of Annex J, not all features are flagged. In particular use
5437 of the renamed packages (like @code{Text_IO}) and use of package
5438 @code{ASCII} are not flagged, since these are very common and
5439 would generate many annoying positive warnings. The default is that
5440 such warnings are not generated. This warning is also turned on by
5441 the use of @option{-gnatwa}.
5443 In addition to the above cases, warnings are also generated for
5444 GNAT features that have been provided in past versions but which
5445 have been superseded (typically by features in the new Ada standard).
5446 For example, @code{pragma Ravenscar} will be flagged since its
5447 function is replaced by @code{pragma Profile(Ravenscar)}.
5449 Note that this warning option functions differently from the
5450 restriction @code{No_Obsolescent_Features} in two respects.
5451 First, the restriction applies only to annex J features.
5452 Second, the restriction does flag uses of package @code{ASCII}.
5455 @emph{Suppress warnings on obsolescent features (Annex J).}
5456 @cindex @option{-gnatwJ} (@command{gcc})
5457 This switch disables warnings on use of obsolescent features.
5460 @emph{Activate warnings on variables that could be constants.}
5461 @cindex @option{-gnatwk} (@command{gcc})
5462 This switch activates warnings for variables that are initialized but
5463 never modified, and then could be declared constants. The default is that
5464 such warnings are not given.
5465 This warning can also be turned on using @option{-gnatwa}.
5468 @emph{Suppress warnings on variables that could be constants.}
5469 @cindex @option{-gnatwK} (@command{gcc})
5470 This switch disables warnings on variables that could be declared constants.
5473 @emph{Activate warnings for elaboration pragmas.}
5474 @cindex @option{-gnatwl} (@command{gcc})
5475 @cindex Elaboration, warnings
5476 This switch activates warnings on missing
5477 @code{Elaborate_All} and @code{Elaborate} pragmas.
5478 See the section in this guide on elaboration checking for details on
5479 when such pragmas should be used. In dynamic elaboration mode, this switch
5480 generations warnings about the need to add elaboration pragmas. Note however,
5481 that if you blindly follow these warnings, and add @code{Elaborate_All}
5482 warnings wherever they are recommended, you basically end up with the
5483 equivalent of the static elaboration model, which may not be what you want for
5484 legacy code for which the static model does not work.
5486 For the static model, the messages generated are labeled "info:" (for
5487 information messages). They are not warnings to add elaboration pragmas,
5488 merely informational messages showing what implicit elaboration pragmas
5489 have been added, for use in analyzing elaboration circularity problems.
5491 Warnings are also generated if you
5492 are using the static mode of elaboration, and a @code{pragma Elaborate}
5493 is encountered. The default is that such warnings
5495 This warning is not automatically turned on by the use of @option{-gnatwa}.
5498 @emph{Suppress warnings for elaboration pragmas.}
5499 @cindex @option{-gnatwL} (@command{gcc})
5500 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5501 See the section in this guide on elaboration checking for details on
5502 when such pragmas should be used.
5505 @emph{List inherited aspects.}
5506 @cindex @option{-gnatw.l} (@command{gcc})
5507 This switch causes the compiler to list inherited invariants,
5508 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5509 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5510 These messages are not automatically turned on by the use of @option{-gnatwa}.
5513 @emph{Suppress listing of inherited aspects.}
5514 @cindex @option{-gnatw.L} (@command{gcc})
5515 This switch suppresses listing of inherited aspects.
5518 @emph{Activate warnings on modified but unreferenced variables.}
5519 @cindex @option{-gnatwm} (@command{gcc})
5520 This switch activates warnings for variables that are assigned (using
5521 an initialization value or with one or more assignment statements) but
5522 whose value is never read. The warning is suppressed for volatile
5523 variables and also for variables that are renamings of other variables
5524 or for which an address clause is given.
5525 This warning can also be turned on using @option{-gnatwa}.
5526 The default is that these warnings are not given.
5529 @emph{Disable warnings on modified but unreferenced variables.}
5530 @cindex @option{-gnatwM} (@command{gcc})
5531 This switch disables warnings for variables that are assigned or
5532 initialized, but never read.
5535 @emph{Activate warnings on suspicious modulus values.}
5536 @cindex @option{-gnatw.m} (@command{gcc})
5537 This switch activates warnings for modulus values that seem suspicious.
5538 The cases caught are where the size is the same as the modulus (e.g.
5539 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5540 with no size clause. The guess in both cases is that 2**x was intended
5541 rather than x. In addition expressions of the form 2*x for small x
5542 generate a warning (the almost certainly accurate guess being that
5543 2**x was intended). The default is that these warnings are given.
5546 @emph{Disable warnings on suspicious modulus values.}
5547 @cindex @option{-gnatw.M} (@command{gcc})
5548 This switch disables warnings for suspicious modulus values.
5551 @emph{Set normal warnings mode.}
5552 @cindex @option{-gnatwn} (@command{gcc})
5553 This switch sets normal warning mode, in which enabled warnings are
5554 issued and treated as warnings rather than errors. This is the default
5555 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5556 an explicit @option{-gnatws} or
5557 @option{-gnatwe}. It also cancels the effect of the
5558 implicit @option{-gnatwe} that is activated by the
5559 use of @option{-gnatg}.
5562 @emph{Activate warnings on address clause overlays.}
5563 @cindex @option{-gnatwo} (@command{gcc})
5564 @cindex Address Clauses, warnings
5565 This switch activates warnings for possibly unintended initialization
5566 effects of defining address clauses that cause one variable to overlap
5567 another. The default is that such warnings are generated.
5568 This warning can also be turned on using @option{-gnatwa}.
5571 @emph{Suppress warnings on address clause overlays.}
5572 @cindex @option{-gnatwO} (@command{gcc})
5573 This switch suppresses warnings on possibly unintended initialization
5574 effects of defining address clauses that cause one variable to overlap
5578 @emph{Activate warnings on modified but unreferenced out parameters.}
5579 @cindex @option{-gnatw.o} (@command{gcc})
5580 This switch activates warnings for variables that are modified by using
5581 them as actuals for a call to a procedure with an out mode formal, where
5582 the resulting assigned value is never read. It is applicable in the case
5583 where there is more than one out mode formal. If there is only one out
5584 mode formal, the warning is issued by default (controlled by -gnatwu).
5585 The warning is suppressed for volatile
5586 variables and also for variables that are renamings of other variables
5587 or for which an address clause is given.
5588 The default is that these warnings are not given. Note that this warning
5589 is not included in -gnatwa, it must be activated explicitly.
5592 @emph{Disable warnings on modified but unreferenced out parameters.}
5593 @cindex @option{-gnatw.O} (@command{gcc})
5594 This switch suppresses warnings for variables that are modified by using
5595 them as actuals for a call to a procedure with an out mode formal, where
5596 the resulting assigned value is never read.
5599 @emph{Activate warnings on ineffective pragma Inlines.}
5600 @cindex @option{-gnatwp} (@command{gcc})
5601 @cindex Inlining, warnings
5602 This switch activates warnings for failure of front end inlining
5603 (activated by @option{-gnatN}) to inline a particular call. There are
5604 many reasons for not being able to inline a call, including most
5605 commonly that the call is too complex to inline. The default is
5606 that such warnings are not given.
5607 This warning can also be turned on using @option{-gnatwa}.
5608 Warnings on ineffective inlining by the gcc back-end can be activated
5609 separately, using the gcc switch -Winline.
5612 @emph{Suppress warnings on ineffective pragma Inlines.}
5613 @cindex @option{-gnatwP} (@command{gcc})
5614 This switch suppresses warnings on ineffective pragma Inlines. If the
5615 inlining mechanism cannot inline a call, it will simply ignore the
5619 @emph{Activate warnings on parameter ordering.}
5620 @cindex @option{-gnatw.p} (@command{gcc})
5621 @cindex Parameter order, warnings
5622 This switch activates warnings for cases of suspicious parameter
5623 ordering when the list of arguments are all simple identifiers that
5624 match the names of the formals, but are in a different order. The
5625 warning is suppressed if any use of named parameter notation is used,
5626 so this is the appropriate way to suppress a false positive (and
5627 serves to emphasize that the "misordering" is deliberate). The
5629 that such warnings are not given.
5630 This warning can also be turned on using @option{-gnatwa}.
5633 @emph{Suppress warnings on parameter ordering.}
5634 @cindex @option{-gnatw.P} (@command{gcc})
5635 This switch suppresses warnings on cases of suspicious parameter
5639 @emph{Activate warnings on questionable missing parentheses.}
5640 @cindex @option{-gnatwq} (@command{gcc})
5641 @cindex Parentheses, warnings
5642 This switch activates warnings for cases where parentheses are not used and
5643 the result is potential ambiguity from a readers point of view. For example
5644 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5645 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5646 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5647 follow the rule of always parenthesizing to make the association clear, and
5648 this warning switch warns if such parentheses are not present. The default
5649 is that these warnings are given.
5650 This warning can also be turned on using @option{-gnatwa}.
5653 @emph{Suppress warnings on questionable missing parentheses.}
5654 @cindex @option{-gnatwQ} (@command{gcc})
5655 This switch suppresses warnings for cases where the association is not
5656 clear and the use of parentheses is preferred.
5659 @emph{Activate warnings on redundant constructs.}
5660 @cindex @option{-gnatwr} (@command{gcc})
5661 This switch activates warnings for redundant constructs. The following
5662 is the current list of constructs regarded as redundant:
5666 Assignment of an item to itself.
5668 Type conversion that converts an expression to its own type.
5670 Use of the attribute @code{Base} where @code{typ'Base} is the same
5673 Use of pragma @code{Pack} when all components are placed by a record
5674 representation clause.
5676 Exception handler containing only a reraise statement (raise with no
5677 operand) which has no effect.
5679 Use of the operator abs on an operand that is known at compile time
5682 Comparison of boolean expressions to an explicit True value.
5685 This warning can also be turned on using @option{-gnatwa}.
5686 The default is that warnings for redundant constructs are not given.
5689 @emph{Suppress warnings on redundant constructs.}
5690 @cindex @option{-gnatwR} (@command{gcc})
5691 This switch suppresses warnings for redundant constructs.
5694 @emph{Activate warnings for object renaming function.}
5695 @cindex @option{-gnatw.r} (@command{gcc})
5696 This switch activates warnings for an object renaming that renames a
5697 function call, which is equivalent to a constant declaration (as
5698 opposed to renaming the function itself). The default is that these
5699 warnings are given. This warning can also be turned on using
5703 @emph{Suppress warnings for object renaming function.}
5704 @cindex @option{-gnatwT} (@command{gcc})
5705 This switch suppresses warnings for object renaming function.
5708 @emph{Suppress all warnings.}
5709 @cindex @option{-gnatws} (@command{gcc})
5710 This switch completely suppresses the
5711 output of all warning messages from the GNAT front end, including
5712 both warnings that can be controlled by switches described in this
5713 section, and those that are normally given unconditionally. The
5714 effect of this suppress action can only be cancelled by a subsequent
5715 use of the switch @option{-gnatwn}.
5717 Note that switch @option{-gnatws} does not suppress
5718 warnings from the @command{gcc} back end.
5719 To suppress these back end warnings as well, use the switch @option{-w}
5720 in addition to @option{-gnatws}. Also this switch has no effect on the
5721 handling of style check messages.
5724 @emph{Activate warnings on overridden size clauses.}
5725 @cindex @option{-gnatw.s} (@command{gcc})
5726 @cindex Record Representation (component sizes)
5727 This switch activates warnings on component clauses in record
5728 representation clauses where the length given overrides that
5729 specified by an explicit size clause for the component type. A
5730 warning is similarly given in the array case if a specified
5731 component size overrides an explicit size clause for the array
5733 Note that @option{-gnatwa} does not affect the setting of this warning option.
5736 @emph{Suppress warnings on overridden size clauses.}
5737 @cindex @option{-gnatw.S} (@command{gcc})
5738 This switch suppresses warnings on component clauses in record
5739 representation clauses that override size clauses, and similar
5740 warnings when an array component size overrides a size clause.
5743 @emph{Activate warnings for tracking of deleted conditional code.}
5744 @cindex @option{-gnatwt} (@command{gcc})
5745 @cindex Deactivated code, warnings
5746 @cindex Deleted code, warnings
5747 This switch activates warnings for tracking of code in conditionals (IF and
5748 CASE statements) that is detected to be dead code which cannot be executed, and
5749 which is removed by the front end. This warning is off by default, and is not
5750 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5751 useful for detecting deactivated code in certified applications.
5754 @emph{Suppress warnings for tracking of deleted conditional code.}
5755 @cindex @option{-gnatwT} (@command{gcc})
5756 This switch suppresses warnings for tracking of deleted conditional code.
5759 @emph{Activate warnings on suspicious contracts.}
5760 @cindex @option{-gnatw.t} (@command{gcc})
5761 This switch activates warnings on suspicious postconditions (whether a
5762 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5763 and suspicious contract cases (pragma @code{Contract_Case}). A
5764 function postcondition or contract case is suspicious when no postcondition
5765 or contract case for this function mentions the result of the function.
5766 A procedure postcondition or contract case is suspicious when it only
5767 refers to the pre-state of the procedure, because in that case it should
5768 rather be expressed as a precondition. The default is that such warnings
5769 are not generated. This warning can also be turned on using @option{-gnatwa}.
5772 @emph{Suppress warnings on suspicious contracts.}
5773 @cindex @option{-gnatw.T} (@command{gcc})
5774 This switch suppresses warnings on suspicious postconditions.
5777 @emph{Activate warnings on unused entities.}
5778 @cindex @option{-gnatwu} (@command{gcc})
5779 This switch activates warnings to be generated for entities that
5780 are declared but not referenced, and for units that are @code{with}'ed
5782 referenced. In the case of packages, a warning is also generated if
5783 no entities in the package are referenced. This means that if a with'ed
5784 package is referenced but the only references are in @code{use}
5785 clauses or @code{renames}
5786 declarations, a warning is still generated. A warning is also generated
5787 for a generic package that is @code{with}'ed but never instantiated.
5788 In the case where a package or subprogram body is compiled, and there
5789 is a @code{with} on the corresponding spec
5790 that is only referenced in the body,
5791 a warning is also generated, noting that the
5792 @code{with} can be moved to the body. The default is that
5793 such warnings are not generated.
5794 This switch also activates warnings on unreferenced formals
5795 (it includes the effect of @option{-gnatwf}).
5796 This warning can also be turned on using @option{-gnatwa}.
5799 @emph{Suppress warnings on unused entities.}
5800 @cindex @option{-gnatwU} (@command{gcc})
5801 This switch suppresses warnings for unused entities and packages.
5802 It also turns off warnings on unreferenced formals (and thus includes
5803 the effect of @option{-gnatwF}).
5806 @emph{Activate warnings on unordered enumeration types.}
5807 @cindex @option{-gnatw.u} (@command{gcc})
5808 This switch causes enumeration types to be considered as conceptually
5809 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5810 The effect is to generate warnings in clients that use explicit comparisons
5811 or subranges, since these constructs both treat objects of the type as
5812 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5813 which the type is declared, or its body or subunits.) Please refer to
5814 the description of pragma @code{Ordered} in the
5815 @cite{@value{EDITION} Reference Manual} for further details.
5816 The default is that such warnings are not generated.
5817 This warning is not automatically turned on by the use of @option{-gnatwa}.
5820 @emph{Deactivate warnings on unordered enumeration types.}
5821 @cindex @option{-gnatw.U} (@command{gcc})
5822 This switch causes all enumeration types to be considered as ordered, so
5823 that no warnings are given for comparisons or subranges for any type.
5826 @emph{Activate warnings on unassigned variables.}
5827 @cindex @option{-gnatwv} (@command{gcc})
5828 @cindex Unassigned variable warnings
5829 This switch activates warnings for access to variables which
5830 may not be properly initialized. The default is that
5831 such warnings are generated.
5832 This warning can also be turned on using @option{-gnatwa}.
5835 @emph{Suppress warnings on unassigned variables.}
5836 @cindex @option{-gnatwV} (@command{gcc})
5837 This switch suppresses warnings for access to variables which
5838 may not be properly initialized.
5839 For variables of a composite type, the warning can also be suppressed in
5840 Ada 2005 by using a default initialization with a box. For example, if
5841 Table is an array of records whose components are only partially uninitialized,
5842 then the following code:
5844 @smallexample @c ada
5845 Tab : Table := (others => <>);
5848 will suppress warnings on subsequent statements that access components
5852 @emph{Activate info messages for non-default bit order.}
5853 @cindex @option{-gnatw.v} (@command{gcc})
5854 @cindex bit order warnings
5855 This switch activates messages (labeled "info", they are not warnings,
5856 just informational messages) about the effects of non-default bit-order
5857 on records to which a component clause is applied. The effect of specifying
5858 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5859 these messages, which are given by default, are useful in understanding the
5860 exact consequences of using this feature. These messages
5861 can also be turned on using @option{-gnatwa}
5864 @emph{Suppress info messages for non-default bit order.}
5865 @cindex @option{-gnatw.V} (@command{gcc})
5866 This switch suppresses information messages for the effects of specifying
5867 non-default bit order on record components with component clauses.
5870 @emph{Activate warnings on wrong low bound assumption.}
5871 @cindex @option{-gnatww} (@command{gcc})
5872 @cindex String indexing warnings
5873 This switch activates warnings for indexing an unconstrained string parameter
5874 with a literal or S'Length. This is a case where the code is assuming that the
5875 low bound is one, which is in general not true (for example when a slice is
5876 passed). The default is that such warnings are generated.
5877 This warning can also be turned on using @option{-gnatwa}.
5880 @emph{Suppress warnings on wrong low bound assumption.}
5881 @cindex @option{-gnatwW} (@command{gcc})
5882 This switch suppresses warnings for indexing an unconstrained string parameter
5883 with a literal or S'Length. Note that this warning can also be suppressed
5884 in a particular case by adding an
5885 assertion that the lower bound is 1,
5886 as shown in the following example.
5888 @smallexample @c ada
5889 procedure K (S : String) is
5890 pragma Assert (S'First = 1);
5895 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5896 @cindex @option{-gnatw.w} (@command{gcc})
5897 @cindex Warnings Off control
5898 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5899 where either the pragma is entirely useless (because it suppresses no
5900 warnings), or it could be replaced by @code{pragma Unreferenced} or
5901 @code{pragma Unmodified}. The default is that these warnings are not given.
5902 Note that this warning is not included in -gnatwa, it must be
5903 activated explicitly.
5906 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5907 @cindex @option{-gnatw.W} (@command{gcc})
5908 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5911 @emph{Activate warnings on Export/Import pragmas.}
5912 @cindex @option{-gnatwx} (@command{gcc})
5913 @cindex Export/Import pragma warnings
5914 This switch activates warnings on Export/Import pragmas when
5915 the compiler detects a possible conflict between the Ada and
5916 foreign language calling sequences. For example, the use of
5917 default parameters in a convention C procedure is dubious
5918 because the C compiler cannot supply the proper default, so
5919 a warning is issued. The default is that such warnings are
5921 This warning can also be turned on using @option{-gnatwa}.
5924 @emph{Suppress warnings on Export/Import pragmas.}
5925 @cindex @option{-gnatwX} (@command{gcc})
5926 This switch suppresses warnings on Export/Import pragmas.
5927 The sense of this is that you are telling the compiler that
5928 you know what you are doing in writing the pragma, and it
5929 should not complain at you.
5932 @emph{Activate warnings for No_Exception_Propagation mode.}
5933 @cindex @option{-gnatwm} (@command{gcc})
5934 This switch activates warnings for exception usage when pragma Restrictions
5935 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5936 explicit exception raises which are not covered by a local handler, and for
5937 exception handlers which do not cover a local raise. The default is that these
5938 warnings are not given.
5941 @emph{Disable warnings for No_Exception_Propagation mode.}
5942 This switch disables warnings for exception usage when pragma Restrictions
5943 (No_Exception_Propagation) is in effect.
5946 @emph{Activate warnings for Ada compatibility issues.}
5947 @cindex @option{-gnatwy} (@command{gcc})
5948 @cindex Ada compatibility issues warnings
5949 For the most part, newer versions of Ada are upwards compatible
5950 with older versions. For example, Ada 2005 programs will almost
5951 always work when compiled as Ada 2012.
5952 However there are some exceptions (for example the fact that
5953 @code{some} is now a reserved word in Ada 2012). This
5954 switch activates several warnings to help in identifying
5955 and correcting such incompatibilities. The default is that
5956 these warnings are generated. Note that at one point Ada 2005
5957 was called Ada 0Y, hence the choice of character.
5958 This warning can also be turned on using @option{-gnatwa}.
5961 @emph{Disable warnings for Ada compatibility issues.}
5962 @cindex @option{-gnatwY} (@command{gcc})
5963 @cindex Ada compatibility issues warnings
5964 This switch suppresses the warnings intended to help in identifying
5965 incompatibilities between Ada language versions.
5968 @emph{Activate warnings on unchecked conversions.}
5969 @cindex @option{-gnatwz} (@command{gcc})
5970 @cindex Unchecked_Conversion warnings
5971 This switch activates warnings for unchecked conversions
5972 where the types are known at compile time to have different
5974 is that such warnings are generated. Warnings are also
5975 generated for subprogram pointers with different conventions,
5976 and, on VMS only, for data pointers with different conventions.
5977 This warning can also be turned on using @option{-gnatwa}.
5980 @emph{Suppress warnings on unchecked conversions.}
5981 @cindex @option{-gnatwZ} (@command{gcc})
5982 This switch suppresses warnings for unchecked conversions
5983 where the types are known at compile time to have different
5984 sizes or conventions.
5986 @item ^-Wunused^WARNINGS=UNUSED^
5987 @cindex @option{-Wunused}
5988 The warnings controlled by the @option{-gnatw} switch are generated by
5989 the front end of the compiler. The @option{GCC} back end can provide
5990 additional warnings and they are controlled by the @option{-W} switch.
5991 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5992 warnings for entities that are declared but not referenced.
5994 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5995 @cindex @option{-Wuninitialized}
5996 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5997 the back end warning for uninitialized variables. This switch must be
5998 used in conjunction with an optimization level greater than zero.
6000 @item -Wstack-usage=@var{len}
6001 @cindex @option{-Wstack-usage}
6002 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
6003 See @ref{Static Stack Usage Analysis} for details.
6005 @item ^-Wall^/ALL_BACK_END_WARNINGS^
6006 @cindex @option{-Wall}
6007 This switch enables most warnings from the @option{GCC} back end.
6008 The code generator detects a number of warning situations that are missed
6009 by the @option{GNAT} front end, and this switch can be used to activate them.
6010 The use of this switch also sets the default front end warning mode to
6011 @option{-gnatwa}, that is, most front end warnings activated as well.
6013 @item ^-w^/NO_BACK_END_WARNINGS^
6015 Conversely, this switch suppresses warnings from the @option{GCC} back end.
6016 The use of this switch also sets the default front end warning mode to
6017 @option{-gnatws}, that is, front end warnings suppressed as well.
6023 A string of warning parameters can be used in the same parameter. For example:
6030 will turn on all optional warnings except for unrecognized pragma warnings,
6031 and also specify that warnings should be treated as errors.
6034 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
6077 @node Debugging and Assertion Control
6078 @subsection Debugging and Assertion Control
6082 @cindex @option{-gnata} (@command{gcc})
6088 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6089 are ignored. This switch, where @samp{a} stands for assert, causes
6090 @code{Assert} and @code{Debug} pragmas to be activated.
6092 The pragmas have the form:
6096 @b{pragma} Assert (@var{Boolean-expression} @r{[},
6097 @var{static-string-expression}@r{]})
6098 @b{pragma} Debug (@var{procedure call})
6103 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6104 If the result is @code{True}, the pragma has no effect (other than
6105 possible side effects from evaluating the expression). If the result is
6106 @code{False}, the exception @code{Assert_Failure} declared in the package
6107 @code{System.Assertions} is
6108 raised (passing @var{static-string-expression}, if present, as the
6109 message associated with the exception). If no string expression is
6110 given the default is a string giving the file name and line number
6113 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6114 @code{pragma Debug} may appear within a declaration sequence, allowing
6115 debugging procedures to be called between declarations.
6118 @item /DEBUG@r{[}=debug-level@r{]}
6120 Specifies how much debugging information is to be included in
6121 the resulting object file where 'debug-level' is one of the following:
6124 Include both debugger symbol records and traceback
6126 This is the default setting.
6128 Include both debugger symbol records and traceback in
6131 Excludes both debugger symbol records and traceback
6132 the object file. Same as /NODEBUG.
6134 Includes only debugger symbol records in the object
6135 file. Note that this doesn't include traceback information.
6140 @node Validity Checking
6141 @subsection Validity Checking
6142 @findex Validity Checking
6145 The Ada Reference Manual defines the concept of invalid values (see
6146 RM 13.9.1). The primary source of invalid values is uninitialized
6147 variables. A scalar variable that is left uninitialized may contain
6148 an invalid value; the concept of invalid does not apply to access or
6151 It is an error to read an invalid value, but the RM does not require
6152 run-time checks to detect such errors, except for some minimal
6153 checking to prevent erroneous execution (i.e. unpredictable
6154 behavior). This corresponds to the @option{-gnatVd} switch below,
6155 which is the default. For example, by default, if the expression of a
6156 case statement is invalid, it will raise Constraint_Error rather than
6157 causing a wild jump, and if an array index on the left-hand side of an
6158 assignment is invalid, it will raise Constraint_Error rather than
6159 overwriting an arbitrary memory location.
6161 The @option{-gnatVa} may be used to enable additional validity checks,
6162 which are not required by the RM. These checks are often very
6163 expensive (which is why the RM does not require them). These checks
6164 are useful in tracking down uninitialized variables, but they are
6165 not usually recommended for production builds.
6167 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6168 control; you can enable whichever validity checks you desire. However,
6169 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6170 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6171 sufficient for non-debugging use.
6173 The @option{-gnatB} switch tells the compiler to assume that all
6174 values are valid (that is, within their declared subtype range)
6175 except in the context of a use of the Valid attribute. This means
6176 the compiler can generate more efficient code, since the range
6177 of values is better known at compile time. However, an uninitialized
6178 variable can cause wild jumps and memory corruption in this mode.
6180 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6181 checking mode as described below.
6183 The @code{x} argument is a string of letters that
6184 indicate validity checks that are performed or not performed in addition
6185 to the default checks required by Ada as described above.
6188 The options allowed for this qualifier
6189 indicate validity checks that are performed or not performed in addition
6190 to the default checks required by Ada as described above.
6196 @emph{All validity checks.}
6197 @cindex @option{-gnatVa} (@command{gcc})
6198 All validity checks are turned on.
6200 That is, @option{-gnatVa} is
6201 equivalent to @option{gnatVcdfimorst}.
6205 @emph{Validity checks for copies.}
6206 @cindex @option{-gnatVc} (@command{gcc})
6207 The right hand side of assignments, and the initializing values of
6208 object declarations are validity checked.
6211 @emph{Default (RM) validity checks.}
6212 @cindex @option{-gnatVd} (@command{gcc})
6213 Some validity checks are done by default following normal Ada semantics
6215 A check is done in case statements that the expression is within the range
6216 of the subtype. If it is not, Constraint_Error is raised.
6217 For assignments to array components, a check is done that the expression used
6218 as index is within the range. If it is not, Constraint_Error is raised.
6219 Both these validity checks may be turned off using switch @option{-gnatVD}.
6220 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6221 switch @option{-gnatVd} will leave the checks turned on.
6222 Switch @option{-gnatVD} should be used only if you are sure that all such
6223 expressions have valid values. If you use this switch and invalid values
6224 are present, then the program is erroneous, and wild jumps or memory
6225 overwriting may occur.
6228 @emph{Validity checks for elementary components.}
6229 @cindex @option{-gnatVe} (@command{gcc})
6230 In the absence of this switch, assignments to record or array components are
6231 not validity checked, even if validity checks for assignments generally
6232 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6233 require valid data, but assignment of individual components does. So for
6234 example, there is a difference between copying the elements of an array with a
6235 slice assignment, compared to assigning element by element in a loop. This
6236 switch allows you to turn off validity checking for components, even when they
6237 are assigned component by component.
6240 @emph{Validity checks for floating-point values.}
6241 @cindex @option{-gnatVf} (@command{gcc})
6242 In the absence of this switch, validity checking occurs only for discrete
6243 values. If @option{-gnatVf} is specified, then validity checking also applies
6244 for floating-point values, and NaNs and infinities are considered invalid,
6245 as well as out of range values for constrained types. Note that this means
6246 that standard IEEE infinity mode is not allowed. The exact contexts
6247 in which floating-point values are checked depends on the setting of other
6248 options. For example,
6249 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6250 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6251 (the order does not matter) specifies that floating-point parameters of mode
6252 @code{in} should be validity checked.
6255 @emph{Validity checks for @code{in} mode parameters}
6256 @cindex @option{-gnatVi} (@command{gcc})
6257 Arguments for parameters of mode @code{in} are validity checked in function
6258 and procedure calls at the point of call.
6261 @emph{Validity checks for @code{in out} mode parameters.}
6262 @cindex @option{-gnatVm} (@command{gcc})
6263 Arguments for parameters of mode @code{in out} are validity checked in
6264 procedure calls at the point of call. The @code{'m'} here stands for
6265 modify, since this concerns parameters that can be modified by the call.
6266 Note that there is no specific option to test @code{out} parameters,
6267 but any reference within the subprogram will be tested in the usual
6268 manner, and if an invalid value is copied back, any reference to it
6269 will be subject to validity checking.
6272 @emph{No validity checks.}
6273 @cindex @option{-gnatVn} (@command{gcc})
6274 This switch turns off all validity checking, including the default checking
6275 for case statements and left hand side subscripts. Note that the use of
6276 the switch @option{-gnatp} suppresses all run-time checks, including
6277 validity checks, and thus implies @option{-gnatVn}. When this switch
6278 is used, it cancels any other @option{-gnatV} previously issued.
6281 @emph{Validity checks for operator and attribute operands.}
6282 @cindex @option{-gnatVo} (@command{gcc})
6283 Arguments for predefined operators and attributes are validity checked.
6284 This includes all operators in package @code{Standard},
6285 the shift operators defined as intrinsic in package @code{Interfaces}
6286 and operands for attributes such as @code{Pos}. Checks are also made
6287 on individual component values for composite comparisons, and on the
6288 expressions in type conversions and qualified expressions. Checks are
6289 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6292 @emph{Validity checks for parameters.}
6293 @cindex @option{-gnatVp} (@command{gcc})
6294 This controls the treatment of parameters within a subprogram (as opposed
6295 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6296 of parameters on a call. If either of these call options is used, then
6297 normally an assumption is made within a subprogram that the input arguments
6298 have been validity checking at the point of call, and do not need checking
6299 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6300 is not made, and parameters are not assumed to be valid, so their validity
6301 will be checked (or rechecked) within the subprogram.
6304 @emph{Validity checks for function returns.}
6305 @cindex @option{-gnatVr} (@command{gcc})
6306 The expression in @code{return} statements in functions is validity
6310 @emph{Validity checks for subscripts.}
6311 @cindex @option{-gnatVs} (@command{gcc})
6312 All subscripts expressions are checked for validity, whether they appear
6313 on the right side or left side (in default mode only left side subscripts
6314 are validity checked).
6317 @emph{Validity checks for tests.}
6318 @cindex @option{-gnatVt} (@command{gcc})
6319 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6320 statements are checked, as well as guard expressions in entry calls.
6325 The @option{-gnatV} switch may be followed by
6326 ^a string of letters^a list of options^
6327 to turn on a series of validity checking options.
6329 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6330 specifies that in addition to the default validity checking, copies and
6331 function return expressions are to be validity checked.
6332 In order to make it easier
6333 to specify the desired combination of effects,
6335 the upper case letters @code{CDFIMORST} may
6336 be used to turn off the corresponding lower case option.
6339 the prefix @code{NO} on an option turns off the corresponding validity
6342 @item @code{NOCOPIES}
6343 @item @code{NODEFAULT}
6344 @item @code{NOFLOATS}
6345 @item @code{NOIN_PARAMS}
6346 @item @code{NOMOD_PARAMS}
6347 @item @code{NOOPERANDS}
6348 @item @code{NORETURNS}
6349 @item @code{NOSUBSCRIPTS}
6350 @item @code{NOTESTS}
6354 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6355 turns on all validity checking options except for
6356 checking of @code{@b{in out}} procedure arguments.
6358 The specification of additional validity checking generates extra code (and
6359 in the case of @option{-gnatVa} the code expansion can be substantial).
6360 However, these additional checks can be very useful in detecting
6361 uninitialized variables, incorrect use of unchecked conversion, and other
6362 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6363 is useful in conjunction with the extra validity checking, since this
6364 ensures that wherever possible uninitialized variables have invalid values.
6366 See also the pragma @code{Validity_Checks} which allows modification of
6367 the validity checking mode at the program source level, and also allows for
6368 temporary disabling of validity checks.
6370 @node Style Checking
6371 @subsection Style Checking
6372 @findex Style checking
6375 The @option{-gnaty^x^(option,option,@dots{})^} switch
6376 @cindex @option{-gnaty} (@command{gcc})
6377 causes the compiler to
6378 enforce specified style rules. A limited set of style rules has been used
6379 in writing the GNAT sources themselves. This switch allows user programs
6380 to activate all or some of these checks. If the source program fails a
6381 specified style check, an appropriate message is given, preceded by
6382 the character sequence ``(style)''. This message does not prevent
6383 successful compilation (unless the @option{-gnatwe} switch is used).
6385 Note that this is by no means intended to be a general facility for
6386 checking arbitrary coding standards. It is simply an embedding of the
6387 style rules we have chosen for the GNAT sources. If you are starting
6388 a project which does not have established style standards, you may
6389 find it useful to adopt the entire set of GNAT coding standards, or
6390 some subset of them. If you already have an established set of coding
6391 standards, then it may be that selected style checking options do
6392 indeed correspond to choices you have made, but for general checking
6393 of an existing set of coding rules, you should look to the gnatcheck
6394 tool, which is designed for that purpose.
6397 @code{(option,option,@dots{})} is a sequence of keywords
6400 The string @var{x} is a sequence of letters or digits
6402 indicating the particular style
6403 checks to be performed. The following checks are defined:
6408 @emph{Specify indentation level.}
6409 If a digit from 1-9 appears
6410 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6411 then proper indentation is checked, with the digit indicating the
6412 indentation level required. A value of zero turns off this style check.
6413 The general style of required indentation is as specified by
6414 the examples in the Ada Reference Manual. Full line comments must be
6415 aligned with the @code{--} starting on a column that is a multiple of
6416 the alignment level, or they may be aligned the same way as the following
6417 non-blank line (this is useful when full line comments appear in the middle
6421 @emph{Check attribute casing.}
6422 Attribute names, including the case of keywords such as @code{digits}
6423 used as attributes names, must be written in mixed case, that is, the
6424 initial letter and any letter following an underscore must be uppercase.
6425 All other letters must be lowercase.
6427 @item ^A^ARRAY_INDEXES^
6428 @emph{Use of array index numbers in array attributes.}
6429 When using the array attributes First, Last, Range,
6430 or Length, the index number must be omitted for one-dimensional arrays
6431 and is required for multi-dimensional arrays.
6434 @emph{Blanks not allowed at statement end.}
6435 Trailing blanks are not allowed at the end of statements. The purpose of this
6436 rule, together with h (no horizontal tabs), is to enforce a canonical format
6437 for the use of blanks to separate source tokens.
6439 @item ^B^BOOLEAN_OPERATORS^
6440 @emph{Check Boolean operators.}
6441 The use of AND/OR operators is not permitted except in the cases of modular
6442 operands, array operands, and simple stand-alone boolean variables or
6443 boolean constants. In all other cases @code{and then}/@code{or else} are
6447 @emph{Check comments, double space.}
6448 Comments must meet the following set of rules:
6453 The ``@code{--}'' that starts the column must either start in column one,
6454 or else at least one blank must precede this sequence.
6457 Comments that follow other tokens on a line must have at least one blank
6458 following the ``@code{--}'' at the start of the comment.
6461 Full line comments must have at least two blanks following the
6462 ``@code{--}'' that starts the comment, with the following exceptions.
6465 A line consisting only of the ``@code{--}'' characters, possibly preceded
6466 by blanks is permitted.
6469 A comment starting with ``@code{--x}'' where @code{x} is a special character
6471 This allows proper processing of the output generated by specialized tools
6472 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6474 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6475 special character is defined as being in one of the ASCII ranges
6476 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6477 Note that this usage is not permitted
6478 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6481 A line consisting entirely of minus signs, possibly preceded by blanks, is
6482 permitted. This allows the construction of box comments where lines of minus
6483 signs are used to form the top and bottom of the box.
6486 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6487 least one blank follows the initial ``@code{--}''. Together with the preceding
6488 rule, this allows the construction of box comments, as shown in the following
6491 ---------------------------
6492 -- This is a box comment --
6493 -- with two text lines. --
6494 ---------------------------
6499 @emph{Check comments, single space.}
6500 This is identical to @code{^c^COMMENTS^} except that only one space
6501 is required following the @code{--} of a comment instead of two.
6503 @item ^d^DOS_LINE_ENDINGS^
6504 @emph{Check no DOS line terminators present.}
6505 All lines must be terminated by a single ASCII.LF
6506 character (in particular the DOS line terminator sequence CR/LF is not
6510 @emph{Check end/exit labels.}
6511 Optional labels on @code{end} statements ending subprograms and on
6512 @code{exit} statements exiting named loops, are required to be present.
6515 @emph{No form feeds or vertical tabs.}
6516 Neither form feeds nor vertical tab characters are permitted
6520 @emph{GNAT style mode.}
6521 The set of style check switches is set to match that used by the GNAT sources.
6522 This may be useful when developing code that is eventually intended to be
6523 incorporated into GNAT. For further details, see GNAT sources.
6526 @emph{No horizontal tabs.}
6527 Horizontal tab characters are not permitted in the source text.
6528 Together with the b (no blanks at end of line) check, this
6529 enforces a canonical form for the use of blanks to separate
6533 @emph{Check if-then layout.}
6534 The keyword @code{then} must appear either on the same
6535 line as corresponding @code{if}, or on a line on its own, lined
6536 up under the @code{if} with at least one non-blank line in between
6537 containing all or part of the condition to be tested.
6540 @emph{check mode IN keywords.}
6541 Mode @code{in} (the default mode) is not
6542 allowed to be given explicitly. @code{in out} is fine,
6543 but not @code{in} on its own.
6546 @emph{Check keyword casing.}
6547 All keywords must be in lower case (with the exception of keywords
6548 such as @code{digits} used as attribute names to which this check
6552 @emph{Check layout.}
6553 Layout of statement and declaration constructs must follow the
6554 recommendations in the Ada Reference Manual, as indicated by the
6555 form of the syntax rules. For example an @code{else} keyword must
6556 be lined up with the corresponding @code{if} keyword.
6558 There are two respects in which the style rule enforced by this check
6559 option are more liberal than those in the Ada Reference Manual. First
6560 in the case of record declarations, it is permissible to put the
6561 @code{record} keyword on the same line as the @code{type} keyword, and
6562 then the @code{end} in @code{end record} must line up under @code{type}.
6563 This is also permitted when the type declaration is split on two lines.
6564 For example, any of the following three layouts is acceptable:
6566 @smallexample @c ada
6589 Second, in the case of a block statement, a permitted alternative
6590 is to put the block label on the same line as the @code{declare} or
6591 @code{begin} keyword, and then line the @code{end} keyword up under
6592 the block label. For example both the following are permitted:
6594 @smallexample @c ada
6612 The same alternative format is allowed for loops. For example, both of
6613 the following are permitted:
6615 @smallexample @c ada
6617 Clear : while J < 10 loop
6628 @item ^Lnnn^MAX_NESTING=nnn^
6629 @emph{Set maximum nesting level.}
6630 The maximum level of nesting of constructs (including subprograms, loops,
6631 blocks, packages, and conditionals) may not exceed the given value
6632 @option{nnn}. A value of zero disconnects this style check.
6634 @item ^m^LINE_LENGTH^
6635 @emph{Check maximum line length.}
6636 The length of source lines must not exceed 79 characters, including
6637 any trailing blanks. The value of 79 allows convenient display on an
6638 80 character wide device or window, allowing for possible special
6639 treatment of 80 character lines. Note that this count is of
6640 characters in the source text. This means that a tab character counts
6641 as one character in this count but a wide character sequence counts as
6642 a single character (however many bytes are needed in the encoding).
6644 @item ^Mnnn^MAX_LENGTH=nnn^
6645 @emph{Set maximum line length.}
6646 The length of lines must not exceed the
6647 given value @option{nnn}. The maximum value that can be specified is 32767.
6649 @item ^n^STANDARD_CASING^
6650 @emph{Check casing of entities in Standard.}
6651 Any identifier from Standard must be cased
6652 to match the presentation in the Ada Reference Manual (for example,
6653 @code{Integer} and @code{ASCII.NUL}).
6656 @emph{Turn off all style checks.}
6657 All style check options are turned off.
6659 @item ^o^ORDERED_SUBPROGRAMS^
6660 @emph{Check order of subprogram bodies.}
6661 All subprogram bodies in a given scope
6662 (e.g.@: a package body) must be in alphabetical order. The ordering
6663 rule uses normal Ada rules for comparing strings, ignoring casing
6664 of letters, except that if there is a trailing numeric suffix, then
6665 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6668 @item ^O^OVERRIDING_INDICATORS^
6669 @emph{Check that overriding subprograms are explicitly marked as such.}
6670 The declaration of a primitive operation of a type extension that overrides
6671 an inherited operation must carry an overriding indicator.
6674 @emph{Check pragma casing.}
6675 Pragma names must be written in mixed case, that is, the
6676 initial letter and any letter following an underscore must be uppercase.
6677 All other letters must be lowercase.
6679 @item ^r^REFERENCES^
6680 @emph{Check references.}
6681 All identifier references must be cased in the same way as the
6682 corresponding declaration. No specific casing style is imposed on
6683 identifiers. The only requirement is for consistency of references
6687 @emph{Check separate specs.}
6688 Separate declarations (``specs'') are required for subprograms (a
6689 body is not allowed to serve as its own declaration). The only
6690 exception is that parameterless library level procedures are
6691 not required to have a separate declaration. This exception covers
6692 the most frequent form of main program procedures.
6694 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6695 @emph{Check no statements after @code{then}/@code{else}.}
6696 No statements are allowed
6697 on the same line as a @code{then} or @code{else} keyword following the
6698 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6699 affected, and a special exception allows a pragma to appear after @code{else}.
6702 @emph{Check token spacing.}
6703 The following token spacing rules are enforced:
6708 The keywords @code{abs} and @code{not} must be followed by a space.
6711 The token @code{=>} must be surrounded by spaces.
6714 The token @code{<>} must be preceded by a space or a left parenthesis.
6717 Binary operators other than @code{**} must be surrounded by spaces.
6718 There is no restriction on the layout of the @code{**} binary operator.
6721 Colon must be surrounded by spaces.
6724 Colon-equal (assignment, initialization) must be surrounded by spaces.
6727 Comma must be the first non-blank character on the line, or be
6728 immediately preceded by a non-blank character, and must be followed
6732 If the token preceding a left parenthesis ends with a letter or digit, then
6733 a space must separate the two tokens.
6736 if the token following a right parenthesis starts with a letter or digit, then
6737 a space must separate the two tokens.
6740 A right parenthesis must either be the first non-blank character on
6741 a line, or it must be preceded by a non-blank character.
6744 A semicolon must not be preceded by a space, and must not be followed by
6745 a non-blank character.
6748 A unary plus or minus may not be followed by a space.
6751 A vertical bar must be surrounded by spaces.
6755 Exactly one blank (and no other white space) must appear between
6756 a @code{not} token and a following @code{in} token.
6758 @item ^u^UNNECESSARY_BLANK_LINES^
6759 @emph{Check unnecessary blank lines.}
6760 Unnecessary blank lines are not allowed. A blank line is considered
6761 unnecessary if it appears at the end of the file, or if more than
6762 one blank line occurs in sequence.
6764 @item ^x^XTRA_PARENS^
6765 @emph{Check extra parentheses.}
6766 Unnecessary extra level of parentheses (C-style) are not allowed
6767 around conditions in @code{if} statements, @code{while} statements and
6768 @code{exit} statements.
6770 @item ^y^ALL_BUILTIN^
6771 @emph{Set all standard style check options}
6772 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6773 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6774 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6775 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6779 @emph{Remove style check options}
6780 This causes any subsequent options in the string to act as canceling the
6781 corresponding style check option. To cancel maximum nesting level control,
6782 use @option{L} parameter witout any integer value after that, because any
6783 digit following @option{-} in the parameter string of the @option{-gnaty}
6784 option will be threated as canceling indentation check. The same is true
6785 for @option{M} parameter. @option{y} and @option{N} parameters are not
6786 allowed after @option{-}.
6789 This causes any subsequent options in the string to enable the corresponding
6790 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6796 @emph{Removing style check options}
6797 If the name of a style check is preceded by @option{NO} then the corresponding
6798 style check is turned off. For example @option{NOCOMMENTS} turns off style
6799 checking for comments.
6804 In the above rules, appearing in column one is always permitted, that is,
6805 counts as meeting either a requirement for a required preceding space,
6806 or as meeting a requirement for no preceding space.
6808 Appearing at the end of a line is also always permitted, that is, counts
6809 as meeting either a requirement for a following space, or as meeting
6810 a requirement for no following space.
6813 If any of these style rules is violated, a message is generated giving
6814 details on the violation. The initial characters of such messages are
6815 always ``@code{(style)}''. Note that these messages are treated as warning
6816 messages, so they normally do not prevent the generation of an object
6817 file. The @option{-gnatwe} switch can be used to treat warning messages,
6818 including style messages, as fatal errors.
6822 @option{-gnaty} on its own (that is not
6823 followed by any letters or digits) is equivalent
6824 to the use of @option{-gnatyy} as described above, that is all
6825 built-in standard style check options are enabled.
6829 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6830 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6831 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6841 clears any previously set style checks.
6843 @node Run-Time Checks
6844 @subsection Run-Time Checks
6845 @cindex Division by zero
6846 @cindex Access before elaboration
6847 @cindex Checks, division by zero
6848 @cindex Checks, access before elaboration
6849 @cindex Checks, stack overflow checking
6852 By default, the following checks are suppressed: integer overflow
6853 checks, stack overflow checks, and checks for access before
6854 elaboration on subprogram calls. All other checks, including range
6855 checks and array bounds checks, are turned on by default. The
6856 following @command{gcc} switches refine this default behavior.
6861 @cindex @option{-gnatp} (@command{gcc})
6862 @cindex Suppressing checks
6863 @cindex Checks, suppressing
6865 This switch causes the unit to be compiled
6866 as though @code{pragma Suppress (All_checks)}
6867 had been present in the source. Validity checks are also eliminated (in
6868 other words @option{-gnatp} also implies @option{-gnatVn}.
6869 Use this switch to improve the performance
6870 of the code at the expense of safety in the presence of invalid data or
6873 Note that when checks are suppressed, the compiler is allowed, but not
6874 required, to omit the checking code. If the run-time cost of the
6875 checking code is zero or near-zero, the compiler will generate it even
6876 if checks are suppressed. In particular, if the compiler can prove
6877 that a certain check will necessarily fail, it will generate code to
6878 do an unconditional ``raise'', even if checks are suppressed. The
6879 compiler warns in this case. Another case in which checks may not be
6880 eliminated is when they are embedded in certain run time routines such
6881 as math library routines.
6883 Of course, run-time checks are omitted whenever the compiler can prove
6884 that they will not fail, whether or not checks are suppressed.
6886 Note that if you suppress a check that would have failed, program
6887 execution is erroneous, which means the behavior is totally
6888 unpredictable. The program might crash, or print wrong answers, or
6889 do anything else. It might even do exactly what you wanted it to do
6890 (and then it might start failing mysteriously next week or next
6891 year). The compiler will generate code based on the assumption that
6892 the condition being checked is true, which can result in disaster if
6893 that assumption is wrong.
6895 The @option{-gnatp} switch has no effect if a subsequent
6896 @option{-gnat-p} switch appears.
6899 @cindex @option{-gnat-p} (@command{gcc})
6900 @cindex Suppressing checks
6901 @cindex Checks, suppressing
6903 This switch cancels the effect of a previous @option{gnatp} switch.
6906 @cindex @option{-gnato??} (@command{gcc})
6907 @cindex Overflow checks
6908 @cindex Check, overflow
6909 In @code{CHECKED} and @code{MINIMIZED} modes (@option{-gnato1} and
6910 @option{-gnato2}), it enables overflow checking for integer operations.
6911 In @code{ELIMINATED} mode (@option{-gnato3}), it enables arbitrary
6912 precision arithmetic for integer operations. In all these modes, this
6913 causes @value{EDITION} to generate slower and larger executable programs
6914 by adding code to either check for overflow (resulting in raising
6915 @code{Constraint_Error} as required by standard Ada semantics) or avoid
6916 overflows. In mode @code{CHECKED}, overflow checks correspond to
6917 situations in which the true value of the result of an operation may be
6918 outside the base range of the result type. In mode @code{MINIMIZED},
6919 overflow checks correspond to situations in which the true value of the
6920 result of an operation may be outside the largest available machine
6921 integer type (@code{Long_Long_Integer}). The following example shows the
6924 @smallexample @c ada
6925 procedure Add_And_Subtract (X : in out Integer; Y, Z : in Integer) is
6928 end Add_And_Subtract;
6930 X1 : Integer := Integer'Last;
6931 X2 : Integer range 1 .. 5 := 5;
6933 Add_And_Subtract (X1, 1, 0); -- first addition and subtraction
6934 Add_And_Subtract (X1, 1, 1); -- second addition and subtraction
6935 Add_And_Subtract (X2, 1, 0); -- third addition and subtraction
6936 Add_And_Subtract (X2, 1, 1); -- fourth addition and subtraction
6940 Note that if explicit values are assigned at compile time, the compiler
6941 may be able to detect overflow at compile time, in which case no actual
6942 run-time checking code is required, and @code{Constraint_Error} will be
6943 raised unconditionally, with or without @option{-gnato}.
6945 The first addition results in a value that is outside the base range of
6946 @code{Integer}. In mode @code{CHECKED}, this raises
6947 @code{Constraint_Error} at run time. In mode @code{MINIMIZED}, the
6948 addition and subtraction are performed in type @code{Long_Long_Integer},
6949 which is 64 bits for most machines. The compiler detects that no
6950 overflow check is needed on these operations. The program still raises
6951 @code{Constraint_Error} at run time because the resulting value is too
6952 large to be assigned to @code{X}. The assignment results in a violation
6953 of the explicit range constraint; such range checks are performed by
6954 default, and are unaffected by @option{-gnato??}. In mode
6955 @code{ELIMINATED}, the compiler uses type @code{Long_Long_Integer} for
6956 intermediate computations, as this type is sufficient here to avoid all
6957 overflows. When it is not sufficient, the compiler uses instead a
6958 library for multiple-precision arithmetic, which may cause a significant
6959 run-time overhead. The program still raises @code{Constraint_Error} at
6960 run time when assigning to @code{X}.
6962 The second addition results in a value that is outside the base range of
6963 @code{Integer}. In mode @code{CHECKED}, this raises
6964 @code{Constraint_Error} at run time, like in the previous case. In mode
6965 @code{MINIMIZED}, the addition and subtraction are performed in type
6966 @code{Long_Long_Integer}, resulting in a final value that fits in an
6967 @code{Integer}. Thus, no @code{Constraint_Error} is raised. In mode
6968 @code{ELIMINATED}, the compiler generates the same code as in mode
6969 @code{MINIMIZED}, which avoids all overflows.
6971 The third addition and subtraction result in an intermediate value and a
6972 result well in the base range of @code{Integer}, so no
6973 @code{Constraint_Error} exception is raised at run time in any
6974 mode. However, the copy to @code{X2} when returning from the call to
6975 @code{Add_And_Subtract} fails the range check for the type of
6976 @code{X2}. Hence, a @code{Constraint_Error} exception is raised at run
6979 The fourth addition and subtraction result in an intermediate value and
6980 a result well in the base range of @code{Integer}, and in a final value
6981 that fits in the type of @code{X2}. Hence, no exception is raised at run
6984 Basically the rule is that in the default mode (@option{-gnato??} not
6985 used), the generated code assures that all integer variables stay within
6986 their declared ranges, or within the base range if there is no declared
6987 range. This prevents any serious problems like indexes out of range for
6990 What is not checked in default mode is an overflow that results in an
6991 in-range, but incorrect value. In the above example, the first
6992 assignment to @code{X1} gives a result that is within the range of the
6993 target variable, but the result is wrong in the sense that it is too
6994 large to be represented correctly. Typically the assignment to @code{X1}
6995 will result in wrap around to the largest negative number.
6997 @findex Machine_Overflows
6998 Note that the @option{-gnato??} switch does not affect the code generated
6999 for any floating-point operations; it applies only to integer
7001 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
7002 attribute set to @code{False} and the normal mode of operation is to
7003 generate IEEE NaN and infinite values on overflow or invalid operations
7004 (such as dividing 0.0 by 0.0).
7006 The reason that we distinguish overflow checking from other kinds of
7007 range constraint checking is that a failure of an overflow check, unlike
7008 for example the failure of a range check, can result in an incorrect
7009 value, but cannot cause random memory destruction (like an out of range
7010 subscript), or a wild jump (from an out of range case value). Overflow
7011 checking is also quite expensive in time and space, since in general it
7012 requires the use of double length arithmetic.
7014 Note again that the default is @option{-gnato00}, so overflow checking is
7015 not performed in default mode. This means that out of the box, with the
7016 default settings, @value{EDITION} does not do all the checks expected from the
7017 language description in the Ada Reference Manual. If you want all constraint
7018 checks to be performed, as described in this Manual, then you must
7019 explicitly use the @option{-gnato??} switch either on the @command{gnatmake} or
7020 @command{gcc} command.
7023 @cindex @option{-gnatE} (@command{gcc})
7024 @cindex Elaboration checks
7025 @cindex Check, elaboration
7026 Enables dynamic checks for access-before-elaboration
7027 on subprogram calls and generic instantiations.
7028 Note that @option{-gnatE} is not necessary for safety, because in the
7029 default mode, GNAT ensures statically that the checks would not fail.
7030 For full details of the effect and use of this switch,
7031 @xref{Compiling Using gcc}.
7034 @cindex @option{-fstack-check} (@command{gcc})
7035 @cindex Stack Overflow Checking
7036 @cindex Checks, stack overflow checking
7037 Activates stack overflow checking. For full details of the effect and use of
7038 this switch see @ref{Stack Overflow Checking}.
7043 The setting of these switches only controls the default setting of the
7044 checks. You may modify them using either @code{Suppress} (to remove
7045 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
7048 @node Using gcc for Syntax Checking
7049 @subsection Using @command{gcc} for Syntax Checking
7052 @cindex @option{-gnats} (@command{gcc})
7056 The @code{s} stands for ``syntax''.
7059 Run GNAT in syntax checking only mode. For
7060 example, the command
7063 $ gcc -c -gnats x.adb
7067 compiles file @file{x.adb} in syntax-check-only mode. You can check a
7068 series of files in a single command
7070 , and can use wild cards to specify such a group of files.
7071 Note that you must specify the @option{-c} (compile
7072 only) flag in addition to the @option{-gnats} flag.
7075 You may use other switches in conjunction with @option{-gnats}. In
7076 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
7077 format of any generated error messages.
7079 When the source file is empty or contains only empty lines and/or comments,
7080 the output is a warning:
7083 $ gcc -c -gnats -x ada toto.txt
7084 toto.txt:1:01: warning: empty file, contains no compilation units
7088 Otherwise, the output is simply the error messages, if any. No object file or
7089 ALI file is generated by a syntax-only compilation. Also, no units other
7090 than the one specified are accessed. For example, if a unit @code{X}
7091 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
7092 check only mode does not access the source file containing unit
7095 @cindex Multiple units, syntax checking
7096 Normally, GNAT allows only a single unit in a source file. However, this
7097 restriction does not apply in syntax-check-only mode, and it is possible
7098 to check a file containing multiple compilation units concatenated
7099 together. This is primarily used by the @code{gnatchop} utility
7100 (@pxref{Renaming Files Using gnatchop}).
7103 @node Using gcc for Semantic Checking
7104 @subsection Using @command{gcc} for Semantic Checking
7107 @cindex @option{-gnatc} (@command{gcc})
7111 The @code{c} stands for ``check''.
7113 Causes the compiler to operate in semantic check mode,
7114 with full checking for all illegalities specified in the
7115 Ada Reference Manual, but without generation of any object code
7116 (no object file is generated).
7118 Because dependent files must be accessed, you must follow the GNAT
7119 semantic restrictions on file structuring to operate in this mode:
7123 The needed source files must be accessible
7124 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7127 Each file must contain only one compilation unit.
7130 The file name and unit name must match (@pxref{File Naming Rules}).
7133 The output consists of error messages as appropriate. No object file is
7134 generated. An @file{ALI} file is generated for use in the context of
7135 cross-reference tools, but this file is marked as not being suitable
7136 for binding (since no object file is generated).
7137 The checking corresponds exactly to the notion of
7138 legality in the Ada Reference Manual.
7140 Any unit can be compiled in semantics-checking-only mode, including
7141 units that would not normally be compiled (subunits,
7142 and specifications where a separate body is present).
7145 @node Compiling Different Versions of Ada
7146 @subsection Compiling Different Versions of Ada
7149 The switches described in this section allow you to explicitly specify
7150 the version of the Ada language that your programs are written in.
7151 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
7152 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
7153 indicate Ada 83 compatibility mode.
7156 @cindex Compatibility with Ada 83
7158 @item -gnat83 (Ada 83 Compatibility Mode)
7159 @cindex @option{-gnat83} (@command{gcc})
7160 @cindex ACVC, Ada 83 tests
7164 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7165 specifies that the program is to be compiled in Ada 83 mode. With
7166 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7167 semantics where this can be done easily.
7168 It is not possible to guarantee this switch does a perfect
7169 job; some subtle tests, such as are
7170 found in earlier ACVC tests (and that have been removed from the ACATS suite
7171 for Ada 95), might not compile correctly.
7172 Nevertheless, this switch may be useful in some circumstances, for example
7173 where, due to contractual reasons, existing code needs to be maintained
7174 using only Ada 83 features.
7176 With few exceptions (most notably the need to use @code{<>} on
7177 @cindex Generic formal parameters
7178 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7179 reserved words, and the use of packages
7180 with optional bodies), it is not necessary to specify the
7181 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7182 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7183 a correct Ada 83 program is usually also a correct program
7184 in these later versions of the language standard.
7185 For further information, please refer to @ref{Compatibility and Porting Guide}.
7187 @item -gnat95 (Ada 95 mode)
7188 @cindex @option{-gnat95} (@command{gcc})
7192 This switch directs the compiler to implement the Ada 95 version of the
7194 Since Ada 95 is almost completely upwards
7195 compatible with Ada 83, Ada 83 programs may generally be compiled using
7196 this switch (see the description of the @option{-gnat83} switch for further
7197 information about Ada 83 mode).
7198 If an Ada 2005 program is compiled in Ada 95 mode,
7199 uses of the new Ada 2005 features will cause error
7200 messages or warnings.
7202 This switch also can be used to cancel the effect of a previous
7203 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7204 switch earlier in the command line.
7206 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7207 @cindex @option{-gnat05} (@command{gcc})
7208 @cindex @option{-gnat2005} (@command{gcc})
7209 @cindex Ada 2005 mode
7212 This switch directs the compiler to implement the Ada 2005 version of the
7213 language, as documented in the official Ada standards document.
7214 Since Ada 2005 is almost completely upwards
7215 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7216 may generally be compiled using this switch (see the description of the
7217 @option{-gnat83} and @option{-gnat95} switches for further
7221 Note that even though Ada 2005 is the current official version of the
7222 language, GNAT still compiles in Ada 95 mode by default, so if you are
7223 using Ada 2005 features in your program, you must use this switch (or
7224 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7227 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7228 @cindex @option{-gnat12} (@command{gcc})
7229 @cindex @option{-gnat2012} (@command{gcc})
7230 @cindex Ada 2012 mode
7233 This switch directs the compiler to implement the Ada 2012 version of the
7235 Since Ada 2012 is almost completely upwards
7236 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7237 Ada 83 and Ada 95 programs
7238 may generally be compiled using this switch (see the description of the
7239 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7240 for further information).
7242 For information about the approved ``Ada Issues'' that have been incorporated
7243 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7244 Included with GNAT releases is a file @file{features-ada12} that describes
7245 the set of implemented Ada 2012 features.
7247 @item -gnatX (Enable GNAT Extensions)
7248 @cindex @option{-gnatX} (@command{gcc})
7249 @cindex Ada language extensions
7250 @cindex GNAT extensions
7253 This switch directs the compiler to implement the latest version of the
7254 language (currently Ada 2012) and also to enable certain GNAT implementation
7255 extensions that are not part of any Ada standard. For a full list of these
7256 extensions, see the GNAT reference manual.
7260 @node Character Set Control
7261 @subsection Character Set Control
7263 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7264 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7267 Normally GNAT recognizes the Latin-1 character set in source program
7268 identifiers, as described in the Ada Reference Manual.
7270 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7271 single character ^^or word^ indicating the character set, as follows:
7275 ISO 8859-1 (Latin-1) identifiers
7278 ISO 8859-2 (Latin-2) letters allowed in identifiers
7281 ISO 8859-3 (Latin-3) letters allowed in identifiers
7284 ISO 8859-4 (Latin-4) letters allowed in identifiers
7287 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7290 ISO 8859-15 (Latin-9) letters allowed in identifiers
7293 IBM PC letters (code page 437) allowed in identifiers
7296 IBM PC letters (code page 850) allowed in identifiers
7298 @item ^f^FULL_UPPER^
7299 Full upper-half codes allowed in identifiers
7302 No upper-half codes allowed in identifiers
7305 Wide-character codes (that is, codes greater than 255)
7306 allowed in identifiers
7309 @xref{Foreign Language Representation}, for full details on the
7310 implementation of these character sets.
7312 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7313 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7314 Specify the method of encoding for wide characters.
7315 @var{e} is one of the following:
7320 Hex encoding (brackets coding also recognized)
7323 Upper half encoding (brackets encoding also recognized)
7326 Shift/JIS encoding (brackets encoding also recognized)
7329 EUC encoding (brackets encoding also recognized)
7332 UTF-8 encoding (brackets encoding also recognized)
7335 Brackets encoding only (default value)
7337 For full details on these encoding
7338 methods see @ref{Wide Character Encodings}.
7339 Note that brackets coding is always accepted, even if one of the other
7340 options is specified, so for example @option{-gnatW8} specifies that both
7341 brackets and UTF-8 encodings will be recognized. The units that are
7342 with'ed directly or indirectly will be scanned using the specified
7343 representation scheme, and so if one of the non-brackets scheme is
7344 used, it must be used consistently throughout the program. However,
7345 since brackets encoding is always recognized, it may be conveniently
7346 used in standard libraries, allowing these libraries to be used with
7347 any of the available coding schemes.
7349 Note that brackets encoding only applies to program text. Within comments,
7350 brackets are considered to be normal graphic characters, and bracket sequences
7351 are never recognized as wide characters.
7353 If no @option{-gnatW?} parameter is present, then the default
7354 representation is normally Brackets encoding only. However, if the
7355 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7356 byte order mark or BOM for UTF-8), then these three characters are
7357 skipped and the default representation for the file is set to UTF-8.
7359 Note that the wide character representation that is specified (explicitly
7360 or by default) for the main program also acts as the default encoding used
7361 for Wide_Text_IO files if not specifically overridden by a WCEM form
7366 When no @option{-gnatW?} is specified, then characters (other than wide
7367 characters represented using brackets notation) are treated as 8-bit
7368 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7369 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7370 characters in the range 16#00#..16#1F# are not accepted in program text
7371 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7372 in program text, but allowed and ignored in comments. Note in particular
7373 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7374 as an end of line in this default mode. If your source program contains
7375 instances of the NEL character used as a line terminator,
7376 you must use UTF-8 encoding for the whole
7377 source program. In default mode, all lines must be ended by a standard
7378 end of line sequence (CR, CR/LF, or LF).
7380 Note that the convention of simply accepting all upper half characters in
7381 comments means that programs that use standard ASCII for program text, but
7382 UTF-8 encoding for comments are accepted in default mode, providing that the
7383 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7384 This is a common mode for many programs with foreign language comments.
7386 @node File Naming Control
7387 @subsection File Naming Control
7390 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7391 @cindex @option{-gnatk} (@command{gcc})
7392 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7393 1-999, indicates the maximum allowable length of a file name (not
7394 including the @file{.ads} or @file{.adb} extension). The default is not
7395 to enable file name krunching.
7397 For the source file naming rules, @xref{File Naming Rules}.
7400 @node Subprogram Inlining Control
7401 @subsection Subprogram Inlining Control
7406 @cindex @option{-gnatn} (@command{gcc})
7408 The @code{n} here is intended to suggest the first syllable of the
7411 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7412 inlining to actually occur, optimization must be enabled and, in order
7413 to enable inlining of subprograms specified by pragma @code{Inline},
7414 you must also specify this switch.
7415 In the absence of this switch, GNAT does not attempt
7416 inlining and does not need to access the bodies of
7417 subprograms for which @code{pragma Inline} is specified if they are not
7418 in the current unit.
7420 You can optionally specify the inlining level: 1 for moderate inlining across
7421 modules, which is a good compromise between compilation times and performances
7422 at run time, or 2 for full inlining across modules, which may bring about
7423 longer compilation times. If no inlining level is specified, the compiler will
7424 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7425 @option{-Os} and 2 for @option{-O3}.
7427 If you specify this switch the compiler will access these bodies,
7428 creating an extra source dependency for the resulting object file, and
7429 where possible, the call will be inlined.
7430 For further details on when inlining is possible
7431 see @ref{Inlining of Subprograms}.
7434 @cindex @option{-gnatN} (@command{gcc})
7435 This switch activates front-end inlining which also
7436 generates additional dependencies.
7438 When using a gcc-based back end (in practice this means using any version
7439 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7440 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7441 Historically front end inlining was more extensive than the gcc back end
7442 inlining, but that is no longer the case.
7445 @node Auxiliary Output Control
7446 @subsection Auxiliary Output Control
7450 @cindex @option{-gnatt} (@command{gcc})
7451 @cindex Writing internal trees
7452 @cindex Internal trees, writing to file
7453 Causes GNAT to write the internal tree for a unit to a file (with the
7454 extension @file{.adt}.
7455 This not normally required, but is used by separate analysis tools.
7457 these tools do the necessary compilations automatically, so you should
7458 not have to specify this switch in normal operation.
7459 Note that the combination of switches @option{-gnatct}
7460 generates a tree in the form required by ASIS applications.
7463 @cindex @option{-gnatu} (@command{gcc})
7464 Print a list of units required by this compilation on @file{stdout}.
7465 The listing includes all units on which the unit being compiled depends
7466 either directly or indirectly.
7469 @item -pass-exit-codes
7470 @cindex @option{-pass-exit-codes} (@command{gcc})
7471 If this switch is not used, the exit code returned by @command{gcc} when
7472 compiling multiple files indicates whether all source files have
7473 been successfully used to generate object files or not.
7475 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7476 exit status and allows an integrated development environment to better
7477 react to a compilation failure. Those exit status are:
7481 There was an error in at least one source file.
7483 At least one source file did not generate an object file.
7485 The compiler died unexpectedly (internal error for example).
7487 An object file has been generated for every source file.
7492 @node Debugging Control
7493 @subsection Debugging Control
7497 @cindex Debugging options
7500 @cindex @option{-gnatd} (@command{gcc})
7501 Activate internal debugging switches. @var{x} is a letter or digit, or
7502 string of letters or digits, which specifies the type of debugging
7503 outputs desired. Normally these are used only for internal development
7504 or system debugging purposes. You can find full documentation for these
7505 switches in the body of the @code{Debug} unit in the compiler source
7506 file @file{debug.adb}.
7510 @cindex @option{-gnatG} (@command{gcc})
7511 This switch causes the compiler to generate auxiliary output containing
7512 a pseudo-source listing of the generated expanded code. Like most Ada
7513 compilers, GNAT works by first transforming the high level Ada code into
7514 lower level constructs. For example, tasking operations are transformed
7515 into calls to the tasking run-time routines. A unique capability of GNAT
7516 is to list this expanded code in a form very close to normal Ada source.
7517 This is very useful in understanding the implications of various Ada
7518 usage on the efficiency of the generated code. There are many cases in
7519 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7520 generate a lot of run-time code. By using @option{-gnatG} you can identify
7521 these cases, and consider whether it may be desirable to modify the coding
7522 approach to improve efficiency.
7524 The optional parameter @code{nn} if present after -gnatG specifies an
7525 alternative maximum line length that overrides the normal default of 72.
7526 This value is in the range 40-999999, values less than 40 being silently
7527 reset to 40. The equal sign is optional.
7529 The format of the output is very similar to standard Ada source, and is
7530 easily understood by an Ada programmer. The following special syntactic
7531 additions correspond to low level features used in the generated code that
7532 do not have any exact analogies in pure Ada source form. The following
7533 is a partial list of these special constructions. See the spec
7534 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7536 If the switch @option{-gnatL} is used in conjunction with
7537 @cindex @option{-gnatL} (@command{gcc})
7538 @option{-gnatG}, then the original source lines are interspersed
7539 in the expanded source (as comment lines with the original line number).
7542 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7543 Shows the storage pool being used for an allocator.
7545 @item at end @var{procedure-name};
7546 Shows the finalization (cleanup) procedure for a scope.
7548 @item (if @var{expr} then @var{expr} else @var{expr})
7549 Conditional expression equivalent to the @code{x?y:z} construction in C.
7551 @item @var{target}^^^(@var{source})
7552 A conversion with floating-point truncation instead of rounding.
7554 @item @var{target}?(@var{source})
7555 A conversion that bypasses normal Ada semantic checking. In particular
7556 enumeration types and fixed-point types are treated simply as integers.
7558 @item @var{target}?^^^(@var{source})
7559 Combines the above two cases.
7561 @item @var{x} #/ @var{y}
7562 @itemx @var{x} #mod @var{y}
7563 @itemx @var{x} #* @var{y}
7564 @itemx @var{x} #rem @var{y}
7565 A division or multiplication of fixed-point values which are treated as
7566 integers without any kind of scaling.
7568 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7569 Shows the storage pool associated with a @code{free} statement.
7571 @item [subtype or type declaration]
7572 Used to list an equivalent declaration for an internally generated
7573 type that is referenced elsewhere in the listing.
7575 @c @item freeze @var{type-name} @ovar{actions}
7576 @c Expanding @ovar macro inline (explanation in macro def comments)
7577 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7578 Shows the point at which @var{type-name} is frozen, with possible
7579 associated actions to be performed at the freeze point.
7581 @item reference @var{itype}
7582 Reference (and hence definition) to internal type @var{itype}.
7584 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7585 Intrinsic function call.
7587 @item @var{label-name} : label
7588 Declaration of label @var{labelname}.
7590 @item #$ @var{subprogram-name}
7591 An implicit call to a run-time support routine
7592 (to meet the requirement of H.3.1(9) in a
7595 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7596 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7597 @var{expr}, but handled more efficiently).
7599 @item [constraint_error]
7600 Raise the @code{Constraint_Error} exception.
7602 @item @var{expression}'reference
7603 A pointer to the result of evaluating @var{expression}.
7605 @item @var{target-type}!(@var{source-expression})
7606 An unchecked conversion of @var{source-expression} to @var{target-type}.
7608 @item [@var{numerator}/@var{denominator}]
7609 Used to represent internal real literals (that) have no exact
7610 representation in base 2-16 (for example, the result of compile time
7611 evaluation of the expression 1.0/27.0).
7615 @cindex @option{-gnatD} (@command{gcc})
7616 When used in conjunction with @option{-gnatG}, this switch causes
7617 the expanded source, as described above for
7618 @option{-gnatG} to be written to files with names
7619 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7620 instead of to the standard output file. For
7621 example, if the source file name is @file{hello.adb}, then a file
7622 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7623 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7624 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7625 you to do source level debugging using the generated code which is
7626 sometimes useful for complex code, for example to find out exactly
7627 which part of a complex construction raised an exception. This switch
7628 also suppress generation of cross-reference information (see
7629 @option{-gnatx}) since otherwise the cross-reference information
7630 would refer to the @file{^.dg^.DG^} file, which would cause
7631 confusion since this is not the original source file.
7633 Note that @option{-gnatD} actually implies @option{-gnatG}
7634 automatically, so it is not necessary to give both options.
7635 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7637 If the switch @option{-gnatL} is used in conjunction with
7638 @cindex @option{-gnatL} (@command{gcc})
7639 @option{-gnatDG}, then the original source lines are interspersed
7640 in the expanded source (as comment lines with the original line number).
7642 The optional parameter @code{nn} if present after -gnatD specifies an
7643 alternative maximum line length that overrides the normal default of 72.
7644 This value is in the range 40-999999, values less than 40 being silently
7645 reset to 40. The equal sign is optional.
7648 @cindex @option{-gnatr} (@command{gcc})
7649 @cindex pragma Restrictions
7650 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7651 so that violation of restrictions causes warnings rather than illegalities.
7652 This is useful during the development process when new restrictions are added
7653 or investigated. The switch also causes pragma Profile to be treated as
7654 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7655 restriction warnings rather than restrictions.
7658 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7659 @cindex @option{-gnatR} (@command{gcc})
7660 This switch controls output from the compiler of a listing showing
7661 representation information for declared types and objects. For
7662 @option{-gnatR0}, no information is output (equivalent to omitting
7663 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7664 so @option{-gnatR} with no parameter has the same effect), size and alignment
7665 information is listed for declared array and record types. For
7666 @option{-gnatR2}, size and alignment information is listed for all
7667 declared types and objects. Finally @option{-gnatR3} includes symbolic
7668 expressions for values that are computed at run time for
7669 variant records. These symbolic expressions have a mostly obvious
7670 format with #n being used to represent the value of the n'th
7671 discriminant. See source files @file{repinfo.ads/adb} in the
7672 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7673 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7674 the output is to a file with the name @file{^file.rep^file_REP^} where
7675 file is the name of the corresponding source file.
7678 @item /REPRESENTATION_INFO
7679 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7680 This qualifier controls output from the compiler of a listing showing
7681 representation information for declared types and objects. For
7682 @option{/REPRESENTATION_INFO=NONE}, no information is output
7683 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7684 @option{/REPRESENTATION_INFO} without option is equivalent to
7685 @option{/REPRESENTATION_INFO=ARRAYS}.
7686 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7687 information is listed for declared array and record types. For
7688 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7689 is listed for all expression information for values that are computed
7690 at run time for variant records. These symbolic expressions have a mostly
7691 obvious format with #n being used to represent the value of the n'th
7692 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7693 @code{GNAT} sources for full details on the format of
7694 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7695 If _FILE is added at the end of an option
7696 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7697 then the output is to a file with the name @file{file_REP} where
7698 file is the name of the corresponding source file.
7700 Note that it is possible for record components to have zero size. In
7701 this case, the component clause uses an obvious extension of permitted
7702 Ada syntax, for example @code{at 0 range 0 .. -1}.
7704 Representation information requires that code be generated (since it is the
7705 code generator that lays out complex data structures). If an attempt is made
7706 to output representation information when no code is generated, for example
7707 when a subunit is compiled on its own, then no information can be generated
7708 and the compiler outputs a message to this effect.
7711 @cindex @option{-gnatS} (@command{gcc})
7712 The use of the switch @option{-gnatS} for an
7713 Ada compilation will cause the compiler to output a
7714 representation of package Standard in a form very
7715 close to standard Ada. It is not quite possible to
7716 do this entirely in standard Ada (since new
7717 numeric base types cannot be created in standard
7718 Ada), but the output is easily
7719 readable to any Ada programmer, and is useful to
7720 determine the characteristics of target dependent
7721 types in package Standard.
7724 @cindex @option{-gnatx} (@command{gcc})
7725 Normally the compiler generates full cross-referencing information in
7726 the @file{ALI} file. This information is used by a number of tools,
7727 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7728 suppresses this information. This saves some space and may slightly
7729 speed up compilation, but means that these tools cannot be used.
7732 @node Exception Handling Control
7733 @subsection Exception Handling Control
7736 GNAT uses two methods for handling exceptions at run-time. The
7737 @code{setjmp/longjmp} method saves the context when entering
7738 a frame with an exception handler. Then when an exception is
7739 raised, the context can be restored immediately, without the
7740 need for tracing stack frames. This method provides very fast
7741 exception propagation, but introduces significant overhead for
7742 the use of exception handlers, even if no exception is raised.
7744 The other approach is called ``zero cost'' exception handling.
7745 With this method, the compiler builds static tables to describe
7746 the exception ranges. No dynamic code is required when entering
7747 a frame containing an exception handler. When an exception is
7748 raised, the tables are used to control a back trace of the
7749 subprogram invocation stack to locate the required exception
7750 handler. This method has considerably poorer performance for
7751 the propagation of exceptions, but there is no overhead for
7752 exception handlers if no exception is raised. Note that in this
7753 mode and in the context of mixed Ada and C/C++ programming,
7754 to propagate an exception through a C/C++ code, the C/C++ code
7755 must be compiled with the @option{-funwind-tables} GCC's
7758 The following switches may be used to control which of the
7759 two exception handling methods is used.
7765 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7766 This switch causes the setjmp/longjmp run-time (when available) to be used
7767 for exception handling. If the default
7768 mechanism for the target is zero cost exceptions, then
7769 this switch can be used to modify this default, and must be
7770 used for all units in the partition.
7771 This option is rarely used. One case in which it may be
7772 advantageous is if you have an application where exception
7773 raising is common and the overall performance of the
7774 application is improved by favoring exception propagation.
7777 @cindex @option{--RTS=zcx} (@command{gnatmake})
7778 @cindex Zero Cost Exceptions
7779 This switch causes the zero cost approach to be used
7780 for exception handling. If this is the default mechanism for the
7781 target (see below), then this switch is unneeded. If the default
7782 mechanism for the target is setjmp/longjmp exceptions, then
7783 this switch can be used to modify this default, and must be
7784 used for all units in the partition.
7785 This option can only be used if the zero cost approach
7786 is available for the target in use, otherwise it will generate an error.
7790 The same option @option{--RTS} must be used both for @command{gcc}
7791 and @command{gnatbind}. Passing this option to @command{gnatmake}
7792 (@pxref{Switches for gnatmake}) will ensure the required consistency
7793 through the compilation and binding steps.
7795 @node Units to Sources Mapping Files
7796 @subsection Units to Sources Mapping Files
7800 @item -gnatem=@var{path}
7801 @cindex @option{-gnatem} (@command{gcc})
7802 A mapping file is a way to communicate to the compiler two mappings:
7803 from unit names to file names (without any directory information) and from
7804 file names to path names (with full directory information). These mappings
7805 are used by the compiler to short-circuit the path search.
7807 The use of mapping files is not required for correct operation of the
7808 compiler, but mapping files can improve efficiency, particularly when
7809 sources are read over a slow network connection. In normal operation,
7810 you need not be concerned with the format or use of mapping files,
7811 and the @option{-gnatem} switch is not a switch that you would use
7812 explicitly. It is intended primarily for use by automatic tools such as
7813 @command{gnatmake} running under the project file facility. The
7814 description here of the format of mapping files is provided
7815 for completeness and for possible use by other tools.
7817 A mapping file is a sequence of sets of three lines. In each set, the
7818 first line is the unit name, in lower case, with @code{%s} appended
7819 for specs and @code{%b} appended for bodies; the second line is the
7820 file name; and the third line is the path name.
7826 /gnat/project1/sources/main.2.ada
7829 When the switch @option{-gnatem} is specified, the compiler will
7830 create in memory the two mappings from the specified file. If there is
7831 any problem (nonexistent file, truncated file or duplicate entries),
7832 no mapping will be created.
7834 Several @option{-gnatem} switches may be specified; however, only the
7835 last one on the command line will be taken into account.
7837 When using a project file, @command{gnatmake} creates a temporary
7838 mapping file and communicates it to the compiler using this switch.
7842 @node Integrated Preprocessing
7843 @subsection Integrated Preprocessing
7846 GNAT sources may be preprocessed immediately before compilation.
7847 In this case, the actual
7848 text of the source is not the text of the source file, but is derived from it
7849 through a process called preprocessing. Integrated preprocessing is specified
7850 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7851 indicates, through a text file, the preprocessing data to be used.
7852 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7855 Note that when integrated preprocessing is used, the output from the
7856 preprocessor is not written to any external file. Instead it is passed
7857 internally to the compiler. If you need to preserve the result of
7858 preprocessing in a file, then you should use @command{gnatprep}
7859 to perform the desired preprocessing in stand-alone mode.
7862 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7863 used when Integrated Preprocessing is used. The reason is that preprocessing
7864 with another Preprocessing Data file without changing the sources will
7865 not trigger recompilation without this switch.
7868 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7869 always trigger recompilation for sources that are preprocessed,
7870 because @command{gnatmake} cannot compute the checksum of the source after
7874 The actual preprocessing function is described in details in section
7875 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7876 preprocessing is triggered and parameterized.
7880 @item -gnatep=@var{file}
7881 @cindex @option{-gnatep} (@command{gcc})
7882 This switch indicates to the compiler the file name (without directory
7883 information) of the preprocessor data file to use. The preprocessor data file
7884 should be found in the source directories. Note that when the compiler is
7885 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7886 file, if the object directory is not also a source directory, the builder needs
7887 to be called with @option{-x}.
7890 A preprocessing data file is a text file with significant lines indicating
7891 how should be preprocessed either a specific source or all sources not
7892 mentioned in other lines. A significant line is a nonempty, non-comment line.
7893 Comments are similar to Ada comments.
7896 Each significant line starts with either a literal string or the character '*'.
7897 A literal string is the file name (without directory information) of the source
7898 to preprocess. A character '*' indicates the preprocessing for all the sources
7899 that are not specified explicitly on other lines (order of the lines is not
7900 significant). It is an error to have two lines with the same file name or two
7901 lines starting with the character '*'.
7904 After the file name or the character '*', another optional literal string
7905 indicating the file name of the definition file to be used for preprocessing
7906 (@pxref{Form of Definitions File}). The definition files are found by the
7907 compiler in one of the source directories. In some cases, when compiling
7908 a source in a directory other than the current directory, if the definition
7909 file is in the current directory, it may be necessary to add the current
7910 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7911 the compiler would not find the definition file.
7914 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7915 be found. Those ^switches^switches^ are:
7920 Causes both preprocessor lines and the lines deleted by
7921 preprocessing to be replaced by blank lines, preserving the line number.
7922 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7923 it cancels the effect of @option{-c}.
7926 Causes both preprocessor lines and the lines deleted
7927 by preprocessing to be retained as comments marked
7928 with the special string ``@code{--! }''.
7930 @item -Dsymbol=value
7931 Define or redefine a symbol, associated with value. A symbol is an Ada
7932 identifier, or an Ada reserved word, with the exception of @code{if},
7933 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7934 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7935 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7936 same name defined in a definition file.
7939 Causes a sorted list of symbol names and values to be
7940 listed on the standard output file.
7943 Causes undefined symbols to be treated as having the value @code{FALSE}
7945 of a preprocessor test. In the absence of this option, an undefined symbol in
7946 a @code{#if} or @code{#elsif} test will be treated as an error.
7951 Examples of valid lines in a preprocessor data file:
7954 "toto.adb" "prep.def" -u
7955 -- preprocess "toto.adb", using definition file "prep.def",
7956 -- undefined symbol are False.
7959 -- preprocess all other sources without a definition file;
7960 -- suppressed lined are commented; symbol VERSION has the value V101.
7962 "titi.adb" "prep2.def" -s
7963 -- preprocess "titi.adb", using definition file "prep2.def";
7964 -- list all symbols with their values.
7967 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7968 @cindex @option{-gnateD} (@command{gcc})
7969 Define or redefine a preprocessing symbol, associated with value. If no value
7970 is given on the command line, then the value of the symbol is @code{True}.
7971 A symbol is an identifier, following normal Ada (case-insensitive)
7972 rules for its syntax, and value is any sequence (including an empty sequence)
7973 of characters from the set (letters, digits, period, underline).
7974 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7975 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7978 A symbol declared with this ^switch^switch^ on the command line replaces a
7979 symbol with the same name either in a definition file or specified with a
7980 ^switch^switch^ -D in the preprocessor data file.
7983 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7986 When integrated preprocessing is performed and the preprocessor modifies
7987 the source text, write the result of this preprocessing into a file
7988 <source>^.prep^_prep^.
7992 @node Code Generation Control
7993 @subsection Code Generation Control
7997 The GCC technology provides a wide range of target dependent
7998 @option{-m} switches for controlling
7999 details of code generation with respect to different versions of
8000 architectures. This includes variations in instruction sets (e.g.@:
8001 different members of the power pc family), and different requirements
8002 for optimal arrangement of instructions (e.g.@: different members of
8003 the x86 family). The list of available @option{-m} switches may be
8004 found in the GCC documentation.
8006 Use of these @option{-m} switches may in some cases result in improved
8009 The @value{EDITION} technology is tested and qualified without any
8010 @option{-m} switches,
8011 so generally the most reliable approach is to avoid the use of these
8012 switches. However, we generally expect most of these switches to work
8013 successfully with @value{EDITION}, and many customers have reported successful
8014 use of these options.
8016 Our general advice is to avoid the use of @option{-m} switches unless
8017 special needs lead to requirements in this area. In particular,
8018 there is no point in using @option{-m} switches to improve performance
8019 unless you actually see a performance improvement.
8023 @subsection Return Codes
8024 @cindex Return Codes
8025 @cindex @option{/RETURN_CODES=VMS}
8028 On VMS, GNAT compiled programs return POSIX-style codes by default,
8029 e.g.@: @option{/RETURN_CODES=POSIX}.
8031 To enable VMS style return codes, use GNAT BIND and LINK with the option
8032 @option{/RETURN_CODES=VMS}. For example:
8035 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
8036 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
8040 Programs built with /RETURN_CODES=VMS are suitable to be called in
8041 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
8042 are suitable for spawning with appropriate GNAT RTL routines.
8046 @node Search Paths and the Run-Time Library (RTL)
8047 @section Search Paths and the Run-Time Library (RTL)
8050 With the GNAT source-based library system, the compiler must be able to
8051 find source files for units that are needed by the unit being compiled.
8052 Search paths are used to guide this process.
8054 The compiler compiles one source file whose name must be given
8055 explicitly on the command line. In other words, no searching is done
8056 for this file. To find all other source files that are needed (the most
8057 common being the specs of units), the compiler examines the following
8058 directories, in the following order:
8062 The directory containing the source file of the main unit being compiled
8063 (the file name on the command line).
8066 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
8067 @command{gcc} command line, in the order given.
8070 @findex ADA_PRJ_INCLUDE_FILE
8071 Each of the directories listed in the text file whose name is given
8072 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
8075 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8076 driver when project files are used. It should not normally be set
8080 @findex ADA_INCLUDE_PATH
8081 Each of the directories listed in the value of the
8082 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
8084 Construct this value
8085 exactly as the @env{PATH} environment variable: a list of directory
8086 names separated by colons (semicolons when working with the NT version).
8089 Normally, define this value as a logical name containing a comma separated
8090 list of directory names.
8092 This variable can also be defined by means of an environment string
8093 (an argument to the HP C exec* set of functions).
8097 DEFINE ANOTHER_PATH FOO:[BAG]
8098 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8101 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8102 first, followed by the standard Ada
8103 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
8104 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8105 (Text_IO, Sequential_IO, etc)
8106 instead of the standard Ada packages. Thus, in order to get the standard Ada
8107 packages by default, ADA_INCLUDE_PATH must be redefined.
8111 The content of the @file{ada_source_path} file which is part of the GNAT
8112 installation tree and is used to store standard libraries such as the
8113 GNAT Run Time Library (RTL) source files.
8115 @ref{Installing a library}
8120 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
8121 inhibits the use of the directory
8122 containing the source file named in the command line. You can still
8123 have this directory on your search path, but in this case it must be
8124 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8126 Specifying the switch @option{-nostdinc}
8127 inhibits the search of the default location for the GNAT Run Time
8128 Library (RTL) source files.
8130 The compiler outputs its object files and ALI files in the current
8133 Caution: The object file can be redirected with the @option{-o} switch;
8134 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8135 so the @file{ALI} file will not go to the right place. Therefore, you should
8136 avoid using the @option{-o} switch.
8140 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8141 children make up the GNAT RTL, together with the simple @code{System.IO}
8142 package used in the @code{"Hello World"} example. The sources for these units
8143 are needed by the compiler and are kept together in one directory. Not
8144 all of the bodies are needed, but all of the sources are kept together
8145 anyway. In a normal installation, you need not specify these directory
8146 names when compiling or binding. Either the environment variables or
8147 the built-in defaults cause these files to be found.
8149 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8150 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8151 consisting of child units of @code{GNAT}. This is a collection of generally
8152 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8153 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8155 Besides simplifying access to the RTL, a major use of search paths is
8156 in compiling sources from multiple directories. This can make
8157 development environments much more flexible.
8159 @node Order of Compilation Issues
8160 @section Order of Compilation Issues
8163 If, in our earlier example, there was a spec for the @code{hello}
8164 procedure, it would be contained in the file @file{hello.ads}; yet this
8165 file would not have to be explicitly compiled. This is the result of the
8166 model we chose to implement library management. Some of the consequences
8167 of this model are as follows:
8171 There is no point in compiling specs (except for package
8172 specs with no bodies) because these are compiled as needed by clients. If
8173 you attempt a useless compilation, you will receive an error message.
8174 It is also useless to compile subunits because they are compiled as needed
8178 There are no order of compilation requirements: performing a
8179 compilation never obsoletes anything. The only way you can obsolete
8180 something and require recompilations is to modify one of the
8181 source files on which it depends.
8184 There is no library as such, apart from the ALI files
8185 (@pxref{The Ada Library Information Files}, for information on the format
8186 of these files). For now we find it convenient to create separate ALI files,
8187 but eventually the information therein may be incorporated into the object
8191 When you compile a unit, the source files for the specs of all units
8192 that it @code{with}'s, all its subunits, and the bodies of any generics it
8193 instantiates must be available (reachable by the search-paths mechanism
8194 described above), or you will receive a fatal error message.
8201 The following are some typical Ada compilation command line examples:
8204 @item $ gcc -c xyz.adb
8205 Compile body in file @file{xyz.adb} with all default options.
8208 @item $ gcc -c -O2 -gnata xyz-def.adb
8211 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8214 Compile the child unit package in file @file{xyz-def.adb} with extensive
8215 optimizations, and pragma @code{Assert}/@code{Debug} statements
8218 @item $ gcc -c -gnatc abc-def.adb
8219 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8223 @node Binding Using gnatbind
8224 @chapter Binding Using @code{gnatbind}
8228 * Running gnatbind::
8229 * Switches for gnatbind::
8230 * Command-Line Access::
8231 * Search Paths for gnatbind::
8232 * Examples of gnatbind Usage::
8236 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8237 to bind compiled GNAT objects.
8239 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8240 driver (see @ref{The GNAT Driver and Project Files}).
8242 The @code{gnatbind} program performs four separate functions:
8246 Checks that a program is consistent, in accordance with the rules in
8247 Chapter 10 of the Ada Reference Manual. In particular, error
8248 messages are generated if a program uses inconsistent versions of a
8252 Checks that an acceptable order of elaboration exists for the program
8253 and issues an error message if it cannot find an order of elaboration
8254 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8257 Generates a main program incorporating the given elaboration order.
8258 This program is a small Ada package (body and spec) that
8259 must be subsequently compiled
8260 using the GNAT compiler. The necessary compilation step is usually
8261 performed automatically by @command{gnatlink}. The two most important
8262 functions of this program
8263 are to call the elaboration routines of units in an appropriate order
8264 and to call the main program.
8267 Determines the set of object files required by the given main program.
8268 This information is output in the forms of comments in the generated program,
8269 to be read by the @command{gnatlink} utility used to link the Ada application.
8272 @node Running gnatbind
8273 @section Running @code{gnatbind}
8276 The form of the @code{gnatbind} command is
8279 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8280 @c Expanding @ovar macro inline (explanation in macro def comments)
8281 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8285 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8286 unit body. @code{gnatbind} constructs an Ada
8287 package in two files whose names are
8288 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8289 For example, if given the
8290 parameter @file{hello.ali}, for a main program contained in file
8291 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8292 and @file{b~hello.adb}.
8294 When doing consistency checking, the binder takes into consideration
8295 any source files it can locate. For example, if the binder determines
8296 that the given main program requires the package @code{Pack}, whose
8298 file is @file{pack.ali} and whose corresponding source spec file is
8299 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8300 (using the same search path conventions as previously described for the
8301 @command{gcc} command). If it can locate this source file, it checks that
8303 or source checksums of the source and its references to in @file{ALI} files
8304 match. In other words, any @file{ALI} files that mentions this spec must have
8305 resulted from compiling this version of the source file (or in the case
8306 where the source checksums match, a version close enough that the
8307 difference does not matter).
8309 @cindex Source files, use by binder
8310 The effect of this consistency checking, which includes source files, is
8311 that the binder ensures that the program is consistent with the latest
8312 version of the source files that can be located at bind time. Editing a
8313 source file without compiling files that depend on the source file cause
8314 error messages to be generated by the binder.
8316 For example, suppose you have a main program @file{hello.adb} and a
8317 package @code{P}, from file @file{p.ads} and you perform the following
8322 Enter @code{gcc -c hello.adb} to compile the main program.
8325 Enter @code{gcc -c p.ads} to compile package @code{P}.
8328 Edit file @file{p.ads}.
8331 Enter @code{gnatbind hello}.
8335 At this point, the file @file{p.ali} contains an out-of-date time stamp
8336 because the file @file{p.ads} has been edited. The attempt at binding
8337 fails, and the binder generates the following error messages:
8340 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8341 error: "p.ads" has been modified and must be recompiled
8345 Now both files must be recompiled as indicated, and then the bind can
8346 succeed, generating a main program. You need not normally be concerned
8347 with the contents of this file, but for reference purposes a sample
8348 binder output file is given in @ref{Example of Binder Output File}.
8350 In most normal usage, the default mode of @command{gnatbind} which is to
8351 generate the main package in Ada, as described in the previous section.
8352 In particular, this means that any Ada programmer can read and understand
8353 the generated main program. It can also be debugged just like any other
8354 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8355 @command{gnatbind} and @command{gnatlink}.
8357 @node Switches for gnatbind
8358 @section Switches for @command{gnatbind}
8361 The following switches are available with @code{gnatbind}; details will
8362 be presented in subsequent sections.
8365 * Consistency-Checking Modes::
8366 * Binder Error Message Control::
8367 * Elaboration Control::
8369 * Dynamic Allocation Control::
8370 * Binding with Non-Ada Main Programs::
8371 * Binding Programs with No Main Subprogram::
8378 @cindex @option{--version} @command{gnatbind}
8379 Display Copyright and version, then exit disregarding all other options.
8382 @cindex @option{--help} @command{gnatbind}
8383 If @option{--version} was not used, display usage, then exit disregarding
8387 @cindex @option{-a} @command{gnatbind}
8388 Indicates that, if supported by the platform, the adainit procedure should
8389 be treated as an initialisation routine by the linker (a constructor). This
8390 is intended to be used by the Project Manager to automatically initialize
8391 shared Stand-Alone Libraries.
8393 @item ^-aO^/OBJECT_SEARCH^
8394 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8395 Specify directory to be searched for ALI files.
8397 @item ^-aI^/SOURCE_SEARCH^
8398 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8399 Specify directory to be searched for source file.
8401 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8402 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8403 Output ALI list (to standard output or to the named file).
8405 @item ^-b^/REPORT_ERRORS=BRIEF^
8406 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8407 Generate brief messages to @file{stderr} even if verbose mode set.
8409 @item ^-c^/NOOUTPUT^
8410 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8411 Check only, no generation of binder output file.
8413 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8414 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8415 This switch can be used to change the default task stack size value
8416 to a specified size @var{nn}, which is expressed in bytes by default, or
8417 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8419 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8420 in effect, to completing all task specs with
8421 @smallexample @c ada
8422 pragma Storage_Size (nn);
8424 When they do not already have such a pragma.
8426 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8427 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8428 This switch can be used to change the default secondary stack size value
8429 to a specified size @var{nn}, which is expressed in bytes by default, or
8430 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8433 The secondary stack is used to deal with functions that return a variable
8434 sized result, for example a function returning an unconstrained
8435 String. There are two ways in which this secondary stack is allocated.
8437 For most targets, the secondary stack is growing on demand and is allocated
8438 as a chain of blocks in the heap. The -D option is not very
8439 relevant. It only give some control over the size of the allocated
8440 blocks (whose size is the minimum of the default secondary stack size value,
8441 and the actual size needed for the current allocation request).
8443 For certain targets, notably VxWorks 653,
8444 the secondary stack is allocated by carving off a fixed ratio chunk of the
8445 primary task stack. The -D option is used to define the
8446 size of the environment task's secondary stack.
8448 @item ^-e^/ELABORATION_DEPENDENCIES^
8449 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8450 Output complete list of elaboration-order dependencies.
8452 @item ^-E^/STORE_TRACEBACKS^
8453 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8454 Store tracebacks in exception occurrences when the target supports it.
8456 @c The following may get moved to an appendix
8457 This option is currently supported on the following targets:
8458 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8460 See also the packages @code{GNAT.Traceback} and
8461 @code{GNAT.Traceback.Symbolic} for more information.
8463 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8464 @command{gcc} option.
8467 @item ^-F^/FORCE_ELABS_FLAGS^
8468 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8469 Force the checks of elaboration flags. @command{gnatbind} does not normally
8470 generate checks of elaboration flags for the main executable, except when
8471 a Stand-Alone Library is used. However, there are cases when this cannot be
8472 detected by gnatbind. An example is importing an interface of a Stand-Alone
8473 Library through a pragma Import and only specifying through a linker switch
8474 this Stand-Alone Library. This switch is used to guarantee that elaboration
8475 flag checks are generated.
8478 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8479 Output usage (help) information
8481 @item ^-H32^/32_MALLOC^
8482 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8483 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8484 For further details see @ref{Dynamic Allocation Control}.
8486 @item ^-H64^/64_MALLOC^
8487 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8488 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8489 @cindex @code{__gnat_malloc}
8490 For further details see @ref{Dynamic Allocation Control}.
8493 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8494 Specify directory to be searched for source and ALI files.
8496 @item ^-I-^/NOCURRENT_DIRECTORY^
8497 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8498 Do not look for sources in the current directory where @code{gnatbind} was
8499 invoked, and do not look for ALI files in the directory containing the
8500 ALI file named in the @code{gnatbind} command line.
8502 @item ^-l^/ORDER_OF_ELABORATION^
8503 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8504 Output chosen elaboration order.
8506 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8507 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8508 Bind the units for library building. In this case the adainit and
8509 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8510 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8511 ^@var{xxx}final^@var{XXX}FINAL^.
8512 Implies ^-n^/NOCOMPILE^.
8514 (@xref{GNAT and Libraries}, for more details.)
8517 On OpenVMS, these init and final procedures are exported in uppercase
8518 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8519 the init procedure will be "TOTOINIT" and the exported name of the final
8520 procedure will be "TOTOFINAL".
8523 @item ^-Mxyz^/RENAME_MAIN=xyz^
8524 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8525 Rename generated main program from main to xyz. This option is
8526 supported on cross environments only.
8528 @item ^-m^/ERROR_LIMIT=^@var{n}
8529 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8530 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8531 in the range 1..999999. The default value if no switch is
8532 given is 9999. If the number of warnings reaches this limit, then a
8533 message is output and further warnings are suppressed, the bind
8534 continues in this case. If the number of errors reaches this
8535 limit, then a message is output and the bind is abandoned.
8536 A value of zero means that no limit is enforced. The equal
8540 Furthermore, under Windows, the sources pointed to by the libraries path
8541 set in the registry are not searched for.
8545 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8549 @cindex @option{-nostdinc} (@command{gnatbind})
8550 Do not look for sources in the system default directory.
8553 @cindex @option{-nostdlib} (@command{gnatbind})
8554 Do not look for library files in the system default directory.
8556 @item --RTS=@var{rts-path}
8557 @cindex @option{--RTS} (@code{gnatbind})
8558 Specifies the default location of the runtime library. Same meaning as the
8559 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8561 @item ^-o ^/OUTPUT=^@var{file}
8562 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8563 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8564 Note that if this option is used, then linking must be done manually,
8565 gnatlink cannot be used.
8567 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8568 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8569 Output object list (to standard output or to the named file).
8571 @item ^-p^/PESSIMISTIC_ELABORATION^
8572 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8573 Pessimistic (worst-case) elaboration order
8576 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8577 Generate binder file suitable for CodePeer.
8580 @cindex @option{^-R^-R^} (@command{gnatbind})
8581 Output closure source list.
8583 @item ^-s^/READ_SOURCES=ALL^
8584 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8585 Require all source files to be present.
8587 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8588 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8589 Specifies the value to be used when detecting uninitialized scalar
8590 objects with pragma Initialize_Scalars.
8591 The @var{xxx} ^string specified with the switch^option^ may be either
8593 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8594 @item ``@option{^lo^LOW^}'' for the lowest possible value
8595 @item ``@option{^hi^HIGH^}'' for the highest possible value
8596 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8597 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8600 In addition, you can specify @option{-Sev} to indicate that the value is
8601 to be set at run time. In this case, the program will look for an environment
8602 @cindex GNAT_INIT_SCALARS
8603 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8604 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8605 If no environment variable is found, or if it does not have a valid value,
8606 then the default is @option{in} (invalid values).
8610 @cindex @option{-static} (@code{gnatbind})
8611 Link against a static GNAT run time.
8614 @cindex @option{-shared} (@code{gnatbind})
8615 Link against a shared GNAT run time when available.
8618 @item ^-t^/NOTIME_STAMP_CHECK^
8619 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8620 Tolerate time stamp and other consistency errors
8622 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8623 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8624 Set the time slice value to @var{n} milliseconds. If the system supports
8625 the specification of a specific time slice value, then the indicated value
8626 is used. If the system does not support specific time slice values, but
8627 does support some general notion of round-robin scheduling, then any
8628 nonzero value will activate round-robin scheduling.
8630 A value of zero is treated specially. It turns off time
8631 slicing, and in addition, indicates to the tasking run time that the
8632 semantics should match as closely as possible the Annex D
8633 requirements of the Ada RM, and in particular sets the default
8634 scheduling policy to @code{FIFO_Within_Priorities}.
8636 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8637 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8638 Enable dynamic stack usage, with @var{n} results stored and displayed
8639 at program termination. A result is generated when a task
8640 terminates. Results that can't be stored are displayed on the fly, at
8641 task termination. This option is currently not supported on Itanium
8642 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8644 @item ^-v^/REPORT_ERRORS=VERBOSE^
8645 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8646 Verbose mode. Write error messages, header, summary output to
8651 @cindex @option{-w} (@code{gnatbind})
8652 Warning mode (@var{x}=s/e for suppress/treat as error)
8656 @item /WARNINGS=NORMAL
8657 @cindex @option{/WARNINGS} (@code{gnatbind})
8658 Normal warnings mode. Warnings are issued but ignored
8660 @item /WARNINGS=SUPPRESS
8661 @cindex @option{/WARNINGS} (@code{gnatbind})
8662 All warning messages are suppressed
8664 @item /WARNINGS=ERROR
8665 @cindex @option{/WARNINGS} (@code{gnatbind})
8666 Warning messages are treated as fatal errors
8669 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8670 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8671 Override default wide character encoding for standard Text_IO files.
8673 @item ^-x^/READ_SOURCES=NONE^
8674 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8675 Exclude source files (check object consistency only).
8678 @item /READ_SOURCES=AVAILABLE
8679 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8680 Default mode, in which sources are checked for consistency only if
8684 @item ^-y^/ENABLE_LEAP_SECONDS^
8685 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8686 Enable leap seconds support in @code{Ada.Calendar} and its children.
8688 @item ^-z^/ZERO_MAIN^
8689 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8695 You may obtain this listing of switches by running @code{gnatbind} with
8699 @node Consistency-Checking Modes
8700 @subsection Consistency-Checking Modes
8703 As described earlier, by default @code{gnatbind} checks
8704 that object files are consistent with one another and are consistent
8705 with any source files it can locate. The following switches control binder
8710 @item ^-s^/READ_SOURCES=ALL^
8711 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8712 Require source files to be present. In this mode, the binder must be
8713 able to locate all source files that are referenced, in order to check
8714 their consistency. In normal mode, if a source file cannot be located it
8715 is simply ignored. If you specify this switch, a missing source
8718 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8719 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8720 Override default wide character encoding for standard Text_IO files.
8721 Normally the default wide character encoding method used for standard
8722 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8723 the main source input (see description of switch
8724 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8725 use of this switch for the binder (which has the same set of
8726 possible arguments) overrides this default as specified.
8728 @item ^-x^/READ_SOURCES=NONE^
8729 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8730 Exclude source files. In this mode, the binder only checks that ALI
8731 files are consistent with one another. Source files are not accessed.
8732 The binder runs faster in this mode, and there is still a guarantee that
8733 the resulting program is self-consistent.
8734 If a source file has been edited since it was last compiled, and you
8735 specify this switch, the binder will not detect that the object
8736 file is out of date with respect to the source file. Note that this is the
8737 mode that is automatically used by @command{gnatmake} because in this
8738 case the checking against sources has already been performed by
8739 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8742 @item /READ_SOURCES=AVAILABLE
8743 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8744 This is the default mode in which source files are checked if they are
8745 available, and ignored if they are not available.
8749 @node Binder Error Message Control
8750 @subsection Binder Error Message Control
8753 The following switches provide control over the generation of error
8754 messages from the binder:
8758 @item ^-v^/REPORT_ERRORS=VERBOSE^
8759 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8760 Verbose mode. In the normal mode, brief error messages are generated to
8761 @file{stderr}. If this switch is present, a header is written
8762 to @file{stdout} and any error messages are directed to @file{stdout}.
8763 All that is written to @file{stderr} is a brief summary message.
8765 @item ^-b^/REPORT_ERRORS=BRIEF^
8766 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8767 Generate brief error messages to @file{stderr} even if verbose mode is
8768 specified. This is relevant only when used with the
8769 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8773 @cindex @option{-m} (@code{gnatbind})
8774 Limits the number of error messages to @var{n}, a decimal integer in the
8775 range 1-999. The binder terminates immediately if this limit is reached.
8778 @cindex @option{-M} (@code{gnatbind})
8779 Renames the generated main program from @code{main} to @code{xxx}.
8780 This is useful in the case of some cross-building environments, where
8781 the actual main program is separate from the one generated
8785 @item ^-ws^/WARNINGS=SUPPRESS^
8786 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8788 Suppress all warning messages.
8790 @item ^-we^/WARNINGS=ERROR^
8791 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8792 Treat any warning messages as fatal errors.
8795 @item /WARNINGS=NORMAL
8796 Standard mode with warnings generated, but warnings do not get treated
8800 @item ^-t^/NOTIME_STAMP_CHECK^
8801 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8802 @cindex Time stamp checks, in binder
8803 @cindex Binder consistency checks
8804 @cindex Consistency checks, in binder
8805 The binder performs a number of consistency checks including:
8809 Check that time stamps of a given source unit are consistent
8811 Check that checksums of a given source unit are consistent
8813 Check that consistent versions of @code{GNAT} were used for compilation
8815 Check consistency of configuration pragmas as required
8819 Normally failure of such checks, in accordance with the consistency
8820 requirements of the Ada Reference Manual, causes error messages to be
8821 generated which abort the binder and prevent the output of a binder
8822 file and subsequent link to obtain an executable.
8824 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8825 into warnings, so that
8826 binding and linking can continue to completion even in the presence of such
8827 errors. The result may be a failed link (due to missing symbols), or a
8828 non-functional executable which has undefined semantics.
8829 @emph{This means that
8830 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8834 @node Elaboration Control
8835 @subsection Elaboration Control
8838 The following switches provide additional control over the elaboration
8839 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8842 @item ^-p^/PESSIMISTIC_ELABORATION^
8843 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8844 Normally the binder attempts to choose an elaboration order that is
8845 likely to minimize the likelihood of an elaboration order error resulting
8846 in raising a @code{Program_Error} exception. This switch reverses the
8847 action of the binder, and requests that it deliberately choose an order
8848 that is likely to maximize the likelihood of an elaboration error.
8849 This is useful in ensuring portability and avoiding dependence on
8850 accidental fortuitous elaboration ordering.
8852 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8854 elaboration checking is used (@option{-gnatE} switch used for compilation).
8855 This is because in the default static elaboration mode, all necessary
8856 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8857 These implicit pragmas are still respected by the binder in
8858 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8859 safe elaboration order is assured.
8861 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8862 production use; it is more for debugging/experimental use.
8865 @node Output Control
8866 @subsection Output Control
8869 The following switches allow additional control over the output
8870 generated by the binder.
8875 @item ^-c^/NOOUTPUT^
8876 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8877 Check only. Do not generate the binder output file. In this mode the
8878 binder performs all error checks but does not generate an output file.
8880 @item ^-e^/ELABORATION_DEPENDENCIES^
8881 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8882 Output complete list of elaboration-order dependencies, showing the
8883 reason for each dependency. This output can be rather extensive but may
8884 be useful in diagnosing problems with elaboration order. The output is
8885 written to @file{stdout}.
8888 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8889 Output usage information. The output is written to @file{stdout}.
8891 @item ^-K^/LINKER_OPTION_LIST^
8892 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8893 Output linker options to @file{stdout}. Includes library search paths,
8894 contents of pragmas Ident and Linker_Options, and libraries added
8897 @item ^-l^/ORDER_OF_ELABORATION^
8898 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8899 Output chosen elaboration order. The output is written to @file{stdout}.
8901 @item ^-O^/OBJECT_LIST^
8902 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8903 Output full names of all the object files that must be linked to provide
8904 the Ada component of the program. The output is written to @file{stdout}.
8905 This list includes the files explicitly supplied and referenced by the user
8906 as well as implicitly referenced run-time unit files. The latter are
8907 omitted if the corresponding units reside in shared libraries. The
8908 directory names for the run-time units depend on the system configuration.
8910 @item ^-o ^/OUTPUT=^@var{file}
8911 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8912 Set name of output file to @var{file} instead of the normal
8913 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8914 binder generated body filename.
8915 Note that if this option is used, then linking must be done manually.
8916 It is not possible to use gnatlink in this case, since it cannot locate
8919 @item ^-r^/RESTRICTION_LIST^
8920 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8921 Generate list of @code{pragma Restrictions} that could be applied to
8922 the current unit. This is useful for code audit purposes, and also may
8923 be used to improve code generation in some cases.
8927 @node Dynamic Allocation Control
8928 @subsection Dynamic Allocation Control
8931 The heap control switches -- @option{-H32} and @option{-H64} --
8932 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8933 They only affect compiler-generated allocations via @code{__gnat_malloc};
8934 explicit calls to @code{malloc} and related functions from the C
8935 run-time library are unaffected.
8939 Allocate memory on 32-bit heap
8942 Allocate memory on 64-bit heap. This is the default
8943 unless explicitly overridden by a @code{'Size} clause on the access type.
8948 See also @ref{Access types and 32/64-bit allocation}.
8952 These switches are only effective on VMS platforms.
8956 @node Binding with Non-Ada Main Programs
8957 @subsection Binding with Non-Ada Main Programs
8960 In our description so far we have assumed that the main
8961 program is in Ada, and that the task of the binder is to generate a
8962 corresponding function @code{main} that invokes this Ada main
8963 program. GNAT also supports the building of executable programs where
8964 the main program is not in Ada, but some of the called routines are
8965 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8966 The following switch is used in this situation:
8970 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8971 No main program. The main program is not in Ada.
8975 In this case, most of the functions of the binder are still required,
8976 but instead of generating a main program, the binder generates a file
8977 containing the following callable routines:
8982 You must call this routine to initialize the Ada part of the program by
8983 calling the necessary elaboration routines. A call to @code{adainit} is
8984 required before the first call to an Ada subprogram.
8986 Note that it is assumed that the basic execution environment must be setup
8987 to be appropriate for Ada execution at the point where the first Ada
8988 subprogram is called. In particular, if the Ada code will do any
8989 floating-point operations, then the FPU must be setup in an appropriate
8990 manner. For the case of the x86, for example, full precision mode is
8991 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8992 that the FPU is in the right state.
8996 You must call this routine to perform any library-level finalization
8997 required by the Ada subprograms. A call to @code{adafinal} is required
8998 after the last call to an Ada subprogram, and before the program
9003 If the @option{^-n^/NOMAIN^} switch
9004 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
9005 @cindex Binder, multiple input files
9006 is given, more than one ALI file may appear on
9007 the command line for @code{gnatbind}. The normal @dfn{closure}
9008 calculation is performed for each of the specified units. Calculating
9009 the closure means finding out the set of units involved by tracing
9010 @code{with} references. The reason it is necessary to be able to
9011 specify more than one ALI file is that a given program may invoke two or
9012 more quite separate groups of Ada units.
9014 The binder takes the name of its output file from the last specified ALI
9015 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
9016 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
9017 The output is an Ada unit in source form that can be compiled with GNAT.
9018 This compilation occurs automatically as part of the @command{gnatlink}
9021 Currently the GNAT run time requires a FPU using 80 bits mode
9022 precision. Under targets where this is not the default it is required to
9023 call GNAT.Float_Control.Reset before using floating point numbers (this
9024 include float computation, float input and output) in the Ada code. A
9025 side effect is that this could be the wrong mode for the foreign code
9026 where floating point computation could be broken after this call.
9028 @node Binding Programs with No Main Subprogram
9029 @subsection Binding Programs with No Main Subprogram
9032 It is possible to have an Ada program which does not have a main
9033 subprogram. This program will call the elaboration routines of all the
9034 packages, then the finalization routines.
9036 The following switch is used to bind programs organized in this manner:
9039 @item ^-z^/ZERO_MAIN^
9040 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
9041 Normally the binder checks that the unit name given on the command line
9042 corresponds to a suitable main subprogram. When this switch is used,
9043 a list of ALI files can be given, and the execution of the program
9044 consists of elaboration of these units in an appropriate order. Note
9045 that the default wide character encoding method for standard Text_IO
9046 files is always set to Brackets if this switch is set (you can use
9048 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
9051 @node Command-Line Access
9052 @section Command-Line Access
9055 The package @code{Ada.Command_Line} provides access to the command-line
9056 arguments and program name. In order for this interface to operate
9057 correctly, the two variables
9069 are declared in one of the GNAT library routines. These variables must
9070 be set from the actual @code{argc} and @code{argv} values passed to the
9071 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
9072 generates the C main program to automatically set these variables.
9073 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
9074 set these variables. If they are not set, the procedures in
9075 @code{Ada.Command_Line} will not be available, and any attempt to use
9076 them will raise @code{Constraint_Error}. If command line access is
9077 required, your main program must set @code{gnat_argc} and
9078 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
9081 @node Search Paths for gnatbind
9082 @section Search Paths for @code{gnatbind}
9085 The binder takes the name of an ALI file as its argument and needs to
9086 locate source files as well as other ALI files to verify object consistency.
9088 For source files, it follows exactly the same search rules as @command{gcc}
9089 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
9090 directories searched are:
9094 The directory containing the ALI file named in the command line, unless
9095 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
9098 All directories specified by @option{^-I^/SEARCH^}
9099 switches on the @code{gnatbind}
9100 command line, in the order given.
9103 @findex ADA_PRJ_OBJECTS_FILE
9104 Each of the directories listed in the text file whose name is given
9105 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
9108 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
9109 driver when project files are used. It should not normally be set
9113 @findex ADA_OBJECTS_PATH
9114 Each of the directories listed in the value of the
9115 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
9117 Construct this value
9118 exactly as the @env{PATH} environment variable: a list of directory
9119 names separated by colons (semicolons when working with the NT version
9123 Normally, define this value as a logical name containing a comma separated
9124 list of directory names.
9126 This variable can also be defined by means of an environment string
9127 (an argument to the HP C exec* set of functions).
9131 DEFINE ANOTHER_PATH FOO:[BAG]
9132 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9135 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9136 first, followed by the standard Ada
9137 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9138 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9139 (Text_IO, Sequential_IO, etc)
9140 instead of the standard Ada packages. Thus, in order to get the standard Ada
9141 packages by default, ADA_OBJECTS_PATH must be redefined.
9145 The content of the @file{ada_object_path} file which is part of the GNAT
9146 installation tree and is used to store standard libraries such as the
9147 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9150 @ref{Installing a library}
9155 In the binder the switch @option{^-I^/SEARCH^}
9156 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9157 is used to specify both source and
9158 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9159 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9160 instead if you want to specify
9161 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9162 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9163 if you want to specify library paths
9164 only. This means that for the binder
9165 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9166 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9167 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9168 The binder generates the bind file (a C language source file) in the
9169 current working directory.
9175 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9176 children make up the GNAT Run-Time Library, together with the package
9177 GNAT and its children, which contain a set of useful additional
9178 library functions provided by GNAT. The sources for these units are
9179 needed by the compiler and are kept together in one directory. The ALI
9180 files and object files generated by compiling the RTL are needed by the
9181 binder and the linker and are kept together in one directory, typically
9182 different from the directory containing the sources. In a normal
9183 installation, you need not specify these directory names when compiling
9184 or binding. Either the environment variables or the built-in defaults
9185 cause these files to be found.
9187 Besides simplifying access to the RTL, a major use of search paths is
9188 in compiling sources from multiple directories. This can make
9189 development environments much more flexible.
9191 @node Examples of gnatbind Usage
9192 @section Examples of @code{gnatbind} Usage
9195 This section contains a number of examples of using the GNAT binding
9196 utility @code{gnatbind}.
9199 @item gnatbind hello
9200 The main program @code{Hello} (source program in @file{hello.adb}) is
9201 bound using the standard switch settings. The generated main program is
9202 @file{b~hello.adb}. This is the normal, default use of the binder.
9205 @item gnatbind hello -o mainprog.adb
9208 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9210 The main program @code{Hello} (source program in @file{hello.adb}) is
9211 bound using the standard switch settings. The generated main program is
9212 @file{mainprog.adb} with the associated spec in
9213 @file{mainprog.ads}. Note that you must specify the body here not the
9214 spec. Note that if this option is used, then linking must be done manually,
9215 since gnatlink will not be able to find the generated file.
9218 @c ------------------------------------
9219 @node Linking Using gnatlink
9220 @chapter Linking Using @command{gnatlink}
9221 @c ------------------------------------
9225 This chapter discusses @command{gnatlink}, a tool that links
9226 an Ada program and builds an executable file. This utility
9227 invokes the system linker ^(via the @command{gcc} command)^^
9228 with a correct list of object files and library references.
9229 @command{gnatlink} automatically determines the list of files and
9230 references for the Ada part of a program. It uses the binder file
9231 generated by the @command{gnatbind} to determine this list.
9233 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9234 driver (see @ref{The GNAT Driver and Project Files}).
9237 * Running gnatlink::
9238 * Switches for gnatlink::
9241 @node Running gnatlink
9242 @section Running @command{gnatlink}
9245 The form of the @command{gnatlink} command is
9248 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9249 @c @ovar{non-Ada objects} @ovar{linker options}
9250 @c Expanding @ovar macro inline (explanation in macro def comments)
9251 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9252 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9257 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9259 or linker options) may be in any order, provided that no non-Ada object may
9260 be mistaken for a main @file{ALI} file.
9261 Any file name @file{F} without the @file{.ali}
9262 extension will be taken as the main @file{ALI} file if a file exists
9263 whose name is the concatenation of @file{F} and @file{.ali}.
9266 @file{@var{mainprog}.ali} references the ALI file of the main program.
9267 The @file{.ali} extension of this file can be omitted. From this
9268 reference, @command{gnatlink} locates the corresponding binder file
9269 @file{b~@var{mainprog}.adb} and, using the information in this file along
9270 with the list of non-Ada objects and linker options, constructs a
9271 linker command file to create the executable.
9273 The arguments other than the @command{gnatlink} switches and the main
9274 @file{ALI} file are passed to the linker uninterpreted.
9275 They typically include the names of
9276 object files for units written in other languages than Ada and any library
9277 references required to resolve references in any of these foreign language
9278 units, or in @code{Import} pragmas in any Ada units.
9280 @var{linker options} is an optional list of linker specific
9282 The default linker called by gnatlink is @command{gcc} which in
9283 turn calls the appropriate system linker.
9285 One useful option for the linker is @option{-s}: it reduces the size of the
9286 executable by removing all symbol table and relocation information from the
9289 Standard options for the linker such as @option{-lmy_lib} or
9290 @option{-Ldir} can be added as is.
9291 For options that are not recognized by
9292 @command{gcc} as linker options, use the @command{gcc} switches
9293 @option{-Xlinker} or @option{-Wl,}.
9295 Refer to the GCC documentation for
9298 Here is an example showing how to generate a linker map:
9301 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9304 Using @var{linker options} it is possible to set the program stack and
9307 See @ref{Setting Stack Size from gnatlink} and
9308 @ref{Setting Heap Size from gnatlink}.
9311 @command{gnatlink} determines the list of objects required by the Ada
9312 program and prepends them to the list of objects passed to the linker.
9313 @command{gnatlink} also gathers any arguments set by the use of
9314 @code{pragma Linker_Options} and adds them to the list of arguments
9315 presented to the linker.
9318 @command{gnatlink} accepts the following types of extra files on the command
9319 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9320 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9321 handled according to their extension.
9324 @node Switches for gnatlink
9325 @section Switches for @command{gnatlink}
9328 The following switches are available with the @command{gnatlink} utility:
9334 @cindex @option{--version} @command{gnatlink}
9335 Display Copyright and version, then exit disregarding all other options.
9338 @cindex @option{--help} @command{gnatlink}
9339 If @option{--version} was not used, display usage, then exit disregarding
9342 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9343 @cindex Command line length
9344 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9345 On some targets, the command line length is limited, and @command{gnatlink}
9346 will generate a separate file for the linker if the list of object files
9348 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9349 to be generated even if
9350 the limit is not exceeded. This is useful in some cases to deal with
9351 special situations where the command line length is exceeded.
9354 @cindex Debugging information, including
9355 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9356 The option to include debugging information causes the Ada bind file (in
9357 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9358 @option{^-g^/DEBUG^}.
9359 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9360 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9361 Without @option{^-g^/DEBUG^}, the binder removes these files by
9362 default. The same procedure apply if a C bind file was generated using
9363 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9364 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9366 @item ^-n^/NOCOMPILE^
9367 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9368 Do not compile the file generated by the binder. This may be used when
9369 a link is rerun with different options, but there is no need to recompile
9373 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9374 Causes additional information to be output, including a full list of the
9375 included object files. This switch option is most useful when you want
9376 to see what set of object files are being used in the link step.
9378 @item ^-v -v^/VERBOSE/VERBOSE^
9379 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9380 Very verbose mode. Requests that the compiler operate in verbose mode when
9381 it compiles the binder file, and that the system linker run in verbose mode.
9383 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9384 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9385 @var{exec-name} specifies an alternate name for the generated
9386 executable program. If this switch is omitted, the executable has the same
9387 name as the main unit. For example, @code{gnatlink try.ali} creates
9388 an executable called @file{^try^TRY.EXE^}.
9391 @item -b @var{target}
9392 @cindex @option{-b} (@command{gnatlink})
9393 Compile your program to run on @var{target}, which is the name of a
9394 system configuration. You must have a GNAT cross-compiler built if
9395 @var{target} is not the same as your host system.
9398 @cindex @option{-B} (@command{gnatlink})
9399 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9400 from @var{dir} instead of the default location. Only use this switch
9401 when multiple versions of the GNAT compiler are available.
9402 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9403 for further details. You would normally use the @option{-b} or
9404 @option{-V} switch instead.
9407 When linking an executable, create a map file. The name of the map file
9408 has the same name as the executable with extension ".map".
9411 When linking an executable, create a map file. The name of the map file is
9414 @item --GCC=@var{compiler_name}
9415 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9416 Program used for compiling the binder file. The default is
9417 @command{gcc}. You need to use quotes around @var{compiler_name} if
9418 @code{compiler_name} contains spaces or other separator characters.
9419 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9420 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9421 inserted after your command name. Thus in the above example the compiler
9422 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9423 A limitation of this syntax is that the name and path name of the executable
9424 itself must not include any embedded spaces. If the compiler executable is
9425 different from the default one (gcc or <prefix>-gcc), then the back-end
9426 switches in the ALI file are not used to compile the binder generated source.
9427 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9428 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9429 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9430 is taken into account. However, all the additional switches are also taken
9432 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9433 @option{--GCC="bar -x -y -z -t"}.
9435 @item --LINK=@var{name}
9436 @cindex @option{--LINK=} (@command{gnatlink})
9437 @var{name} is the name of the linker to be invoked. This is especially
9438 useful in mixed language programs since languages such as C++ require
9439 their own linker to be used. When this switch is omitted, the default
9440 name for the linker is @command{gcc}. When this switch is used, the
9441 specified linker is called instead of @command{gcc} with exactly the same
9442 parameters that would have been passed to @command{gcc} so if the desired
9443 linker requires different parameters it is necessary to use a wrapper
9444 script that massages the parameters before invoking the real linker. It
9445 may be useful to control the exact invocation by using the verbose
9451 @item /DEBUG=TRACEBACK
9452 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9453 This qualifier causes sufficient information to be included in the
9454 executable file to allow a traceback, but does not include the full
9455 symbol information needed by the debugger.
9457 @item /IDENTIFICATION="<string>"
9458 @code{"<string>"} specifies the string to be stored in the image file
9459 identification field in the image header.
9460 It overrides any pragma @code{Ident} specified string.
9462 @item /NOINHIBIT-EXEC
9463 Generate the executable file even if there are linker warnings.
9465 @item /NOSTART_FILES
9466 Don't link in the object file containing the ``main'' transfer address.
9467 Used when linking with a foreign language main program compiled with an
9471 Prefer linking with object libraries over sharable images, even without
9477 @node The GNAT Make Program gnatmake
9478 @chapter The GNAT Make Program @command{gnatmake}
9482 * Running gnatmake::
9483 * Switches for gnatmake::
9484 * Mode Switches for gnatmake::
9485 * Notes on the Command Line::
9486 * How gnatmake Works::
9487 * Examples of gnatmake Usage::
9490 A typical development cycle when working on an Ada program consists of
9491 the following steps:
9495 Edit some sources to fix bugs.
9501 Compile all sources affected.
9511 The third step can be tricky, because not only do the modified files
9512 @cindex Dependency rules
9513 have to be compiled, but any files depending on these files must also be
9514 recompiled. The dependency rules in Ada can be quite complex, especially
9515 in the presence of overloading, @code{use} clauses, generics and inlined
9518 @command{gnatmake} automatically takes care of the third and fourth steps
9519 of this process. It determines which sources need to be compiled,
9520 compiles them, and binds and links the resulting object files.
9522 Unlike some other Ada make programs, the dependencies are always
9523 accurately recomputed from the new sources. The source based approach of
9524 the GNAT compilation model makes this possible. This means that if
9525 changes to the source program cause corresponding changes in
9526 dependencies, they will always be tracked exactly correctly by
9529 @node Running gnatmake
9530 @section Running @command{gnatmake}
9533 The usual form of the @command{gnatmake} command is
9536 @c $ gnatmake @ovar{switches} @var{file_name}
9537 @c @ovar{file_names} @ovar{mode_switches}
9538 @c Expanding @ovar macro inline (explanation in macro def comments)
9539 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9540 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9544 The only required argument is one @var{file_name}, which specifies
9545 a compilation unit that is a main program. Several @var{file_names} can be
9546 specified: this will result in several executables being built.
9547 If @code{switches} are present, they can be placed before the first
9548 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9549 If @var{mode_switches} are present, they must always be placed after
9550 the last @var{file_name} and all @code{switches}.
9552 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9553 extension may be omitted from the @var{file_name} arguments. However, if
9554 you are using non-standard extensions, then it is required that the
9555 extension be given. A relative or absolute directory path can be
9556 specified in a @var{file_name}, in which case, the input source file will
9557 be searched for in the specified directory only. Otherwise, the input
9558 source file will first be searched in the directory where
9559 @command{gnatmake} was invoked and if it is not found, it will be search on
9560 the source path of the compiler as described in
9561 @ref{Search Paths and the Run-Time Library (RTL)}.
9563 All @command{gnatmake} output (except when you specify
9564 @option{^-M^/DEPENDENCIES_LIST^}) is to
9565 @file{stderr}. The output produced by the
9566 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9569 @node Switches for gnatmake
9570 @section Switches for @command{gnatmake}
9573 You may specify any of the following switches to @command{gnatmake}:
9579 @cindex @option{--version} @command{gnatmake}
9580 Display Copyright and version, then exit disregarding all other options.
9583 @cindex @option{--help} @command{gnatmake}
9584 If @option{--version} was not used, display usage, then exit disregarding
9588 @item --GCC=@var{compiler_name}
9589 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9590 Program used for compiling. The default is `@command{gcc}'. You need to use
9591 quotes around @var{compiler_name} if @code{compiler_name} contains
9592 spaces or other separator characters. As an example @option{--GCC="foo -x
9593 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9594 compiler. A limitation of this syntax is that the name and path name of
9595 the executable itself must not include any embedded spaces. Note that
9596 switch @option{-c} is always inserted after your command name. Thus in the
9597 above example the compiler command that will be used by @command{gnatmake}
9598 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9599 used, only the last @var{compiler_name} is taken into account. However,
9600 all the additional switches are also taken into account. Thus,
9601 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9602 @option{--GCC="bar -x -y -z -t"}.
9604 @item --GNATBIND=@var{binder_name}
9605 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9606 Program used for binding. The default is `@code{gnatbind}'. You need to
9607 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9608 or other separator characters. As an example @option{--GNATBIND="bar -x
9609 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9610 binder. Binder switches that are normally appended by @command{gnatmake}
9611 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9612 A limitation of this syntax is that the name and path name of the executable
9613 itself must not include any embedded spaces.
9615 @item --GNATLINK=@var{linker_name}
9616 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9617 Program used for linking. The default is `@command{gnatlink}'. You need to
9618 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9619 or other separator characters. As an example @option{--GNATLINK="lan -x
9620 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9621 linker. Linker switches that are normally appended by @command{gnatmake} to
9622 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9623 A limitation of this syntax is that the name and path name of the executable
9624 itself must not include any embedded spaces.
9628 @item ^--subdirs^/SUBDIRS^=subdir
9629 Actual object directory of each project file is the subdirectory subdir of the
9630 object directory specified or defaulted in the project file.
9632 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9633 Disallow simultaneous compilations in the same object directory when
9634 project files are used.
9636 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9637 By default, shared library projects are not allowed to import static library
9638 projects. When this switch is used on the command line, this restriction is
9641 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9642 Specify a source info file. This switch is active only when project files
9643 are used. If the source info file is specified as a relative path, then it is
9644 relative to the object directory of the main project. If the source info file
9645 does not exist, then after the Project Manager has successfully parsed and
9646 processed the project files and found the sources, it creates the source info
9647 file. If the source info file already exists and can be read successfully,
9648 then the Project Manager will get all the needed information about the sources
9649 from the source info file and will not look for them. This reduces the time
9650 to process the project files, especially when looking for sources that take a
9651 long time. If the source info file exists but cannot be parsed successfully,
9652 the Project Manager will attempt to recreate it. If the Project Manager fails
9653 to create the source info file, a message is issued, but gnatmake does not
9654 fail. @command{gnatmake} "trusts" the source info file. This means that
9655 if the source files have changed (addition, deletion, moving to a different
9656 source directory), then the source info file need to be deleted and recreated.
9659 @item --create-map-file
9660 When linking an executable, create a map file. The name of the map file
9661 has the same name as the executable with extension ".map".
9663 @item --create-map-file=mapfile
9664 When linking an executable, create a map file. The name of the map file is
9669 @item ^-a^/ALL_FILES^
9670 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9671 Consider all files in the make process, even the GNAT internal system
9672 files (for example, the predefined Ada library files), as well as any
9673 locked files. Locked files are files whose ALI file is write-protected.
9675 @command{gnatmake} does not check these files,
9676 because the assumption is that the GNAT internal files are properly up
9677 to date, and also that any write protected ALI files have been properly
9678 installed. Note that if there is an installation problem, such that one
9679 of these files is not up to date, it will be properly caught by the
9681 You may have to specify this switch if you are working on GNAT
9682 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9683 in conjunction with @option{^-f^/FORCE_COMPILE^}
9684 if you need to recompile an entire application,
9685 including run-time files, using special configuration pragmas,
9686 such as a @code{Normalize_Scalars} pragma.
9689 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9692 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9695 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9698 @item ^-b^/ACTIONS=BIND^
9699 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9700 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9701 compilation and binding, but no link.
9702 Can be combined with @option{^-l^/ACTIONS=LINK^}
9703 to do binding and linking. When not combined with
9704 @option{^-c^/ACTIONS=COMPILE^}
9705 all the units in the closure of the main program must have been previously
9706 compiled and must be up to date. The root unit specified by @var{file_name}
9707 may be given without extension, with the source extension or, if no GNAT
9708 Project File is specified, with the ALI file extension.
9710 @item ^-c^/ACTIONS=COMPILE^
9711 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9712 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9713 is also specified. Do not perform linking, except if both
9714 @option{^-b^/ACTIONS=BIND^} and
9715 @option{^-l^/ACTIONS=LINK^} are also specified.
9716 If the root unit specified by @var{file_name} is not a main unit, this is the
9717 default. Otherwise @command{gnatmake} will attempt binding and linking
9718 unless all objects are up to date and the executable is more recent than
9722 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9723 Use a temporary mapping file. A mapping file is a way to communicate
9724 to the compiler two mappings: from unit names to file names (without
9725 any directory information) and from file names to path names (with
9726 full directory information). A mapping file can make the compiler's
9727 file searches faster, especially if there are many source directories,
9728 or the sources are read over a slow network connection. If
9729 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9730 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9731 is initially populated based on the project file. If
9732 @option{^-C^/MAPPING^} is used without
9733 @option{^-P^/PROJECT_FILE^},
9734 the mapping file is initially empty. Each invocation of the compiler
9735 will add any newly accessed sources to the mapping file.
9737 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9738 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9739 Use a specific mapping file. The file, specified as a path name (absolute or
9740 relative) by this switch, should already exist, otherwise the switch is
9741 ineffective. The specified mapping file will be communicated to the compiler.
9742 This switch is not compatible with a project file
9743 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9744 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9746 @item ^-d^/DISPLAY_PROGRESS^
9747 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9748 Display progress for each source, up to date or not, as a single line
9751 completed x out of y (zz%)
9754 If the file needs to be compiled this is displayed after the invocation of
9755 the compiler. These lines are displayed even in quiet output mode.
9757 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9758 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9759 Put all object files and ALI file in directory @var{dir}.
9760 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9761 and ALI files go in the current working directory.
9763 This switch cannot be used when using a project file.
9766 @cindex @option{-eI} (@command{gnatmake})
9767 Indicates that the main source is a multi-unit source and the rank of the unit
9768 in the source file is nnn. nnn needs to be a positive number and a valid
9769 index in the source. This switch cannot be used when @command{gnatmake} is
9770 invoked for several mains.
9774 @cindex @option{-eL} (@command{gnatmake})
9775 @cindex symbolic links
9776 Follow all symbolic links when processing project files.
9777 This should be used if your project uses symbolic links for files or
9778 directories, but is not needed in other cases.
9780 @cindex naming scheme
9781 This also assumes that no directory matches the naming scheme for files (for
9782 instance that you do not have a directory called "sources.ads" when using the
9783 default GNAT naming scheme).
9785 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9786 save a lot of system calls (several per source file and object file), which
9787 can result in a significant speed up to load and manipulate a project file,
9788 especially when using source files from a remote system.
9792 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9793 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9794 Output the commands for the compiler, the binder and the linker
9795 on ^standard output^SYS$OUTPUT^,
9796 instead of ^standard error^SYS$ERROR^.
9798 @item ^-f^/FORCE_COMPILE^
9799 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9800 Force recompilations. Recompile all sources, even though some object
9801 files may be up to date, but don't recompile predefined or GNAT internal
9802 files or locked files (files with a write-protected ALI file),
9803 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9805 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9806 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9807 When using project files, if some errors or warnings are detected during
9808 parsing and verbose mode is not in effect (no use of switch
9809 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9810 file, rather than its simple file name.
9813 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9814 Enable debugging. This switch is simply passed to the compiler and to the
9817 @item ^-i^/IN_PLACE^
9818 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9819 In normal mode, @command{gnatmake} compiles all object files and ALI files
9820 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9821 then instead object files and ALI files that already exist are overwritten
9822 in place. This means that once a large project is organized into separate
9823 directories in the desired manner, then @command{gnatmake} will automatically
9824 maintain and update this organization. If no ALI files are found on the
9825 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9826 the new object and ALI files are created in the
9827 directory containing the source being compiled. If another organization
9828 is desired, where objects and sources are kept in different directories,
9829 a useful technique is to create dummy ALI files in the desired directories.
9830 When detecting such a dummy file, @command{gnatmake} will be forced to
9831 recompile the corresponding source file, and it will be put the resulting
9832 object and ALI files in the directory where it found the dummy file.
9834 @item ^-j^/PROCESSES=^@var{n}
9835 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9836 @cindex Parallel make
9837 Use @var{n} processes to carry out the (re)compilations. On a
9838 multiprocessor machine compilations will occur in parallel. In the
9839 event of compilation errors, messages from various compilations might
9840 get interspersed (but @command{gnatmake} will give you the full ordered
9841 list of failing compiles at the end). If this is problematic, rerun
9842 the make process with n set to 1 to get a clean list of messages.
9844 @item ^-k^/CONTINUE_ON_ERROR^
9845 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9846 Keep going. Continue as much as possible after a compilation error. To
9847 ease the programmer's task in case of compilation errors, the list of
9848 sources for which the compile fails is given when @command{gnatmake}
9851 If @command{gnatmake} is invoked with several @file{file_names} and with this
9852 switch, if there are compilation errors when building an executable,
9853 @command{gnatmake} will not attempt to build the following executables.
9855 @item ^-l^/ACTIONS=LINK^
9856 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9857 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9858 and linking. Linking will not be performed if combined with
9859 @option{^-c^/ACTIONS=COMPILE^}
9860 but not with @option{^-b^/ACTIONS=BIND^}.
9861 When not combined with @option{^-b^/ACTIONS=BIND^}
9862 all the units in the closure of the main program must have been previously
9863 compiled and must be up to date, and the main program needs to have been bound.
9864 The root unit specified by @var{file_name}
9865 may be given without extension, with the source extension or, if no GNAT
9866 Project File is specified, with the ALI file extension.
9868 @item ^-m^/MINIMAL_RECOMPILATION^
9869 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9870 Specify that the minimum necessary amount of recompilations
9871 be performed. In this mode @command{gnatmake} ignores time
9872 stamp differences when the only
9873 modifications to a source file consist in adding/removing comments,
9874 empty lines, spaces or tabs. This means that if you have changed the
9875 comments in a source file or have simply reformatted it, using this
9876 switch will tell @command{gnatmake} not to recompile files that depend on it
9877 (provided other sources on which these files depend have undergone no
9878 semantic modifications). Note that the debugging information may be
9879 out of date with respect to the sources if the @option{-m} switch causes
9880 a compilation to be switched, so the use of this switch represents a
9881 trade-off between compilation time and accurate debugging information.
9883 @item ^-M^/DEPENDENCIES_LIST^
9884 @cindex Dependencies, producing list
9885 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9886 Check if all objects are up to date. If they are, output the object
9887 dependences to @file{stdout} in a form that can be directly exploited in
9888 a @file{Makefile}. By default, each source file is prefixed with its
9889 (relative or absolute) directory name. This name is whatever you
9890 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9891 and @option{^-I^/SEARCH^} switches. If you use
9892 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9893 @option{^-q^/QUIET^}
9894 (see below), only the source file names,
9895 without relative paths, are output. If you just specify the
9896 @option{^-M^/DEPENDENCIES_LIST^}
9897 switch, dependencies of the GNAT internal system files are omitted. This
9898 is typically what you want. If you also specify
9899 the @option{^-a^/ALL_FILES^} switch,
9900 dependencies of the GNAT internal files are also listed. Note that
9901 dependencies of the objects in external Ada libraries (see switch
9902 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9905 @item ^-n^/DO_OBJECT_CHECK^
9906 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9907 Don't compile, bind, or link. Checks if all objects are up to date.
9908 If they are not, the full name of the first file that needs to be
9909 recompiled is printed.
9910 Repeated use of this option, followed by compiling the indicated source
9911 file, will eventually result in recompiling all required units.
9913 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9914 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9915 Output executable name. The name of the final executable program will be
9916 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9917 name for the executable will be the name of the input file in appropriate form
9918 for an executable file on the host system.
9920 This switch cannot be used when invoking @command{gnatmake} with several
9923 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9924 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9925 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9926 automatically missing object directories, library directories and exec
9929 @item ^-P^/PROJECT_FILE=^@var{project}
9930 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9931 Use project file @var{project}. Only one such switch can be used.
9932 @xref{gnatmake and Project Files}.
9935 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9936 Quiet. When this flag is not set, the commands carried out by
9937 @command{gnatmake} are displayed.
9939 @item ^-s^/SWITCH_CHECK/^
9940 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9941 Recompile if compiler switches have changed since last compilation.
9942 All compiler switches but -I and -o are taken into account in the
9944 orders between different ``first letter'' switches are ignored, but
9945 orders between same switches are taken into account. For example,
9946 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9947 is equivalent to @option{-O -g}.
9949 This switch is recommended when Integrated Preprocessing is used.
9952 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9953 Unique. Recompile at most the main files. It implies -c. Combined with
9954 -f, it is equivalent to calling the compiler directly. Note that using
9955 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9956 (@pxref{Project Files and Main Subprograms}).
9958 @item ^-U^/ALL_PROJECTS^
9959 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9960 When used without a project file or with one or several mains on the command
9961 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9962 on the command line, all sources of all project files are checked and compiled
9963 if not up to date, and libraries are rebuilt, if necessary.
9966 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9967 Verbose. Display the reason for all recompilations @command{gnatmake}
9968 decides are necessary, with the highest verbosity level.
9970 @item ^-vl^/LOW_VERBOSITY^
9971 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9972 Verbosity level Low. Display fewer lines than in verbosity Medium.
9974 @item ^-vm^/MEDIUM_VERBOSITY^
9975 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9976 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9978 @item ^-vh^/HIGH_VERBOSITY^
9979 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9980 Verbosity level High. Equivalent to ^-v^/REASONS^.
9982 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9983 Indicate the verbosity of the parsing of GNAT project files.
9984 @xref{Switches Related to Project Files}.
9986 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9987 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9988 Indicate that sources that are not part of any Project File may be compiled.
9989 Normally, when using Project Files, only sources that are part of a Project
9990 File may be compile. When this switch is used, a source outside of all Project
9991 Files may be compiled. The ALI file and the object file will be put in the
9992 object directory of the main Project. The compilation switches used will only
9993 be those specified on the command line. Even when
9994 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9995 command line need to be sources of a project file.
9997 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9998 Indicate that external variable @var{name} has the value @var{value}.
9999 The Project Manager will use this value for occurrences of
10000 @code{external(name)} when parsing the project file.
10001 @xref{Switches Related to Project Files}.
10004 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
10005 No main subprogram. Bind and link the program even if the unit name
10006 given on the command line is a package name. The resulting executable
10007 will execute the elaboration routines of the package and its closure,
10008 then the finalization routines.
10013 @item @command{gcc} @asis{switches}
10015 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
10016 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
10019 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
10020 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
10021 automatically treated as a compiler switch, and passed on to all
10022 compilations that are carried out.
10027 Source and library search path switches:
10031 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
10032 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
10033 When looking for source files also look in directory @var{dir}.
10034 The order in which source files search is undertaken is
10035 described in @ref{Search Paths and the Run-Time Library (RTL)}.
10037 @item ^-aL^/SKIP_MISSING=^@var{dir}
10038 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
10039 Consider @var{dir} as being an externally provided Ada library.
10040 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
10041 files have been located in directory @var{dir}. This allows you to have
10042 missing bodies for the units in @var{dir} and to ignore out of date bodies
10043 for the same units. You still need to specify
10044 the location of the specs for these units by using the switches
10045 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
10046 or @option{^-I^/SEARCH=^@var{dir}}.
10047 Note: this switch is provided for compatibility with previous versions
10048 of @command{gnatmake}. The easier method of causing standard libraries
10049 to be excluded from consideration is to write-protect the corresponding
10052 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
10053 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
10054 When searching for library and object files, look in directory
10055 @var{dir}. The order in which library files are searched is described in
10056 @ref{Search Paths for gnatbind}.
10058 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
10059 @cindex Search paths, for @command{gnatmake}
10060 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
10061 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
10062 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10064 @item ^-I^/SEARCH=^@var{dir}
10065 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
10066 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
10067 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10069 @item ^-I-^/NOCURRENT_DIRECTORY^
10070 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
10071 @cindex Source files, suppressing search
10072 Do not look for source files in the directory containing the source
10073 file named in the command line.
10074 Do not look for ALI or object files in the directory
10075 where @command{gnatmake} was invoked.
10077 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
10078 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
10079 @cindex Linker libraries
10080 Add directory @var{dir} to the list of directories in which the linker
10081 will search for libraries. This is equivalent to
10082 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
10084 Furthermore, under Windows, the sources pointed to by the libraries path
10085 set in the registry are not searched for.
10089 @cindex @option{-nostdinc} (@command{gnatmake})
10090 Do not look for source files in the system default directory.
10093 @cindex @option{-nostdlib} (@command{gnatmake})
10094 Do not look for library files in the system default directory.
10096 @item --RTS=@var{rts-path}
10097 @cindex @option{--RTS} (@command{gnatmake})
10098 Specifies the default location of the runtime library. GNAT looks for the
10100 in the following directories, and stops as soon as a valid runtime is found
10101 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
10102 @file{ada_object_path} present):
10105 @item <current directory>/$rts_path
10107 @item <default-search-dir>/$rts_path
10109 @item <default-search-dir>/rts-$rts_path
10113 The selected path is handled like a normal RTS path.
10117 @node Mode Switches for gnatmake
10118 @section Mode Switches for @command{gnatmake}
10121 The mode switches (referred to as @code{mode_switches}) allow the
10122 inclusion of switches that are to be passed to the compiler itself, the
10123 binder or the linker. The effect of a mode switch is to cause all
10124 subsequent switches up to the end of the switch list, or up to the next
10125 mode switch, to be interpreted as switches to be passed on to the
10126 designated component of GNAT.
10130 @item -cargs @var{switches}
10131 @cindex @option{-cargs} (@command{gnatmake})
10132 Compiler switches. Here @var{switches} is a list of switches
10133 that are valid switches for @command{gcc}. They will be passed on to
10134 all compile steps performed by @command{gnatmake}.
10136 @item -bargs @var{switches}
10137 @cindex @option{-bargs} (@command{gnatmake})
10138 Binder switches. Here @var{switches} is a list of switches
10139 that are valid switches for @code{gnatbind}. They will be passed on to
10140 all bind steps performed by @command{gnatmake}.
10142 @item -largs @var{switches}
10143 @cindex @option{-largs} (@command{gnatmake})
10144 Linker switches. Here @var{switches} is a list of switches
10145 that are valid switches for @command{gnatlink}. They will be passed on to
10146 all link steps performed by @command{gnatmake}.
10148 @item -margs @var{switches}
10149 @cindex @option{-margs} (@command{gnatmake})
10150 Make switches. The switches are directly interpreted by @command{gnatmake},
10151 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10152 or @option{-largs}.
10155 @node Notes on the Command Line
10156 @section Notes on the Command Line
10159 This section contains some additional useful notes on the operation
10160 of the @command{gnatmake} command.
10164 @cindex Recompilation, by @command{gnatmake}
10165 If @command{gnatmake} finds no ALI files, it recompiles the main program
10166 and all other units required by the main program.
10167 This means that @command{gnatmake}
10168 can be used for the initial compile, as well as during subsequent steps of
10169 the development cycle.
10172 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10173 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10174 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10178 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10179 is used to specify both source and
10180 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10181 instead if you just want to specify
10182 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10183 if you want to specify library paths
10187 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10188 This may conveniently be used to exclude standard libraries from
10189 consideration and in particular it means that the use of the
10190 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10191 unless @option{^-a^/ALL_FILES^} is also specified.
10194 @command{gnatmake} has been designed to make the use of Ada libraries
10195 particularly convenient. Assume you have an Ada library organized
10196 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10197 of your Ada compilation units,
10198 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10199 specs of these units, but no bodies. Then to compile a unit
10200 stored in @code{main.adb}, which uses this Ada library you would just type
10204 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10207 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10208 /SKIP_MISSING=@i{[OBJ_DIR]} main
10213 Using @command{gnatmake} along with the
10214 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10215 switch provides a mechanism for avoiding unnecessary recompilations. Using
10217 you can update the comments/format of your
10218 source files without having to recompile everything. Note, however, that
10219 adding or deleting lines in a source files may render its debugging
10220 info obsolete. If the file in question is a spec, the impact is rather
10221 limited, as that debugging info will only be useful during the
10222 elaboration phase of your program. For bodies the impact can be more
10223 significant. In all events, your debugger will warn you if a source file
10224 is more recent than the corresponding object, and alert you to the fact
10225 that the debugging information may be out of date.
10228 @node How gnatmake Works
10229 @section How @command{gnatmake} Works
10232 Generally @command{gnatmake} automatically performs all necessary
10233 recompilations and you don't need to worry about how it works. However,
10234 it may be useful to have some basic understanding of the @command{gnatmake}
10235 approach and in particular to understand how it uses the results of
10236 previous compilations without incorrectly depending on them.
10238 First a definition: an object file is considered @dfn{up to date} if the
10239 corresponding ALI file exists and if all the source files listed in the
10240 dependency section of this ALI file have time stamps matching those in
10241 the ALI file. This means that neither the source file itself nor any
10242 files that it depends on have been modified, and hence there is no need
10243 to recompile this file.
10245 @command{gnatmake} works by first checking if the specified main unit is up
10246 to date. If so, no compilations are required for the main unit. If not,
10247 @command{gnatmake} compiles the main program to build a new ALI file that
10248 reflects the latest sources. Then the ALI file of the main unit is
10249 examined to find all the source files on which the main program depends,
10250 and @command{gnatmake} recursively applies the above procedure on all these
10253 This process ensures that @command{gnatmake} only trusts the dependencies
10254 in an existing ALI file if they are known to be correct. Otherwise it
10255 always recompiles to determine a new, guaranteed accurate set of
10256 dependencies. As a result the program is compiled ``upside down'' from what may
10257 be more familiar as the required order of compilation in some other Ada
10258 systems. In particular, clients are compiled before the units on which
10259 they depend. The ability of GNAT to compile in any order is critical in
10260 allowing an order of compilation to be chosen that guarantees that
10261 @command{gnatmake} will recompute a correct set of new dependencies if
10264 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10265 imported by several of the executables, it will be recompiled at most once.
10267 Note: when using non-standard naming conventions
10268 (@pxref{Using Other File Names}), changing through a configuration pragmas
10269 file the version of a source and invoking @command{gnatmake} to recompile may
10270 have no effect, if the previous version of the source is still accessible
10271 by @command{gnatmake}. It may be necessary to use the switch
10272 ^-f^/FORCE_COMPILE^.
10274 @node Examples of gnatmake Usage
10275 @section Examples of @command{gnatmake} Usage
10278 @item gnatmake hello.adb
10279 Compile all files necessary to bind and link the main program
10280 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10281 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10283 @item gnatmake main1 main2 main3
10284 Compile all files necessary to bind and link the main programs
10285 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10286 (containing unit @code{Main2}) and @file{main3.adb}
10287 (containing unit @code{Main3}) and bind and link the resulting object files
10288 to generate three executable files @file{^main1^MAIN1.EXE^},
10289 @file{^main2^MAIN2.EXE^}
10290 and @file{^main3^MAIN3.EXE^}.
10293 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10297 @item gnatmake Main_Unit /QUIET
10298 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10299 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10301 Compile all files necessary to bind and link the main program unit
10302 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10303 be done with optimization level 2 and the order of elaboration will be
10304 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10305 displaying commands it is executing.
10308 @c *************************
10309 @node Improving Performance
10310 @chapter Improving Performance
10311 @cindex Improving performance
10314 This chapter presents several topics related to program performance.
10315 It first describes some of the tradeoffs that need to be considered
10316 and some of the techniques for making your program run faster.
10317 It then documents the @command{gnatelim} tool and unused subprogram/data
10318 elimination feature, which can reduce the size of program executables.
10322 * Performance Considerations::
10323 * Text_IO Suggestions::
10324 * Reducing Size of Ada Executables with gnatelim::
10325 * Reducing Size of Executables with unused subprogram/data elimination::
10329 @c *****************************
10330 @node Performance Considerations
10331 @section Performance Considerations
10334 The GNAT system provides a number of options that allow a trade-off
10339 performance of the generated code
10342 speed of compilation
10345 minimization of dependences and recompilation
10348 the degree of run-time checking.
10352 The defaults (if no options are selected) aim at improving the speed
10353 of compilation and minimizing dependences, at the expense of performance
10354 of the generated code:
10361 no inlining of subprogram calls
10364 all run-time checks enabled except overflow and elaboration checks
10368 These options are suitable for most program development purposes. This
10369 chapter describes how you can modify these choices, and also provides
10370 some guidelines on debugging optimized code.
10373 * Controlling Run-Time Checks::
10374 * Use of Restrictions::
10375 * Optimization Levels::
10376 * Debugging Optimized Code::
10377 * Inlining of Subprograms::
10378 * Vectorization of loops::
10379 * Other Optimization Switches::
10380 * Optimization and Strict Aliasing::
10383 * Coverage Analysis::
10387 @node Controlling Run-Time Checks
10388 @subsection Controlling Run-Time Checks
10391 By default, GNAT generates all run-time checks, except integer overflow
10392 checks, stack overflow checks, and checks for access before elaboration on
10393 subprogram calls. The latter are not required in default mode, because all
10394 necessary checking is done at compile time.
10395 @cindex @option{-gnatp} (@command{gcc})
10396 @cindex @option{-gnato} (@command{gcc})
10397 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10398 be modified. @xref{Run-Time Checks}.
10400 Our experience is that the default is suitable for most development
10403 We treat integer overflow specially because these
10404 are quite expensive and in our experience are not as important as other
10405 run-time checks in the development process. Note that division by zero
10406 is not considered an overflow check, and divide by zero checks are
10407 generated where required by default.
10409 Elaboration checks are off by default, and also not needed by default, since
10410 GNAT uses a static elaboration analysis approach that avoids the need for
10411 run-time checking. This manual contains a full chapter discussing the issue
10412 of elaboration checks, and if the default is not satisfactory for your use,
10413 you should read this chapter.
10415 For validity checks, the minimal checks required by the Ada Reference
10416 Manual (for case statements and assignments to array elements) are on
10417 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10418 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10419 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10420 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10421 are also suppressed entirely if @option{-gnatp} is used.
10423 @cindex Overflow checks
10424 @cindex Checks, overflow
10427 @cindex pragma Suppress
10428 @cindex pragma Unsuppress
10429 Note that the setting of the switches controls the default setting of
10430 the checks. They may be modified using either @code{pragma Suppress} (to
10431 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10432 checks) in the program source.
10434 @node Use of Restrictions
10435 @subsection Use of Restrictions
10438 The use of pragma Restrictions allows you to control which features are
10439 permitted in your program. Apart from the obvious point that if you avoid
10440 relatively expensive features like finalization (enforceable by the use
10441 of pragma Restrictions (No_Finalization), the use of this pragma does not
10442 affect the generated code in most cases.
10444 One notable exception to this rule is that the possibility of task abort
10445 results in some distributed overhead, particularly if finalization or
10446 exception handlers are used. The reason is that certain sections of code
10447 have to be marked as non-abortable.
10449 If you use neither the @code{abort} statement, nor asynchronous transfer
10450 of control (@code{select @dots{} then abort}), then this distributed overhead
10451 is removed, which may have a general positive effect in improving
10452 overall performance. Especially code involving frequent use of tasking
10453 constructs and controlled types will show much improved performance.
10454 The relevant restrictions pragmas are
10456 @smallexample @c ada
10457 pragma Restrictions (No_Abort_Statements);
10458 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10462 It is recommended that these restriction pragmas be used if possible. Note
10463 that this also means that you can write code without worrying about the
10464 possibility of an immediate abort at any point.
10466 @node Optimization Levels
10467 @subsection Optimization Levels
10468 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10471 Without any optimization ^option,^qualifier,^
10472 the compiler's goal is to reduce the cost of
10473 compilation and to make debugging produce the expected results.
10474 Statements are independent: if you stop the program with a breakpoint between
10475 statements, you can then assign a new value to any variable or change
10476 the program counter to any other statement in the subprogram and get exactly
10477 the results you would expect from the source code.
10479 Turning on optimization makes the compiler attempt to improve the
10480 performance and/or code size at the expense of compilation time and
10481 possibly the ability to debug the program.
10483 If you use multiple
10484 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10485 the last such option is the one that is effective.
10488 The default is optimization off. This results in the fastest compile
10489 times, but GNAT makes absolutely no attempt to optimize, and the
10490 generated programs are considerably larger and slower than when
10491 optimization is enabled. You can use the
10493 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10494 @option{-O2}, @option{-O3}, and @option{-Os})
10497 @code{OPTIMIZE} qualifier
10499 to @command{gcc} to control the optimization level:
10502 @item ^-O0^/OPTIMIZE=NONE^
10503 No optimization (the default);
10504 generates unoptimized code but has
10505 the fastest compilation time.
10507 Note that many other compilers do fairly extensive optimization
10508 even if ``no optimization'' is specified. With gcc, it is
10509 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10510 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10511 really does mean no optimization at all. This difference between
10512 gcc and other compilers should be kept in mind when doing
10513 performance comparisons.
10515 @item ^-O1^/OPTIMIZE=SOME^
10516 Moderate optimization;
10517 optimizes reasonably well but does not
10518 degrade compilation time significantly.
10520 @item ^-O2^/OPTIMIZE=ALL^
10522 @itemx /OPTIMIZE=DEVELOPMENT
10525 generates highly optimized code and has
10526 the slowest compilation time.
10528 @item ^-O3^/OPTIMIZE=INLINING^
10529 Full optimization as in @option{-O2};
10530 also uses more aggressive automatic inlining of subprograms within a unit
10531 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10533 @item ^-Os^/OPTIMIZE=SPACE^
10534 Optimize space usage (code and data) of resulting program.
10538 Higher optimization levels perform more global transformations on the
10539 program and apply more expensive analysis algorithms in order to generate
10540 faster and more compact code. The price in compilation time, and the
10541 resulting improvement in execution time,
10542 both depend on the particular application and the hardware environment.
10543 You should experiment to find the best level for your application.
10545 Since the precise set of optimizations done at each level will vary from
10546 release to release (and sometime from target to target), it is best to think
10547 of the optimization settings in general terms.
10548 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10549 the GNU Compiler Collection (GCC)}, for details about
10550 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10551 individually enable or disable specific optimizations.
10553 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10554 been tested extensively at all optimization levels. There are some bugs
10555 which appear only with optimization turned on, but there have also been
10556 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10557 level of optimization does not improve the reliability of the code
10558 generator, which in practice is highly reliable at all optimization
10561 Note regarding the use of @option{-O3}: The use of this optimization level
10562 is generally discouraged with GNAT, since it often results in larger
10563 executables which may run more slowly. See further discussion of this point
10564 in @ref{Inlining of Subprograms}.
10566 @node Debugging Optimized Code
10567 @subsection Debugging Optimized Code
10568 @cindex Debugging optimized code
10569 @cindex Optimization and debugging
10572 Although it is possible to do a reasonable amount of debugging at
10574 nonzero optimization levels,
10575 the higher the level the more likely that
10578 @option{/OPTIMIZE} settings other than @code{NONE},
10579 such settings will make it more likely that
10581 source-level constructs will have been eliminated by optimization.
10582 For example, if a loop is strength-reduced, the loop
10583 control variable may be completely eliminated and thus cannot be
10584 displayed in the debugger.
10585 This can only happen at @option{-O2} or @option{-O3}.
10586 Explicit temporary variables that you code might be eliminated at
10587 ^level^setting^ @option{-O1} or higher.
10589 The use of the @option{^-g^/DEBUG^} switch,
10590 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10591 which is needed for source-level debugging,
10592 affects the size of the program executable on disk,
10593 and indeed the debugging information can be quite large.
10594 However, it has no effect on the generated code (and thus does not
10595 degrade performance)
10597 Since the compiler generates debugging tables for a compilation unit before
10598 it performs optimizations, the optimizing transformations may invalidate some
10599 of the debugging data. You therefore need to anticipate certain
10600 anomalous situations that may arise while debugging optimized code.
10601 These are the most common cases:
10605 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10607 the PC bouncing back and forth in the code. This may result from any of
10608 the following optimizations:
10612 @i{Common subexpression elimination:} using a single instance of code for a
10613 quantity that the source computes several times. As a result you
10614 may not be able to stop on what looks like a statement.
10617 @i{Invariant code motion:} moving an expression that does not change within a
10618 loop, to the beginning of the loop.
10621 @i{Instruction scheduling:} moving instructions so as to
10622 overlap loads and stores (typically) with other code, or in
10623 general to move computations of values closer to their uses. Often
10624 this causes you to pass an assignment statement without the assignment
10625 happening and then later bounce back to the statement when the
10626 value is actually needed. Placing a breakpoint on a line of code
10627 and then stepping over it may, therefore, not always cause all the
10628 expected side-effects.
10632 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10633 two identical pieces of code are merged and the program counter suddenly
10634 jumps to a statement that is not supposed to be executed, simply because
10635 it (and the code following) translates to the same thing as the code
10636 that @emph{was} supposed to be executed. This effect is typically seen in
10637 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10638 a @code{break} in a C @code{^switch^switch^} statement.
10641 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10642 There are various reasons for this effect:
10646 In a subprogram prologue, a parameter may not yet have been moved to its
10650 A variable may be dead, and its register re-used. This is
10651 probably the most common cause.
10654 As mentioned above, the assignment of a value to a variable may
10658 A variable may be eliminated entirely by value propagation or
10659 other means. In this case, GCC may incorrectly generate debugging
10660 information for the variable
10664 In general, when an unexpected value appears for a local variable or parameter
10665 you should first ascertain if that value was actually computed by
10666 your program, as opposed to being incorrectly reported by the debugger.
10668 array elements in an object designated by an access value
10669 are generally less of a problem, once you have ascertained that the access
10671 Typically, this means checking variables in the preceding code and in the
10672 calling subprogram to verify that the value observed is explainable from other
10673 values (one must apply the procedure recursively to those
10674 other values); or re-running the code and stopping a little earlier
10675 (perhaps before the call) and stepping to better see how the variable obtained
10676 the value in question; or continuing to step @emph{from} the point of the
10677 strange value to see if code motion had simply moved the variable's
10682 In light of such anomalies, a recommended technique is to use @option{-O0}
10683 early in the software development cycle, when extensive debugging capabilities
10684 are most needed, and then move to @option{-O1} and later @option{-O2} as
10685 the debugger becomes less critical.
10686 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10687 a release management issue.
10689 Note that if you use @option{-g} you can then use the @command{strip} program
10690 on the resulting executable,
10691 which removes both debugging information and global symbols.
10694 @node Inlining of Subprograms
10695 @subsection Inlining of Subprograms
10698 A call to a subprogram in the current unit is inlined if all the
10699 following conditions are met:
10703 The optimization level is at least @option{-O1}.
10706 The called subprogram is suitable for inlining: It must be small enough
10707 and not contain something that @command{gcc} cannot support in inlined
10711 @cindex pragma Inline
10713 Any one of the following applies: @code{pragma Inline} is applied to the
10714 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10715 subprogram is local to the unit and called once from within it; the
10716 subprogram is small and optimization level @option{-O2} is specified;
10717 optimization level @option{-O3} is specified.
10721 Calls to subprograms in @code{with}'ed units are normally not inlined.
10722 To achieve actual inlining (that is, replacement of the call by the code
10723 in the body of the subprogram), the following conditions must all be true:
10727 The optimization level is at least @option{-O1}.
10730 The called subprogram is suitable for inlining: It must be small enough
10731 and not contain something that @command{gcc} cannot support in inlined
10735 The call appears in a body (not in a package spec).
10738 There is a @code{pragma Inline} for the subprogram.
10741 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10744 Even if all these conditions are met, it may not be possible for
10745 the compiler to inline the call, due to the length of the body,
10746 or features in the body that make it impossible for the compiler
10747 to do the inlining.
10749 Note that specifying the @option{-gnatn} switch causes additional
10750 compilation dependencies. Consider the following:
10752 @smallexample @c ada
10772 With the default behavior (no @option{-gnatn} switch specified), the
10773 compilation of the @code{Main} procedure depends only on its own source,
10774 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10775 means that editing the body of @code{R} does not require recompiling
10778 On the other hand, the call @code{R.Q} is not inlined under these
10779 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10780 is compiled, the call will be inlined if the body of @code{Q} is small
10781 enough, but now @code{Main} depends on the body of @code{R} in
10782 @file{r.adb} as well as on the spec. This means that if this body is edited,
10783 the main program must be recompiled. Note that this extra dependency
10784 occurs whether or not the call is in fact inlined by @command{gcc}.
10786 The use of front end inlining with @option{-gnatN} generates similar
10787 additional dependencies.
10789 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10790 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10791 can be used to prevent
10792 all inlining. This switch overrides all other conditions and ensures
10793 that no inlining occurs. The extra dependences resulting from
10794 @option{-gnatn} will still be active, even if
10795 this switch is used to suppress the resulting inlining actions.
10797 @cindex @option{-fno-inline-functions} (@command{gcc})
10798 Note: The @option{-fno-inline-functions} switch can be used to prevent
10799 automatic inlining of subprograms if @option{-O3} is used.
10801 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10802 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10803 automatic inlining of small subprograms if @option{-O2} is used.
10805 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10806 Note: The @option{-fno-inline-functions-called-once} switch
10807 can be used to prevent inlining of subprograms local to the unit
10808 and called once from within it if @option{-O1} is used.
10810 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10811 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10812 specified in lieu of it, @option{-gnatn} being translated into one of them
10813 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10814 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10815 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10816 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10817 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
10818 effect of inlining subprograms you did not think should be inlined. We have
10819 found that the use of @option{-O3} may slow down the compilation and increase
10820 the code size by performing excessive inlining, leading to increased
10821 instruction cache pressure from the increased code size and thus minor
10822 performance improvements. So the bottom line here is that you should not
10823 automatically assume that @option{-O3} is better than @option{-O2}, and
10824 indeed you should use @option{-O3} only if tests show that it actually
10825 improves performance for your program.
10827 @node Vectorization of loops
10828 @subsection Vectorization of loops
10829 @cindex Optimization Switches
10831 You can take advantage of the auto-vectorizer present in the @command{gcc}
10832 back end to vectorize loops with GNAT. The corresponding command line switch
10833 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10834 and other aggressive optimizations helpful for vectorization also are enabled
10835 by default at this level, using @option{-O3} directly is recommended.
10837 You also need to make sure that the target architecture features a supported
10838 SIMD instruction set. For example, for the x86 architecture, you should at
10839 least specify @option{-msse2} to get significant vectorization (but you don't
10840 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10841 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10843 The preferred loop form for vectorization is the @code{for} iteration scheme.
10844 Loops with a @code{while} iteration scheme can also be vectorized if they are
10845 very simple, but the vectorizer will quickly give up otherwise. With either
10846 iteration scheme, the flow of control must be straight, in particular no
10847 @code{exit} statement may appear in the loop body. The loop may however
10848 contain a single nested loop, if it can be vectorized when considered alone:
10850 @smallexample @c ada
10852 A : array (1..4, 1..4) of Long_Float;
10853 S : array (1..4) of Long_Float;
10857 for I in A'Range(1) loop
10858 for J in A'Range(2) loop
10859 S (I) := S (I) + A (I, J);
10866 The vectorizable operations depend on the targeted SIMD instruction set, but
10867 the adding and some of the multiplying operators are generally supported, as
10868 well as the logical operators for modular types. Note that, in the former
10869 case, enabling overflow checks, for example with @option{-gnato}, totally
10870 disables vectorization. The other checks are not supposed to have the same
10871 definitive effect, although compiling with @option{-gnatp} might well reveal
10872 cases where some checks do thwart vectorization.
10874 Type conversions may also prevent vectorization if they involve semantics that
10875 are not directly supported by the code generator or the SIMD instruction set.
10876 A typical example is direct conversion from floating-point to integer types.
10877 The solution in this case is to use the following idiom:
10879 @smallexample @c ada
10880 Integer (S'Truncation (F))
10884 if @code{S} is the subtype of floating-point object @code{F}.
10886 In most cases, the vectorizable loops are loops that iterate over arrays.
10887 All kinds of array types are supported, i.e. constrained array types with
10890 @smallexample @c ada
10891 type Array_Type is array (1 .. 4) of Long_Float;
10895 constrained array types with dynamic bounds:
10897 @smallexample @c ada
10898 type Array_Type is array (1 .. Q.N) of Long_Float;
10900 type Array_Type is array (Q.K .. 4) of Long_Float;
10902 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10906 or unconstrained array types:
10908 @smallexample @c ada
10909 type Array_Type is array (Positive range <>) of Long_Float;
10913 The quality of the generated code decreases when the dynamic aspect of the
10914 array type increases, the worst code being generated for unconstrained array
10915 types. This is so because, the less information the compiler has about the
10916 bounds of the array, the more fallback code it needs to generate in order to
10917 fix things up at run time.
10919 You can obtain information about the vectorization performed by the compiler
10920 by specifying @option{-ftree-vectorizer-verbose=N}. For more details of
10921 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10922 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10924 @node Other Optimization Switches
10925 @subsection Other Optimization Switches
10926 @cindex Optimization Switches
10928 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10929 @command{gcc} optimization switches are potentially usable. These switches
10930 have not been extensively tested with GNAT but can generally be expected
10931 to work. Examples of switches in this category are @option{-funroll-loops}
10932 and the various target-specific @option{-m} options (in particular, it has
10933 been observed that @option{-march=xxx} can significantly improve performance
10934 on appropriate machines). For full details of these switches, see
10935 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10936 the GNU Compiler Collection (GCC)}.
10938 @node Optimization and Strict Aliasing
10939 @subsection Optimization and Strict Aliasing
10941 @cindex Strict Aliasing
10942 @cindex No_Strict_Aliasing
10945 The strong typing capabilities of Ada allow an optimizer to generate
10946 efficient code in situations where other languages would be forced to
10947 make worst case assumptions preventing such optimizations. Consider
10948 the following example:
10950 @smallexample @c ada
10953 type Int1 is new Integer;
10954 type Int2 is new Integer;
10955 type Int1A is access Int1;
10956 type Int2A is access Int2;
10963 for J in Data'Range loop
10964 if Data (J) = Int1V.all then
10965 Int2V.all := Int2V.all + 1;
10974 In this example, since the variable @code{Int1V} can only access objects
10975 of type @code{Int1}, and @code{Int2V} can only access objects of type
10976 @code{Int2}, there is no possibility that the assignment to
10977 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10978 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10979 for all iterations of the loop and avoid the extra memory reference
10980 required to dereference it each time through the loop.
10982 This kind of optimization, called strict aliasing analysis, is
10983 triggered by specifying an optimization level of @option{-O2} or
10984 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10985 when access values are involved.
10987 However, although this optimization is always correct in terms of
10988 the formal semantics of the Ada Reference Manual, difficulties can
10989 arise if features like @code{Unchecked_Conversion} are used to break
10990 the typing system. Consider the following complete program example:
10992 @smallexample @c ada
10995 type int1 is new integer;
10996 type int2 is new integer;
10997 type a1 is access int1;
10998 type a2 is access int2;
11003 function to_a2 (Input : a1) return a2;
11006 with Unchecked_Conversion;
11008 function to_a2 (Input : a1) return a2 is
11010 new Unchecked_Conversion (a1, a2);
11012 return to_a2u (Input);
11018 with Text_IO; use Text_IO;
11020 v1 : a1 := new int1;
11021 v2 : a2 := to_a2 (v1);
11025 put_line (int1'image (v1.all));
11031 This program prints out 0 in @option{-O0} or @option{-O1}
11032 mode, but it prints out 1 in @option{-O2} mode. That's
11033 because in strict aliasing mode, the compiler can and
11034 does assume that the assignment to @code{v2.all} could not
11035 affect the value of @code{v1.all}, since different types
11038 This behavior is not a case of non-conformance with the standard, since
11039 the Ada RM specifies that an unchecked conversion where the resulting
11040 bit pattern is not a correct value of the target type can result in an
11041 abnormal value and attempting to reference an abnormal value makes the
11042 execution of a program erroneous. That's the case here since the result
11043 does not point to an object of type @code{int2}. This means that the
11044 effect is entirely unpredictable.
11046 However, although that explanation may satisfy a language
11047 lawyer, in practice an applications programmer expects an
11048 unchecked conversion involving pointers to create true
11049 aliases and the behavior of printing 1 seems plain wrong.
11050 In this case, the strict aliasing optimization is unwelcome.
11052 Indeed the compiler recognizes this possibility, and the
11053 unchecked conversion generates a warning:
11056 p2.adb:5:07: warning: possible aliasing problem with type "a2"
11057 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
11058 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
11062 Unfortunately the problem is recognized when compiling the body of
11063 package @code{p2}, but the actual "bad" code is generated while
11064 compiling the body of @code{m} and this latter compilation does not see
11065 the suspicious @code{Unchecked_Conversion}.
11067 As implied by the warning message, there are approaches you can use to
11068 avoid the unwanted strict aliasing optimization in a case like this.
11070 One possibility is to simply avoid the use of @option{-O2}, but
11071 that is a bit drastic, since it throws away a number of useful
11072 optimizations that do not involve strict aliasing assumptions.
11074 A less drastic approach is to compile the program using the
11075 option @option{-fno-strict-aliasing}. Actually it is only the
11076 unit containing the dereferencing of the suspicious pointer
11077 that needs to be compiled. So in this case, if we compile
11078 unit @code{m} with this switch, then we get the expected
11079 value of zero printed. Analyzing which units might need
11080 the switch can be painful, so a more reasonable approach
11081 is to compile the entire program with options @option{-O2}
11082 and @option{-fno-strict-aliasing}. If the performance is
11083 satisfactory with this combination of options, then the
11084 advantage is that the entire issue of possible "wrong"
11085 optimization due to strict aliasing is avoided.
11087 To avoid the use of compiler switches, the configuration
11088 pragma @code{No_Strict_Aliasing} with no parameters may be
11089 used to specify that for all access types, the strict
11090 aliasing optimization should be suppressed.
11092 However, these approaches are still overkill, in that they causes
11093 all manipulations of all access values to be deoptimized. A more
11094 refined approach is to concentrate attention on the specific
11095 access type identified as problematic.
11097 First, if a careful analysis of uses of the pointer shows
11098 that there are no possible problematic references, then
11099 the warning can be suppressed by bracketing the
11100 instantiation of @code{Unchecked_Conversion} to turn
11103 @smallexample @c ada
11104 pragma Warnings (Off);
11106 new Unchecked_Conversion (a1, a2);
11107 pragma Warnings (On);
11111 Of course that approach is not appropriate for this particular
11112 example, since indeed there is a problematic reference. In this
11113 case we can take one of two other approaches.
11115 The first possibility is to move the instantiation of unchecked
11116 conversion to the unit in which the type is declared. In
11117 this example, we would move the instantiation of
11118 @code{Unchecked_Conversion} from the body of package
11119 @code{p2} to the spec of package @code{p1}. Now the
11120 warning disappears. That's because any use of the
11121 access type knows there is a suspicious unchecked
11122 conversion, and the strict aliasing optimization
11123 is automatically suppressed for the type.
11125 If it is not practical to move the unchecked conversion to the same unit
11126 in which the destination access type is declared (perhaps because the
11127 source type is not visible in that unit), you may use pragma
11128 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11129 same declarative sequence as the declaration of the access type:
11131 @smallexample @c ada
11132 type a2 is access int2;
11133 pragma No_Strict_Aliasing (a2);
11137 Here again, the compiler now knows that the strict aliasing optimization
11138 should be suppressed for any reference to type @code{a2} and the
11139 expected behavior is obtained.
11141 Finally, note that although the compiler can generate warnings for
11142 simple cases of unchecked conversions, there are tricker and more
11143 indirect ways of creating type incorrect aliases which the compiler
11144 cannot detect. Examples are the use of address overlays and unchecked
11145 conversions involving composite types containing access types as
11146 components. In such cases, no warnings are generated, but there can
11147 still be aliasing problems. One safe coding practice is to forbid the
11148 use of address clauses for type overlaying, and to allow unchecked
11149 conversion only for primitive types. This is not really a significant
11150 restriction since any possible desired effect can be achieved by
11151 unchecked conversion of access values.
11153 The aliasing analysis done in strict aliasing mode can certainly
11154 have significant benefits. We have seen cases of large scale
11155 application code where the time is increased by up to 5% by turning
11156 this optimization off. If you have code that includes significant
11157 usage of unchecked conversion, you might want to just stick with
11158 @option{-O1} and avoid the entire issue. If you get adequate
11159 performance at this level of optimization level, that's probably
11160 the safest approach. If tests show that you really need higher
11161 levels of optimization, then you can experiment with @option{-O2}
11162 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11163 has on size and speed of the code. If you really need to use
11164 @option{-O2} with strict aliasing in effect, then you should
11165 review any uses of unchecked conversion of access types,
11166 particularly if you are getting the warnings described above.
11169 @node Coverage Analysis
11170 @subsection Coverage Analysis
11173 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11174 the user to determine the distribution of execution time across a program,
11175 @pxref{Profiling} for details of usage.
11179 @node Text_IO Suggestions
11180 @section @code{Text_IO} Suggestions
11181 @cindex @code{Text_IO} and performance
11184 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11185 the requirement of maintaining page and line counts. If performance
11186 is critical, a recommendation is to use @code{Stream_IO} instead of
11187 @code{Text_IO} for volume output, since this package has less overhead.
11189 If @code{Text_IO} must be used, note that by default output to the standard
11190 output and standard error files is unbuffered (this provides better
11191 behavior when output statements are used for debugging, or if the
11192 progress of a program is observed by tracking the output, e.g. by
11193 using the Unix @command{tail -f} command to watch redirected output.
11195 If you are generating large volumes of output with @code{Text_IO} and
11196 performance is an important factor, use a designated file instead
11197 of the standard output file, or change the standard output file to
11198 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11202 @node Reducing Size of Ada Executables with gnatelim
11203 @section Reducing Size of Ada Executables with @code{gnatelim}
11207 This section describes @command{gnatelim}, a tool which detects unused
11208 subprograms and helps the compiler to create a smaller executable for your
11213 * Running gnatelim::
11214 * Processing Precompiled Libraries::
11215 * Correcting the List of Eliminate Pragmas::
11216 * Making Your Executables Smaller::
11217 * Summary of the gnatelim Usage Cycle::
11220 @node About gnatelim
11221 @subsection About @code{gnatelim}
11224 When a program shares a set of Ada
11225 packages with other programs, it may happen that this program uses
11226 only a fraction of the subprograms defined in these packages. The code
11227 created for these unused subprograms increases the size of the executable.
11229 @code{gnatelim} tracks unused subprograms in an Ada program and
11230 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11231 subprograms that are declared but never called. By placing the list of
11232 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11233 recompiling your program, you may decrease the size of its executable,
11234 because the compiler will not generate the code for 'eliminated' subprograms.
11235 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11236 information about this pragma.
11238 @code{gnatelim} needs as its input data the name of the main subprogram.
11240 If a set of source files is specified as @code{gnatelim} arguments, it
11241 treats these files as a complete set of sources making up a program to
11242 analyse, and analyses only these sources.
11244 After a full successful build of the main subprogram @code{gnatelim} can be
11245 called without specifying sources to analyse, in this case it computes
11246 the source closure of the main unit from the @file{ALI} files.
11248 The following command will create the set of @file{ALI} files needed for
11252 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11255 Note that @code{gnatelim} does not need object files.
11257 @node Running gnatelim
11258 @subsection Running @code{gnatelim}
11261 @code{gnatelim} has the following command-line interface:
11264 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11268 @var{main_unit_name} should be a name of a source file that contains the main
11269 subprogram of a program (partition).
11271 Each @var{filename} is the name (including the extension) of a source
11272 file to process. ``Wildcards'' are allowed, and
11273 the file name may contain path information.
11275 @samp{@var{gcc_switches}} is a list of switches for
11276 @command{gcc}. They will be passed on to all compiler invocations made by
11277 @command{gnatelim} to generate the ASIS trees. Here you can provide
11278 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11279 use the @option{-gnatec} switch to set the configuration file,
11280 use the @option{-gnat05} switch if sources should be compiled in
11283 @code{gnatelim} has the following switches:
11287 @item ^-files^/FILES^=@var{filename}
11288 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11289 Take the argument source files from the specified file. This file should be an
11290 ordinary text file containing file names separated by spaces or
11291 line breaks. You can use this switch more than once in the same call to
11292 @command{gnatelim}. You also can combine this switch with
11293 an explicit list of files.
11296 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11297 Duplicate all the output sent to @file{stderr} into a log file. The log file
11298 is named @file{gnatelim.log} and is located in the current directory.
11300 @item ^-log^/LOGFILE^=@var{filename}
11301 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11302 Duplicate all the output sent to @file{stderr} into a specified log file.
11304 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11305 @item ^--no-elim-dispatch^/NO_DISPATCH^
11306 Do not generate pragmas for dispatching operations.
11308 @item ^--ignore^/IGNORE^=@var{filename}
11309 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11310 Do not generate pragmas for subprograms declared in the sources
11311 listed in a specified file
11313 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11314 @item ^-o^/OUTPUT^=@var{report_file}
11315 Put @command{gnatelim} output into a specified file. If this file already exists,
11316 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11320 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11321 Quiet mode: by default @code{gnatelim} outputs to the standard error
11322 stream the number of program units left to be processed. This option turns
11325 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11327 Print out execution time.
11329 @item ^-v^/VERBOSE^
11330 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11331 Verbose mode: @code{gnatelim} version information is printed as Ada
11332 comments to the standard output stream. Also, in addition to the number of
11333 program units left @code{gnatelim} will output the name of the current unit
11336 @item ^-wq^/WARNINGS=QUIET^
11337 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11338 Quiet warning mode - some warnings are suppressed. In particular warnings that
11339 indicate that the analysed set of sources is incomplete to make up a
11340 partition and that some subprogram bodies are missing are not generated.
11344 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11345 driver (see @ref{The GNAT Driver and Project Files}).
11347 @node Processing Precompiled Libraries
11348 @subsection Processing Precompiled Libraries
11351 If some program uses a precompiled Ada library, it can be processed by
11352 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11353 Eliminate pragma for a subprogram if the body of this subprogram has not
11354 been analysed, this is a typical case for subprograms from precompiled
11355 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11356 warnings about missing source files and non-analyzed subprogram bodies
11357 that can be generated when processing precompiled Ada libraries.
11359 @node Correcting the List of Eliminate Pragmas
11360 @subsection Correcting the List of Eliminate Pragmas
11363 In some rare cases @code{gnatelim} may try to eliminate
11364 subprograms that are actually called in the program. In this case, the
11365 compiler will generate an error message of the form:
11368 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11372 You will need to manually remove the wrong @code{Eliminate} pragmas from
11373 the configuration file indicated in the error message. You should recompile
11374 your program from scratch after that, because you need a consistent
11375 configuration file(s) during the entire compilation.
11377 @node Making Your Executables Smaller
11378 @subsection Making Your Executables Smaller
11381 In order to get a smaller executable for your program you now have to
11382 recompile the program completely with the configuration file containing
11383 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11384 @file{gnat.adc} file located in your current directory, just do:
11387 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11391 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11392 recompile everything
11393 with the set of pragmas @code{Eliminate} that you have obtained with
11394 @command{gnatelim}).
11396 Be aware that the set of @code{Eliminate} pragmas is specific to each
11397 program. It is not recommended to merge sets of @code{Eliminate}
11398 pragmas created for different programs in one configuration file.
11400 @node Summary of the gnatelim Usage Cycle
11401 @subsection Summary of the @code{gnatelim} Usage Cycle
11404 Here is a quick summary of the steps to be taken in order to reduce
11405 the size of your executables with @code{gnatelim}. You may use
11406 other GNAT options to control the optimization level,
11407 to produce the debugging information, to set search path, etc.
11411 Create a complete set of @file{ALI} files (if the program has not been
11415 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11419 Generate a list of @code{Eliminate} pragmas in default configuration file
11420 @file{gnat.adc} in the current directory
11423 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11426 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11431 Recompile the application
11434 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11439 @node Reducing Size of Executables with unused subprogram/data elimination
11440 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11441 @findex unused subprogram/data elimination
11444 This section describes how you can eliminate unused subprograms and data from
11445 your executable just by setting options at compilation time.
11448 * About unused subprogram/data elimination::
11449 * Compilation options::
11450 * Example of unused subprogram/data elimination::
11453 @node About unused subprogram/data elimination
11454 @subsection About unused subprogram/data elimination
11457 By default, an executable contains all code and data of its composing objects
11458 (directly linked or coming from statically linked libraries), even data or code
11459 never used by this executable.
11461 This feature will allow you to eliminate such unused code from your
11462 executable, making it smaller (in disk and in memory).
11464 This functionality is available on all Linux platforms except for the IA-64
11465 architecture and on all cross platforms using the ELF binary file format.
11466 In both cases GNU binutils version 2.16 or later are required to enable it.
11468 @node Compilation options
11469 @subsection Compilation options
11472 The operation of eliminating the unused code and data from the final executable
11473 is directly performed by the linker.
11475 In order to do this, it has to work with objects compiled with the
11477 @option{-ffunction-sections} @option{-fdata-sections}.
11478 @cindex @option{-ffunction-sections} (@command{gcc})
11479 @cindex @option{-fdata-sections} (@command{gcc})
11480 These options are usable with C and Ada files.
11481 They will place respectively each
11482 function or data in a separate section in the resulting object file.
11484 Once the objects and static libraries are created with these options, the
11485 linker can perform the dead code elimination. You can do this by setting
11486 the @option{-Wl,--gc-sections} option to gcc command or in the
11487 @option{-largs} section of @command{gnatmake}. This will perform a
11488 garbage collection of code and data never referenced.
11490 If the linker performs a partial link (@option{-r} ld linker option), then you
11491 will need to provide one or several entry point using the
11492 @option{-e} / @option{--entry} ld option.
11494 Note that objects compiled without the @option{-ffunction-sections} and
11495 @option{-fdata-sections} options can still be linked with the executable.
11496 However, no dead code elimination will be performed on those objects (they will
11499 The GNAT static library is now compiled with -ffunction-sections and
11500 -fdata-sections on some platforms. This allows you to eliminate the unused code
11501 and data of the GNAT library from your executable.
11503 @node Example of unused subprogram/data elimination
11504 @subsection Example of unused subprogram/data elimination
11507 Here is a simple example:
11509 @smallexample @c ada
11518 Used_Data : Integer;
11519 Unused_Data : Integer;
11521 procedure Used (Data : Integer);
11522 procedure Unused (Data : Integer);
11525 package body Aux is
11526 procedure Used (Data : Integer) is
11531 procedure Unused (Data : Integer) is
11533 Unused_Data := Data;
11539 @code{Unused} and @code{Unused_Data} are never referenced in this code
11540 excerpt, and hence they may be safely removed from the final executable.
11545 $ nm test | grep used
11546 020015f0 T aux__unused
11547 02005d88 B aux__unused_data
11548 020015cc T aux__used
11549 02005d84 B aux__used_data
11551 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11552 -largs -Wl,--gc-sections
11554 $ nm test | grep used
11555 02005350 T aux__used
11556 0201ffe0 B aux__used_data
11560 It can be observed that the procedure @code{Unused} and the object
11561 @code{Unused_Data} are removed by the linker when using the
11562 appropriate options.
11564 @c ********************************
11565 @node Renaming Files Using gnatchop
11566 @chapter Renaming Files Using @code{gnatchop}
11570 This chapter discusses how to handle files with multiple units by using
11571 the @code{gnatchop} utility. This utility is also useful in renaming
11572 files to meet the standard GNAT default file naming conventions.
11575 * Handling Files with Multiple Units::
11576 * Operating gnatchop in Compilation Mode::
11577 * Command Line for gnatchop::
11578 * Switches for gnatchop::
11579 * Examples of gnatchop Usage::
11582 @node Handling Files with Multiple Units
11583 @section Handling Files with Multiple Units
11586 The basic compilation model of GNAT requires that a file submitted to the
11587 compiler have only one unit and there be a strict correspondence
11588 between the file name and the unit name.
11590 The @code{gnatchop} utility allows both of these rules to be relaxed,
11591 allowing GNAT to process files which contain multiple compilation units
11592 and files with arbitrary file names. @code{gnatchop}
11593 reads the specified file and generates one or more output files,
11594 containing one unit per file. The unit and the file name correspond,
11595 as required by GNAT.
11597 If you want to permanently restructure a set of ``foreign'' files so that
11598 they match the GNAT rules, and do the remaining development using the
11599 GNAT structure, you can simply use @command{gnatchop} once, generate the
11600 new set of files and work with them from that point on.
11602 Alternatively, if you want to keep your files in the ``foreign'' format,
11603 perhaps to maintain compatibility with some other Ada compilation
11604 system, you can set up a procedure where you use @command{gnatchop} each
11605 time you compile, regarding the source files that it writes as temporary
11606 files that you throw away.
11608 Note that if your file containing multiple units starts with a byte order
11609 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11610 will each start with a copy of this BOM, meaning that they can be compiled
11611 automatically in UTF-8 mode without needing to specify an explicit encoding.
11613 @node Operating gnatchop in Compilation Mode
11614 @section Operating gnatchop in Compilation Mode
11617 The basic function of @code{gnatchop} is to take a file with multiple units
11618 and split it into separate files. The boundary between files is reasonably
11619 clear, except for the issue of comments and pragmas. In default mode, the
11620 rule is that any pragmas between units belong to the previous unit, except
11621 that configuration pragmas always belong to the following unit. Any comments
11622 belong to the following unit. These rules
11623 almost always result in the right choice of
11624 the split point without needing to mark it explicitly and most users will
11625 find this default to be what they want. In this default mode it is incorrect to
11626 submit a file containing only configuration pragmas, or one that ends in
11627 configuration pragmas, to @code{gnatchop}.
11629 However, using a special option to activate ``compilation mode'',
11631 can perform another function, which is to provide exactly the semantics
11632 required by the RM for handling of configuration pragmas in a compilation.
11633 In the absence of configuration pragmas (at the main file level), this
11634 option has no effect, but it causes such configuration pragmas to be handled
11635 in a quite different manner.
11637 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11638 only configuration pragmas, then this file is appended to the
11639 @file{gnat.adc} file in the current directory. This behavior provides
11640 the required behavior described in the RM for the actions to be taken
11641 on submitting such a file to the compiler, namely that these pragmas
11642 should apply to all subsequent compilations in the same compilation
11643 environment. Using GNAT, the current directory, possibly containing a
11644 @file{gnat.adc} file is the representation
11645 of a compilation environment. For more information on the
11646 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11648 Second, in compilation mode, if @code{gnatchop}
11649 is given a file that starts with
11650 configuration pragmas, and contains one or more units, then these
11651 configuration pragmas are prepended to each of the chopped files. This
11652 behavior provides the required behavior described in the RM for the
11653 actions to be taken on compiling such a file, namely that the pragmas
11654 apply to all units in the compilation, but not to subsequently compiled
11657 Finally, if configuration pragmas appear between units, they are appended
11658 to the previous unit. This results in the previous unit being illegal,
11659 since the compiler does not accept configuration pragmas that follow
11660 a unit. This provides the required RM behavior that forbids configuration
11661 pragmas other than those preceding the first compilation unit of a
11664 For most purposes, @code{gnatchop} will be used in default mode. The
11665 compilation mode described above is used only if you need exactly
11666 accurate behavior with respect to compilations, and you have files
11667 that contain multiple units and configuration pragmas. In this
11668 circumstance the use of @code{gnatchop} with the compilation mode
11669 switch provides the required behavior, and is for example the mode
11670 in which GNAT processes the ACVC tests.
11672 @node Command Line for gnatchop
11673 @section Command Line for @code{gnatchop}
11676 The @code{gnatchop} command has the form:
11679 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11680 @c @ovar{directory}
11681 @c Expanding @ovar macro inline (explanation in macro def comments)
11682 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11683 @r{[}@var{directory}@r{]}
11687 The only required argument is the file name of the file to be chopped.
11688 There are no restrictions on the form of this file name. The file itself
11689 contains one or more Ada units, in normal GNAT format, concatenated
11690 together. As shown, more than one file may be presented to be chopped.
11692 When run in default mode, @code{gnatchop} generates one output file in
11693 the current directory for each unit in each of the files.
11695 @var{directory}, if specified, gives the name of the directory to which
11696 the output files will be written. If it is not specified, all files are
11697 written to the current directory.
11699 For example, given a
11700 file called @file{hellofiles} containing
11702 @smallexample @c ada
11707 with Text_IO; use Text_IO;
11710 Put_Line ("Hello");
11720 $ gnatchop ^hellofiles^HELLOFILES.^
11724 generates two files in the current directory, one called
11725 @file{hello.ads} containing the single line that is the procedure spec,
11726 and the other called @file{hello.adb} containing the remaining text. The
11727 original file is not affected. The generated files can be compiled in
11731 When gnatchop is invoked on a file that is empty or that contains only empty
11732 lines and/or comments, gnatchop will not fail, but will not produce any
11735 For example, given a
11736 file called @file{toto.txt} containing
11738 @smallexample @c ada
11750 $ gnatchop ^toto.txt^TOT.TXT^
11754 will not produce any new file and will result in the following warnings:
11757 toto.txt:1:01: warning: empty file, contains no compilation units
11758 no compilation units found
11759 no source files written
11762 @node Switches for gnatchop
11763 @section Switches for @code{gnatchop}
11766 @command{gnatchop} recognizes the following switches:
11772 @cindex @option{--version} @command{gnatchop}
11773 Display Copyright and version, then exit disregarding all other options.
11776 @cindex @option{--help} @command{gnatchop}
11777 If @option{--version} was not used, display usage, then exit disregarding
11780 @item ^-c^/COMPILATION^
11781 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11782 Causes @code{gnatchop} to operate in compilation mode, in which
11783 configuration pragmas are handled according to strict RM rules. See
11784 previous section for a full description of this mode.
11787 @item -gnat@var{xxx}
11788 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11789 used to parse the given file. Not all @var{xxx} options make sense,
11790 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11791 process a source file that uses Latin-2 coding for identifiers.
11795 Causes @code{gnatchop} to generate a brief help summary to the standard
11796 output file showing usage information.
11798 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11799 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11800 Limit generated file names to the specified number @code{mm}
11802 This is useful if the
11803 resulting set of files is required to be interoperable with systems
11804 which limit the length of file names.
11806 If no value is given, or
11807 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11808 a default of 39, suitable for OpenVMS Alpha
11809 Systems, is assumed
11812 No space is allowed between the @option{-k} and the numeric value. The numeric
11813 value may be omitted in which case a default of @option{-k8},
11815 with DOS-like file systems, is used. If no @option{-k} switch
11817 there is no limit on the length of file names.
11820 @item ^-p^/PRESERVE^
11821 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11822 Causes the file ^modification^creation^ time stamp of the input file to be
11823 preserved and used for the time stamp of the output file(s). This may be
11824 useful for preserving coherency of time stamps in an environment where
11825 @code{gnatchop} is used as part of a standard build process.
11828 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11829 Causes output of informational messages indicating the set of generated
11830 files to be suppressed. Warnings and error messages are unaffected.
11832 @item ^-r^/REFERENCE^
11833 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11834 @findex Source_Reference
11835 Generate @code{Source_Reference} pragmas. Use this switch if the output
11836 files are regarded as temporary and development is to be done in terms
11837 of the original unchopped file. This switch causes
11838 @code{Source_Reference} pragmas to be inserted into each of the
11839 generated files to refers back to the original file name and line number.
11840 The result is that all error messages refer back to the original
11842 In addition, the debugging information placed into the object file (when
11843 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11845 also refers back to this original file so that tools like profilers and
11846 debuggers will give information in terms of the original unchopped file.
11848 If the original file to be chopped itself contains
11849 a @code{Source_Reference}
11850 pragma referencing a third file, then gnatchop respects
11851 this pragma, and the generated @code{Source_Reference} pragmas
11852 in the chopped file refer to the original file, with appropriate
11853 line numbers. This is particularly useful when @code{gnatchop}
11854 is used in conjunction with @code{gnatprep} to compile files that
11855 contain preprocessing statements and multiple units.
11857 @item ^-v^/VERBOSE^
11858 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11859 Causes @code{gnatchop} to operate in verbose mode. The version
11860 number and copyright notice are output, as well as exact copies of
11861 the gnat1 commands spawned to obtain the chop control information.
11863 @item ^-w^/OVERWRITE^
11864 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11865 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11866 fatal error if there is already a file with the same name as a
11867 file it would otherwise output, in other words if the files to be
11868 chopped contain duplicated units. This switch bypasses this
11869 check, and causes all but the last instance of such duplicated
11870 units to be skipped.
11873 @item --GCC=@var{xxxx}
11874 @cindex @option{--GCC=} (@code{gnatchop})
11875 Specify the path of the GNAT parser to be used. When this switch is used,
11876 no attempt is made to add the prefix to the GNAT parser executable.
11880 @node Examples of gnatchop Usage
11881 @section Examples of @code{gnatchop} Usage
11885 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11888 @item gnatchop -w hello_s.ada prerelease/files
11891 Chops the source file @file{hello_s.ada}. The output files will be
11892 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11894 files with matching names in that directory (no files in the current
11895 directory are modified).
11897 @item gnatchop ^archive^ARCHIVE.^
11898 Chops the source file @file{^archive^ARCHIVE.^}
11899 into the current directory. One
11900 useful application of @code{gnatchop} is in sending sets of sources
11901 around, for example in email messages. The required sources are simply
11902 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11904 @command{gnatchop} is used at the other end to reconstitute the original
11907 @item gnatchop file1 file2 file3 direc
11908 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11909 the resulting files in the directory @file{direc}. Note that if any units
11910 occur more than once anywhere within this set of files, an error message
11911 is generated, and no files are written. To override this check, use the
11912 @option{^-w^/OVERWRITE^} switch,
11913 in which case the last occurrence in the last file will
11914 be the one that is output, and earlier duplicate occurrences for a given
11915 unit will be skipped.
11918 @node Configuration Pragmas
11919 @chapter Configuration Pragmas
11920 @cindex Configuration pragmas
11921 @cindex Pragmas, configuration
11924 Configuration pragmas include those pragmas described as
11925 such in the Ada Reference Manual, as well as
11926 implementation-dependent pragmas that are configuration pragmas.
11927 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11928 for details on these additional GNAT-specific configuration pragmas.
11929 Most notably, the pragma @code{Source_File_Name}, which allows
11930 specifying non-default names for source files, is a configuration
11931 pragma. The following is a complete list of configuration pragmas
11932 recognized by GNAT:
11943 Assume_No_Invalid_Values
11948 Compile_Time_Warning
11950 Component_Alignment
11951 Convention_Identifier
11954 Default_Storage_Pool
11960 External_Name_Casing
11963 Float_Representation
11976 Priority_Specific_Dispatching
11979 Propagate_Exceptions
11982 Restricted_Run_Time
11984 Restrictions_Warnings
11986 Short_Circuit_And_Or
11988 Source_File_Name_Project
11991 Suppress_Exception_Locations
11992 Task_Dispatching_Policy
11998 Wide_Character_Encoding
12003 * Handling of Configuration Pragmas::
12004 * The Configuration Pragmas Files::
12007 @node Handling of Configuration Pragmas
12008 @section Handling of Configuration Pragmas
12010 Configuration pragmas may either appear at the start of a compilation
12011 unit, or they can appear in a configuration pragma file to apply to
12012 all compilations performed in a given compilation environment.
12014 GNAT also provides the @code{gnatchop} utility to provide an automatic
12015 way to handle configuration pragmas following the semantics for
12016 compilations (that is, files with multiple units), described in the RM.
12017 See @ref{Operating gnatchop in Compilation Mode} for details.
12018 However, for most purposes, it will be more convenient to edit the
12019 @file{gnat.adc} file that contains configuration pragmas directly,
12020 as described in the following section.
12022 In the case of @code{Restrictions} pragmas appearing as configuration
12023 pragmas in individual compilation units, the exact handling depends on
12024 the type of restriction.
12026 Restrictions that require partition-wide consistency (like
12027 @code{No_Tasking}) are
12028 recognized wherever they appear
12029 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12030 unit. This makes sense since the binder will in any case insist on seeing
12031 consistent use, so any unit not conforming to any restrictions that are
12032 anywhere in the partition will be rejected, and you might as well find
12033 that out at compile time rather than at bind time.
12035 For restrictions that do not require partition-wide consistency, e.g.
12036 SPARK or No_Implementation_Attributes, in general the restriction applies
12037 only to the unit in which the pragma appears, and not to any other units.
12039 The exception is No_Elaboration_Code which always applies to the entire
12040 object file from a compilation, i.e. to the body, spec, and all subunits.
12041 This restriction can be specified in a configuration pragma file, or it
12042 can be on the body and/or the spec (in eithe case it applies to all the
12043 relevant units). It can appear on a subunit only if it has previously
12044 appeared in the body of spec.
12046 @node The Configuration Pragmas Files
12047 @section The Configuration Pragmas Files
12048 @cindex @file{gnat.adc}
12051 In GNAT a compilation environment is defined by the current
12052 directory at the time that a compile command is given. This current
12053 directory is searched for a file whose name is @file{gnat.adc}. If
12054 this file is present, it is expected to contain one or more
12055 configuration pragmas that will be applied to the current compilation.
12056 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12059 Configuration pragmas may be entered into the @file{gnat.adc} file
12060 either by running @code{gnatchop} on a source file that consists only of
12061 configuration pragmas, or more conveniently by
12062 direct editing of the @file{gnat.adc} file, which is a standard format
12065 In addition to @file{gnat.adc}, additional files containing configuration
12066 pragmas may be applied to the current compilation using the switch
12067 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12068 contains only configuration pragmas. These configuration pragmas are
12069 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12070 is present and switch @option{-gnatA} is not used).
12072 It is allowed to specify several switches @option{-gnatec}, all of which
12073 will be taken into account.
12075 If you are using project file, a separate mechanism is provided using
12076 project attributes, see @ref{Specifying Configuration Pragmas} for more
12080 Of special interest to GNAT OpenVMS Alpha is the following
12081 configuration pragma:
12083 @smallexample @c ada
12085 pragma Extend_System (Aux_DEC);
12090 In the presence of this pragma, GNAT adds to the definition of the
12091 predefined package SYSTEM all the additional types and subprograms that are
12092 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12095 @node Handling Arbitrary File Naming Conventions Using gnatname
12096 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
12097 @cindex Arbitrary File Naming Conventions
12100 * Arbitrary File Naming Conventions::
12101 * Running gnatname::
12102 * Switches for gnatname::
12103 * Examples of gnatname Usage::
12106 @node Arbitrary File Naming Conventions
12107 @section Arbitrary File Naming Conventions
12110 The GNAT compiler must be able to know the source file name of a compilation
12111 unit. When using the standard GNAT default file naming conventions
12112 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12113 does not need additional information.
12116 When the source file names do not follow the standard GNAT default file naming
12117 conventions, the GNAT compiler must be given additional information through
12118 a configuration pragmas file (@pxref{Configuration Pragmas})
12120 When the non-standard file naming conventions are well-defined,
12121 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12122 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12123 if the file naming conventions are irregular or arbitrary, a number
12124 of pragma @code{Source_File_Name} for individual compilation units
12126 To help maintain the correspondence between compilation unit names and
12127 source file names within the compiler,
12128 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12131 @node Running gnatname
12132 @section Running @code{gnatname}
12135 The usual form of the @code{gnatname} command is
12138 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12139 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12140 @c Expanding @ovar macro inline (explanation in macro def comments)
12141 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12142 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12146 All of the arguments are optional. If invoked without any argument,
12147 @code{gnatname} will display its usage.
12150 When used with at least one naming pattern, @code{gnatname} will attempt to
12151 find all the compilation units in files that follow at least one of the
12152 naming patterns. To find these compilation units,
12153 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12157 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12158 Each Naming Pattern is enclosed between double quotes (or single
12159 quotes on Windows).
12160 A Naming Pattern is a regular expression similar to the wildcard patterns
12161 used in file names by the Unix shells or the DOS prompt.
12164 @code{gnatname} may be called with several sections of directories/patterns.
12165 Sections are separated by switch @code{--and}. In each section, there must be
12166 at least one pattern. If no directory is specified in a section, the current
12167 directory (or the project directory is @code{-P} is used) is implied.
12168 The options other that the directory switches and the patterns apply globally
12169 even if they are in different sections.
12172 Examples of Naming Patterns are
12181 For a more complete description of the syntax of Naming Patterns,
12182 see the second kind of regular expressions described in @file{g-regexp.ads}
12183 (the ``Glob'' regular expressions).
12186 When invoked with no switch @code{-P}, @code{gnatname} will create a
12187 configuration pragmas file @file{gnat.adc} in the current working directory,
12188 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12191 @node Switches for gnatname
12192 @section Switches for @code{gnatname}
12195 Switches for @code{gnatname} must precede any specified Naming Pattern.
12198 You may specify any of the following switches to @code{gnatname}:
12204 @cindex @option{--version} @command{gnatname}
12205 Display Copyright and version, then exit disregarding all other options.
12208 @cindex @option{--help} @command{gnatname}
12209 If @option{--version} was not used, display usage, then exit disregarding
12213 Start another section of directories/patterns.
12215 @item ^-c^/CONFIG_FILE=^@file{file}
12216 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12217 Create a configuration pragmas file @file{file} (instead of the default
12220 There may be zero, one or more space between @option{-c} and
12223 @file{file} may include directory information. @file{file} must be
12224 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12225 When a switch @option{^-c^/CONFIG_FILE^} is
12226 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12228 @item ^-d^/SOURCE_DIRS=^@file{dir}
12229 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12230 Look for source files in directory @file{dir}. There may be zero, one or more
12231 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12232 When a switch @option{^-d^/SOURCE_DIRS^}
12233 is specified, the current working directory will not be searched for source
12234 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12235 or @option{^-D^/DIR_FILES^} switch.
12236 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12237 If @file{dir} is a relative path, it is relative to the directory of
12238 the configuration pragmas file specified with switch
12239 @option{^-c^/CONFIG_FILE^},
12240 or to the directory of the project file specified with switch
12241 @option{^-P^/PROJECT_FILE^} or,
12242 if neither switch @option{^-c^/CONFIG_FILE^}
12243 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12244 current working directory. The directory
12245 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12247 @item ^-D^/DIRS_FILE=^@file{file}
12248 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12249 Look for source files in all directories listed in text file @file{file}.
12250 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12252 @file{file} must be an existing, readable text file.
12253 Each nonempty line in @file{file} must be a directory.
12254 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12255 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12258 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12259 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12260 Foreign patterns. Using this switch, it is possible to add sources of languages
12261 other than Ada to the list of sources of a project file.
12262 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12265 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12268 will look for Ada units in all files with the @file{.ada} extension,
12269 and will add to the list of file for project @file{prj.gpr} the C files
12270 with extension @file{.^c^C^}.
12273 @cindex @option{^-h^/HELP^} (@code{gnatname})
12274 Output usage (help) information. The output is written to @file{stdout}.
12276 @item ^-P^/PROJECT_FILE=^@file{proj}
12277 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12278 Create or update project file @file{proj}. There may be zero, one or more space
12279 between @option{-P} and @file{proj}. @file{proj} may include directory
12280 information. @file{proj} must be writable.
12281 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12282 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12283 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12285 @item ^-v^/VERBOSE^
12286 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12287 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12288 This includes name of the file written, the name of the directories to search
12289 and, for each file in those directories whose name matches at least one of
12290 the Naming Patterns, an indication of whether the file contains a unit,
12291 and if so the name of the unit.
12293 @item ^-v -v^/VERBOSE /VERBOSE^
12294 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12295 Very Verbose mode. In addition to the output produced in verbose mode,
12296 for each file in the searched directories whose name matches none of
12297 the Naming Patterns, an indication is given that there is no match.
12299 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12300 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12301 Excluded patterns. Using this switch, it is possible to exclude some files
12302 that would match the name patterns. For example,
12304 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12307 will look for Ada units in all files with the @file{.ada} extension,
12308 except those whose names end with @file{_nt.ada}.
12312 @node Examples of gnatname Usage
12313 @section Examples of @code{gnatname} Usage
12317 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12323 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12328 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12329 and be writable. In addition, the directory
12330 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12331 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12334 Note the optional spaces after @option{-c} and @option{-d}.
12339 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12340 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12343 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12344 /EXCLUDED_PATTERN=*_nt_body.ada
12345 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12346 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12350 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12351 even in conjunction with one or several switches
12352 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12353 are used in this example.
12355 @c *****************************************
12356 @c * G N A T P r o j e c t M a n a g e r *
12357 @c *****************************************
12359 @c ------ macros for projects.texi
12360 @c These macros are needed when building the gprbuild documentation, but
12361 @c should have no effect in the gnat user's guide
12363 @macro CODESAMPLE{TXT}
12371 @macro PROJECTFILE{TXT}
12375 @c simulates a newline when in a @CODESAMPLE
12386 @macro TIPHTML{TXT}
12390 @macro IMPORTANT{TXT}
12405 @include projects.texi
12407 @c *****************************************
12408 @c * Cross-referencing tools
12409 @c *****************************************
12411 @node The Cross-Referencing Tools gnatxref and gnatfind
12412 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12417 The compiler generates cross-referencing information (unless
12418 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12419 This information indicates where in the source each entity is declared and
12420 referenced. Note that entities in package Standard are not included, but
12421 entities in all other predefined units are included in the output.
12423 Before using any of these two tools, you need to compile successfully your
12424 application, so that GNAT gets a chance to generate the cross-referencing
12427 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12428 information to provide the user with the capability to easily locate the
12429 declaration and references to an entity. These tools are quite similar,
12430 the difference being that @code{gnatfind} is intended for locating
12431 definitions and/or references to a specified entity or entities, whereas
12432 @code{gnatxref} is oriented to generating a full report of all
12435 To use these tools, you must not compile your application using the
12436 @option{-gnatx} switch on the @command{gnatmake} command line
12437 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12438 information will not be generated.
12440 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12441 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12444 * Switches for gnatxref::
12445 * Switches for gnatfind::
12446 * Project Files for gnatxref and gnatfind::
12447 * Regular Expressions in gnatfind and gnatxref::
12448 * Examples of gnatxref Usage::
12449 * Examples of gnatfind Usage::
12452 @node Switches for gnatxref
12453 @section @code{gnatxref} Switches
12456 The command invocation for @code{gnatxref} is:
12458 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12459 @c Expanding @ovar macro inline (explanation in macro def comments)
12460 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12469 identifies the source files for which a report is to be generated. The
12470 ``with''ed units will be processed too. You must provide at least one file.
12472 These file names are considered to be regular expressions, so for instance
12473 specifying @file{source*.adb} is the same as giving every file in the current
12474 directory whose name starts with @file{source} and whose extension is
12477 You shouldn't specify any directory name, just base names. @command{gnatxref}
12478 and @command{gnatfind} will be able to locate these files by themselves using
12479 the source path. If you specify directories, no result is produced.
12484 The switches can be:
12488 @cindex @option{--version} @command{gnatxref}
12489 Display Copyright and version, then exit disregarding all other options.
12492 @cindex @option{--help} @command{gnatxref}
12493 If @option{--version} was not used, display usage, then exit disregarding
12496 @item ^-a^/ALL_FILES^
12497 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12498 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12499 the read-only files found in the library search path. Otherwise, these files
12500 will be ignored. This option can be used to protect Gnat sources or your own
12501 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12502 much faster, and their output much smaller. Read-only here refers to access
12503 or permissions status in the file system for the current user.
12506 @cindex @option{-aIDIR} (@command{gnatxref})
12507 When looking for source files also look in directory DIR. The order in which
12508 source file search is undertaken is the same as for @command{gnatmake}.
12511 @cindex @option{-aODIR} (@command{gnatxref})
12512 When searching for library and object files, look in directory
12513 DIR. The order in which library files are searched is the same as for
12514 @command{gnatmake}.
12517 @cindex @option{-nostdinc} (@command{gnatxref})
12518 Do not look for sources in the system default directory.
12521 @cindex @option{-nostdlib} (@command{gnatxref})
12522 Do not look for library files in the system default directory.
12524 @item --ext=@var{extension}
12525 @cindex @option{--ext} (@command{gnatxref})
12526 Specify an alternate ali file extension. The default is @code{ali} and other
12527 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12528 switch. Note that if this switch overrides the default, which means that only
12529 the new extension will be considered.
12531 @item --RTS=@var{rts-path}
12532 @cindex @option{--RTS} (@command{gnatxref})
12533 Specifies the default location of the runtime library. Same meaning as the
12534 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12536 @item ^-d^/DERIVED_TYPES^
12537 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12538 If this switch is set @code{gnatxref} will output the parent type
12539 reference for each matching derived types.
12541 @item ^-f^/FULL_PATHNAME^
12542 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12543 If this switch is set, the output file names will be preceded by their
12544 directory (if the file was found in the search path). If this switch is
12545 not set, the directory will not be printed.
12547 @item ^-g^/IGNORE_LOCALS^
12548 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12549 If this switch is set, information is output only for library-level
12550 entities, ignoring local entities. The use of this switch may accelerate
12551 @code{gnatfind} and @code{gnatxref}.
12554 @cindex @option{-IDIR} (@command{gnatxref})
12555 Equivalent to @samp{-aODIR -aIDIR}.
12558 @cindex @option{-pFILE} (@command{gnatxref})
12559 Specify a project file to use @xref{GNAT Project Manager}.
12560 If you need to use the @file{.gpr}
12561 project files, you should use gnatxref through the GNAT driver
12562 (@command{gnat xref -Pproject}).
12564 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12565 project file in the current directory.
12567 If a project file is either specified or found by the tools, then the content
12568 of the source directory and object directory lines are added as if they
12569 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12570 and @samp{^-aO^OBJECT_SEARCH^}.
12572 Output only unused symbols. This may be really useful if you give your
12573 main compilation unit on the command line, as @code{gnatxref} will then
12574 display every unused entity and 'with'ed package.
12578 Instead of producing the default output, @code{gnatxref} will generate a
12579 @file{tags} file that can be used by vi. For examples how to use this
12580 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12581 to the standard output, thus you will have to redirect it to a file.
12587 All these switches may be in any order on the command line, and may even
12588 appear after the file names. They need not be separated by spaces, thus
12589 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12590 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12592 @node Switches for gnatfind
12593 @section @code{gnatfind} Switches
12596 The command line for @code{gnatfind} is:
12599 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12600 @c @r{[}@var{file1} @var{file2} @dots{}]
12601 @c Expanding @ovar macro inline (explanation in macro def comments)
12602 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12603 @r{[}@var{file1} @var{file2} @dots{}@r{]}
12611 An entity will be output only if it matches the regular expression found
12612 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12614 Omitting the pattern is equivalent to specifying @samp{*}, which
12615 will match any entity. Note that if you do not provide a pattern, you
12616 have to provide both a sourcefile and a line.
12618 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12619 for matching purposes. At the current time there is no support for
12620 8-bit codes other than Latin-1, or for wide characters in identifiers.
12623 @code{gnatfind} will look for references, bodies or declarations
12624 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12625 and column @var{column}. See @ref{Examples of gnatfind Usage}
12626 for syntax examples.
12629 is a decimal integer identifying the line number containing
12630 the reference to the entity (or entities) to be located.
12633 is a decimal integer identifying the exact location on the
12634 line of the first character of the identifier for the
12635 entity reference. Columns are numbered from 1.
12637 @item file1 file2 @dots{}
12638 The search will be restricted to these source files. If none are given, then
12639 the search will be done for every library file in the search path.
12640 These file must appear only after the pattern or sourcefile.
12642 These file names are considered to be regular expressions, so for instance
12643 specifying @file{source*.adb} is the same as giving every file in the current
12644 directory whose name starts with @file{source} and whose extension is
12647 The location of the spec of the entity will always be displayed, even if it
12648 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
12649 occurrences of the entity in the separate units of the ones given on the
12650 command line will also be displayed.
12652 Note that if you specify at least one file in this part, @code{gnatfind} may
12653 sometimes not be able to find the body of the subprograms.
12658 At least one of 'sourcefile' or 'pattern' has to be present on
12661 The following switches are available:
12665 @cindex @option{--version} @command{gnatfind}
12666 Display Copyright and version, then exit disregarding all other options.
12669 @cindex @option{--help} @command{gnatfind}
12670 If @option{--version} was not used, display usage, then exit disregarding
12673 @item ^-a^/ALL_FILES^
12674 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12675 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12676 the read-only files found in the library search path. Otherwise, these files
12677 will be ignored. This option can be used to protect Gnat sources or your own
12678 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12679 much faster, and their output much smaller. Read-only here refers to access
12680 or permission status in the file system for the current user.
12683 @cindex @option{-aIDIR} (@command{gnatfind})
12684 When looking for source files also look in directory DIR. The order in which
12685 source file search is undertaken is the same as for @command{gnatmake}.
12688 @cindex @option{-aODIR} (@command{gnatfind})
12689 When searching for library and object files, look in directory
12690 DIR. The order in which library files are searched is the same as for
12691 @command{gnatmake}.
12694 @cindex @option{-nostdinc} (@command{gnatfind})
12695 Do not look for sources in the system default directory.
12698 @cindex @option{-nostdlib} (@command{gnatfind})
12699 Do not look for library files in the system default directory.
12701 @item --ext=@var{extension}
12702 @cindex @option{--ext} (@command{gnatfind})
12703 Specify an alternate ali file extension. The default is @code{ali} and other
12704 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12705 switch. Note that if this switch overrides the default, which means that only
12706 the new extension will be considered.
12708 @item --RTS=@var{rts-path}
12709 @cindex @option{--RTS} (@command{gnatfind})
12710 Specifies the default location of the runtime library. Same meaning as the
12711 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12713 @item ^-d^/DERIVED_TYPE_INFORMATION^
12714 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12715 If this switch is set, then @code{gnatfind} will output the parent type
12716 reference for each matching derived types.
12718 @item ^-e^/EXPRESSIONS^
12719 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12720 By default, @code{gnatfind} accept the simple regular expression set for
12721 @samp{pattern}. If this switch is set, then the pattern will be
12722 considered as full Unix-style regular expression.
12724 @item ^-f^/FULL_PATHNAME^
12725 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12726 If this switch is set, the output file names will be preceded by their
12727 directory (if the file was found in the search path). If this switch is
12728 not set, the directory will not be printed.
12730 @item ^-g^/IGNORE_LOCALS^
12731 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12732 If this switch is set, information is output only for library-level
12733 entities, ignoring local entities. The use of this switch may accelerate
12734 @code{gnatfind} and @code{gnatxref}.
12737 @cindex @option{-IDIR} (@command{gnatfind})
12738 Equivalent to @samp{-aODIR -aIDIR}.
12741 @cindex @option{-pFILE} (@command{gnatfind})
12742 Specify a project file (@pxref{GNAT Project Manager}) to use.
12743 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12744 project file in the current directory.
12746 If a project file is either specified or found by the tools, then the content
12747 of the source directory and object directory lines are added as if they
12748 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12749 @samp{^-aO^/OBJECT_SEARCH^}.
12751 @item ^-r^/REFERENCES^
12752 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12753 By default, @code{gnatfind} will output only the information about the
12754 declaration, body or type completion of the entities. If this switch is
12755 set, the @code{gnatfind} will locate every reference to the entities in
12756 the files specified on the command line (or in every file in the search
12757 path if no file is given on the command line).
12759 @item ^-s^/PRINT_LINES^
12760 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12761 If this switch is set, then @code{gnatfind} will output the content
12762 of the Ada source file lines were the entity was found.
12764 @item ^-t^/TYPE_HIERARCHY^
12765 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12766 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12767 the specified type. It act like -d option but recursively from parent
12768 type to parent type. When this switch is set it is not possible to
12769 specify more than one file.
12774 All these switches may be in any order on the command line, and may even
12775 appear after the file names. They need not be separated by spaces, thus
12776 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12777 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12779 As stated previously, gnatfind will search in every directory in the
12780 search path. You can force it to look only in the current directory if
12781 you specify @code{*} at the end of the command line.
12783 @node Project Files for gnatxref and gnatfind
12784 @section Project Files for @command{gnatxref} and @command{gnatfind}
12787 Project files allow a programmer to specify how to compile its
12788 application, where to find sources, etc. These files are used
12790 primarily by GPS, but they can also be used
12793 @code{gnatxref} and @code{gnatfind}.
12795 A project file name must end with @file{.gpr}. If a single one is
12796 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12797 extract the information from it. If multiple project files are found, none of
12798 them is read, and you have to use the @samp{-p} switch to specify the one
12801 The following lines can be included, even though most of them have default
12802 values which can be used in most cases.
12803 The lines can be entered in any order in the file.
12804 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12805 each line. If you have multiple instances, only the last one is taken into
12810 [default: @code{"^./^[]^"}]
12811 specifies a directory where to look for source files. Multiple @code{src_dir}
12812 lines can be specified and they will be searched in the order they
12816 [default: @code{"^./^[]^"}]
12817 specifies a directory where to look for object and library files. Multiple
12818 @code{obj_dir} lines can be specified, and they will be searched in the order
12821 @item comp_opt=SWITCHES
12822 [default: @code{""}]
12823 creates a variable which can be referred to subsequently by using
12824 the @code{$@{comp_opt@}} notation. This is intended to store the default
12825 switches given to @command{gnatmake} and @command{gcc}.
12827 @item bind_opt=SWITCHES
12828 [default: @code{""}]
12829 creates a variable which can be referred to subsequently by using
12830 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12831 switches given to @command{gnatbind}.
12833 @item link_opt=SWITCHES
12834 [default: @code{""}]
12835 creates a variable which can be referred to subsequently by using
12836 the @samp{$@{link_opt@}} notation. This is intended to store the default
12837 switches given to @command{gnatlink}.
12839 @item main=EXECUTABLE
12840 [default: @code{""}]
12841 specifies the name of the executable for the application. This variable can
12842 be referred to in the following lines by using the @samp{$@{main@}} notation.
12845 @item comp_cmd=COMMAND
12846 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12849 @item comp_cmd=COMMAND
12850 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12852 specifies the command used to compile a single file in the application.
12855 @item make_cmd=COMMAND
12856 [default: @code{"GNAT MAKE $@{main@}
12857 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12858 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12859 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12862 @item make_cmd=COMMAND
12863 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12864 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12865 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12867 specifies the command used to recompile the whole application.
12869 @item run_cmd=COMMAND
12870 [default: @code{"$@{main@}"}]
12871 specifies the command used to run the application.
12873 @item debug_cmd=COMMAND
12874 [default: @code{"gdb $@{main@}"}]
12875 specifies the command used to debug the application
12880 @command{gnatxref} and @command{gnatfind} only take into account the
12881 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12883 @node Regular Expressions in gnatfind and gnatxref
12884 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12887 As specified in the section about @command{gnatfind}, the pattern can be a
12888 regular expression. Actually, there are to set of regular expressions
12889 which are recognized by the program:
12892 @item globbing patterns
12893 These are the most usual regular expression. They are the same that you
12894 generally used in a Unix shell command line, or in a DOS session.
12896 Here is a more formal grammar:
12903 term ::= elmt -- matches elmt
12904 term ::= elmt elmt -- concatenation (elmt then elmt)
12905 term ::= * -- any string of 0 or more characters
12906 term ::= ? -- matches any character
12907 term ::= [char @{char@}] -- matches any character listed
12908 term ::= [char - char] -- matches any character in range
12912 @item full regular expression
12913 The second set of regular expressions is much more powerful. This is the
12914 type of regular expressions recognized by utilities such a @file{grep}.
12916 The following is the form of a regular expression, expressed in Ada
12917 reference manual style BNF is as follows
12924 regexp ::= term @{| term@} -- alternation (term or term @dots{})
12926 term ::= item @{item@} -- concatenation (item then item)
12928 item ::= elmt -- match elmt
12929 item ::= elmt * -- zero or more elmt's
12930 item ::= elmt + -- one or more elmt's
12931 item ::= elmt ? -- matches elmt or nothing
12934 elmt ::= nschar -- matches given character
12935 elmt ::= [nschar @{nschar@}] -- matches any character listed
12936 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12937 elmt ::= [char - char] -- matches chars in given range
12938 elmt ::= \ char -- matches given character
12939 elmt ::= . -- matches any single character
12940 elmt ::= ( regexp ) -- parens used for grouping
12942 char ::= any character, including special characters
12943 nschar ::= any character except ()[].*+?^^^
12947 Following are a few examples:
12951 will match any of the two strings @samp{abcde} and @samp{fghi},
12954 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12955 @samp{abcccd}, and so on,
12958 will match any string which has only lowercase characters in it (and at
12959 least one character.
12964 @node Examples of gnatxref Usage
12965 @section Examples of @code{gnatxref} Usage
12967 @subsection General Usage
12970 For the following examples, we will consider the following units:
12972 @smallexample @c ada
12978 3: procedure Foo (B : in Integer);
12985 1: package body Main is
12986 2: procedure Foo (B : in Integer) is
12997 2: procedure Print (B : Integer);
13006 The first thing to do is to recompile your application (for instance, in
13007 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13008 the cross-referencing information.
13009 You can then issue any of the following commands:
13011 @item gnatxref main.adb
13012 @code{gnatxref} generates cross-reference information for main.adb
13013 and every unit 'with'ed by main.adb.
13015 The output would be:
13023 Decl: main.ads 3:20
13024 Body: main.adb 2:20
13025 Ref: main.adb 4:13 5:13 6:19
13028 Ref: main.adb 6:8 7:8
13038 Decl: main.ads 3:15
13039 Body: main.adb 2:15
13042 Body: main.adb 1:14
13045 Ref: main.adb 6:12 7:12
13049 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13050 its body is in main.adb, line 1, column 14 and is not referenced any where.
13052 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13053 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13055 @item gnatxref package1.adb package2.ads
13056 @code{gnatxref} will generates cross-reference information for
13057 package1.adb, package2.ads and any other package 'with'ed by any
13063 @subsection Using gnatxref with vi
13065 @code{gnatxref} can generate a tags file output, which can be used
13066 directly from @command{vi}. Note that the standard version of @command{vi}
13067 will not work properly with overloaded symbols. Consider using another
13068 free implementation of @command{vi}, such as @command{vim}.
13071 $ gnatxref -v gnatfind.adb > tags
13075 will generate the tags file for @code{gnatfind} itself (if the sources
13076 are in the search path!).
13078 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13079 (replacing @var{entity} by whatever you are looking for), and vi will
13080 display a new file with the corresponding declaration of entity.
13083 @node Examples of gnatfind Usage
13084 @section Examples of @code{gnatfind} Usage
13088 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13089 Find declarations for all entities xyz referenced at least once in
13090 main.adb. The references are search in every library file in the search
13093 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13096 The output will look like:
13098 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13099 ^directory/^[directory]^main.adb:24:10: xyz <= body
13100 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13104 that is to say, one of the entities xyz found in main.adb is declared at
13105 line 12 of main.ads (and its body is in main.adb), and another one is
13106 declared at line 45 of foo.ads
13108 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13109 This is the same command as the previous one, instead @code{gnatfind} will
13110 display the content of the Ada source file lines.
13112 The output will look like:
13115 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13117 ^directory/^[directory]^main.adb:24:10: xyz <= body
13119 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13124 This can make it easier to find exactly the location your are looking
13127 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13128 Find references to all entities containing an x that are
13129 referenced on line 123 of main.ads.
13130 The references will be searched only in main.ads and foo.adb.
13132 @item gnatfind main.ads:123
13133 Find declarations and bodies for all entities that are referenced on
13134 line 123 of main.ads.
13136 This is the same as @code{gnatfind "*":main.adb:123}.
13138 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13139 Find the declaration for the entity referenced at column 45 in
13140 line 123 of file main.adb in directory mydir. Note that it
13141 is usual to omit the identifier name when the column is given,
13142 since the column position identifies a unique reference.
13144 The column has to be the beginning of the identifier, and should not
13145 point to any character in the middle of the identifier.
13149 @c *********************************
13150 @node The GNAT Pretty-Printer gnatpp
13151 @chapter The GNAT Pretty-Printer @command{gnatpp}
13153 @cindex Pretty-Printer
13156 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13157 for source reformatting / pretty-printing.
13158 It takes an Ada source file as input and generates a reformatted
13160 You can specify various style directives via switches; e.g.,
13161 identifier case conventions, rules of indentation, and comment layout.
13163 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13164 tree for the input source and thus requires the input to be syntactically and
13165 semantically legal.
13166 If this condition is not met, @command{gnatpp} will terminate with an
13167 error message; no output file will be generated.
13169 @command{gnatpp} cannot process sources that contain
13170 preprocessing directives.
13172 If the compilation unit
13173 contained in the input source depends semantically upon units located
13174 outside the current directory, you have to provide the source search path
13175 when invoking @command{gnatpp}, if these units are contained in files with
13176 names that do not follow the GNAT file naming rules, you have to provide
13177 the configuration file describing the corresponding naming scheme;
13178 see the description of the @command{gnatpp}
13179 switches below. Another possibility is to use a project file and to
13180 call @command{gnatpp} through the @command{gnat} driver
13181 (see @ref{The GNAT Driver and Project Files}).
13183 The @command{gnatpp} command has the form
13186 @c $ gnatpp @ovar{switches} @var{filename}
13187 @c Expanding @ovar macro inline (explanation in macro def comments)
13188 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13195 @var{switches} is an optional sequence of switches defining such properties as
13196 the formatting rules, the source search path, and the destination for the
13200 @var{filename} is the name (including the extension) of the source file to
13201 reformat; ``wildcards'' or several file names on the same gnatpp command are
13202 allowed. The file name may contain path information; it does not have to
13203 follow the GNAT file naming rules
13206 @samp{@var{gcc_switches}} is a list of switches for
13207 @command{gcc}. They will be passed on to all compiler invocations made by
13208 @command{gnatelim} to generate the ASIS trees. Here you can provide
13209 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13210 use the @option{-gnatec} switch to set the configuration file,
13211 use the @option{-gnat05} switch if sources should be compiled in
13216 * Switches for gnatpp::
13217 * Formatting Rules::
13220 @node Switches for gnatpp
13221 @section Switches for @command{gnatpp}
13224 The following subsections describe the various switches accepted by
13225 @command{gnatpp}, organized by category.
13228 You specify a switch by supplying a name and generally also a value.
13229 In many cases the values for a switch with a given name are incompatible with
13231 (for example the switch that controls the casing of a reserved word may have
13232 exactly one value: upper case, lower case, or
13233 mixed case) and thus exactly one such switch can be in effect for an
13234 invocation of @command{gnatpp}.
13235 If more than one is supplied, the last one is used.
13236 However, some values for the same switch are mutually compatible.
13237 You may supply several such switches to @command{gnatpp}, but then
13238 each must be specified in full, with both the name and the value.
13239 Abbreviated forms (the name appearing once, followed by each value) are
13241 For example, to set
13242 the alignment of the assignment delimiter both in declarations and in
13243 assignment statements, you must write @option{-A2A3}
13244 (or @option{-A2 -A3}), but not @option{-A23}.
13248 In many cases the set of options for a given qualifier are incompatible with
13249 each other (for example the qualifier that controls the casing of a reserved
13250 word may have exactly one option, which specifies either upper case, lower
13251 case, or mixed case), and thus exactly one such option can be in effect for
13252 an invocation of @command{gnatpp}.
13253 If more than one is supplied, the last one is used.
13254 However, some qualifiers have options that are mutually compatible,
13255 and then you may then supply several such options when invoking
13259 In most cases, it is obvious whether or not the
13260 ^values for a switch with a given name^options for a given qualifier^
13261 are compatible with each other.
13262 When the semantics might not be evident, the summaries below explicitly
13263 indicate the effect.
13266 * Alignment Control::
13268 * Construct Layout Control::
13269 * General Text Layout Control::
13270 * Other Formatting Options::
13271 * Setting the Source Search Path::
13272 * Output File Control::
13273 * Other gnatpp Switches::
13276 @node Alignment Control
13277 @subsection Alignment Control
13278 @cindex Alignment control in @command{gnatpp}
13281 Programs can be easier to read if certain constructs are vertically aligned.
13282 By default all alignments are set ON.
13283 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13284 OFF, and then use one or more of the other
13285 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13286 to activate alignment for specific constructs.
13289 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13293 Set all alignments to ON
13296 @item ^-A0^/ALIGN=OFF^
13297 Set all alignments to OFF
13299 @item ^-A1^/ALIGN=COLONS^
13300 Align @code{:} in declarations
13302 @item ^-A2^/ALIGN=DECLARATIONS^
13303 Align @code{:=} in initializations in declarations
13305 @item ^-A3^/ALIGN=STATEMENTS^
13306 Align @code{:=} in assignment statements
13308 @item ^-A4^/ALIGN=ARROWS^
13309 Align @code{=>} in associations
13311 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13312 Align @code{at} keywords in the component clauses in record
13313 representation clauses
13317 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13320 @node Casing Control
13321 @subsection Casing Control
13322 @cindex Casing control in @command{gnatpp}
13325 @command{gnatpp} allows you to specify the casing for reserved words,
13326 pragma names, attribute designators and identifiers.
13327 For identifiers you may define a
13328 general rule for name casing but also override this rule
13329 via a set of dictionary files.
13331 Three types of casing are supported: lower case, upper case, and mixed case.
13332 Lower and upper case are self-explanatory (but since some letters in
13333 Latin1 and other GNAT-supported character sets
13334 exist only in lower-case form, an upper case conversion will have no
13336 ``Mixed case'' means that the first letter, and also each letter immediately
13337 following an underscore, are converted to their uppercase forms;
13338 all the other letters are converted to their lowercase forms.
13341 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13342 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13343 Attribute designators are lower case
13345 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13346 Attribute designators are upper case
13348 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13349 Attribute designators are mixed case (this is the default)
13351 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13352 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13353 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13354 lower case (this is the default)
13356 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13357 Keywords are upper case
13359 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13360 @item ^-nD^/NAME_CASING=AS_DECLARED^
13361 Name casing for defining occurrences are as they appear in the source file
13362 (this is the default)
13364 @item ^-nU^/NAME_CASING=UPPER_CASE^
13365 Names are in upper case
13367 @item ^-nL^/NAME_CASING=LOWER_CASE^
13368 Names are in lower case
13370 @item ^-nM^/NAME_CASING=MIXED_CASE^
13371 Names are in mixed case
13373 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13374 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13375 Enumeration literal casing for defining occurrences are as they appear in the
13376 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13378 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13379 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
13382 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13383 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13386 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13387 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13390 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13391 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13392 Names introduced by type and subtype declarations are always
13393 cased as they appear in the declaration in the source file.
13394 Overrides ^-n^/NAME_CASING^ casing setting.
13396 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13397 Names introduced by type and subtype declarations are always in
13398 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13400 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13401 Names introduced by type and subtype declarations are always in
13402 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13404 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13405 Names introduced by type and subtype declarations are always in
13406 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13408 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13409 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13410 Pragma names are lower case
13412 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13413 Pragma names are upper case
13415 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13416 Pragma names are mixed case (this is the default)
13418 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13419 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13420 Use @var{file} as a @emph{dictionary file} that defines
13421 the casing for a set of specified names,
13422 thereby overriding the effect on these names by
13423 any explicit or implicit
13424 ^-n^/NAME_CASING^ switch.
13425 To supply more than one dictionary file,
13426 use ^several @option{-D} switches^a list of files as options^.
13429 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13430 to define the casing for the Ada predefined names and
13431 the names declared in the GNAT libraries.
13433 @item ^-D-^/SPECIFIC_CASING^
13434 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13435 Do not use the default dictionary file;
13436 instead, use the casing
13437 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13442 The structure of a dictionary file, and details on the conventions
13443 used in the default dictionary file, are defined in @ref{Name Casing}.
13445 The @option{^-D-^/SPECIFIC_CASING^} and
13446 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13449 @node Construct Layout Control
13450 @subsection Construct Layout Control
13451 @cindex Layout control in @command{gnatpp}
13454 This group of @command{gnatpp} switches controls the layout of comments and
13455 complex syntactic constructs. See @ref{Formatting Comments} for details
13459 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13460 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13461 All the comments remain unchanged
13463 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13464 GNAT-style comment line indentation (this is the default).
13466 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13467 Reference-manual comment line indentation.
13469 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13470 GNAT-style comment beginning
13472 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13473 Reformat comment blocks
13475 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13476 Keep unchanged special form comments
13478 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13479 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13480 GNAT-style layout (this is the default)
13482 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13485 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13488 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13490 All the VT characters are removed from the comment text. All the HT characters
13491 are expanded with the sequences of space characters to get to the next tab
13494 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13495 @item ^--no-separate-is^/NO_SEPARATE_IS^
13496 Do not place the keyword @code{is} on a separate line in a subprogram body in
13497 case if the spec occupies more than one line.
13499 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13500 @item ^--separate-label^/SEPARATE_LABEL^
13501 Place statement label(s) on a separate line, with the following statement
13504 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13505 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13506 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13507 keyword @code{then} in IF statements on a separate line.
13509 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13510 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13511 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13512 keyword @code{then} in IF statements on a separate line. This option is
13513 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13515 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13516 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13517 Start each USE clause in a context clause from a separate line.
13519 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13520 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13521 Use a separate line for a loop or block statement name, but do not use an extra
13522 indentation level for the statement itself.
13528 The @option{-c1} and @option{-c2} switches are incompatible.
13529 The @option{-c3} and @option{-c4} switches are compatible with each other and
13530 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13531 the other comment formatting switches.
13533 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13538 For the @option{/COMMENTS_LAYOUT} qualifier:
13541 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13543 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13544 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13548 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13549 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13552 @node General Text Layout Control
13553 @subsection General Text Layout Control
13556 These switches allow control over line length and indentation.
13559 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13560 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13561 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13563 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13564 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13565 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13567 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13568 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13569 Indentation level for continuation lines (relative to the line being
13570 continued), @var{nnn} from 1@dots{}9.
13572 value is one less than the (normal) indentation level, unless the
13573 indentation is set to 1 (in which case the default value for continuation
13574 line indentation is also 1)
13577 @node Other Formatting Options
13578 @subsection Other Formatting Options
13581 These switches control the inclusion of missing end/exit labels, and
13582 the indentation level in @b{case} statements.
13585 @item ^-e^/NO_MISSED_LABELS^
13586 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13587 Do not insert missing end/exit labels. An end label is the name of
13588 a construct that may optionally be repeated at the end of the
13589 construct's declaration;
13590 e.g., the names of packages, subprograms, and tasks.
13591 An exit label is the name of a loop that may appear as target
13592 of an exit statement within the loop.
13593 By default, @command{gnatpp} inserts these end/exit labels when
13594 they are absent from the original source. This option suppresses such
13595 insertion, so that the formatted source reflects the original.
13597 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13598 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13599 Insert a Form Feed character after a pragma Page.
13601 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13602 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13603 Do not use an additional indentation level for @b{case} alternatives
13604 and variants if there are @var{nnn} or more (the default
13606 If @var{nnn} is 0, an additional indentation level is
13607 used for @b{case} alternatives and variants regardless of their number.
13609 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
13610 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
13611 If the number of parameter associations is greater than @var{nnn} and if at
13612 least one association uses named notation, start each association from
13613 a new line. If @var{nnn} is 0, no check for the number of associations
13614 is made, this is the default.
13616 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
13617 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
13618 If the number of parameter specifications is greater than @var{nnn}
13619 (or equal to @var{nnn} in case of a function), start each specification from
13620 a new line. The default for @var{nnn} is 3.
13623 @node Setting the Source Search Path
13624 @subsection Setting the Source Search Path
13627 To define the search path for the input source file, @command{gnatpp}
13628 uses the same switches as the GNAT compiler, with the same effects.
13631 @item ^-I^/SEARCH=^@var{dir}
13632 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13633 The same as the corresponding gcc switch
13635 @item ^-I-^/NOCURRENT_DIRECTORY^
13636 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13637 The same as the corresponding gcc switch
13639 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13640 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13641 The same as the corresponding gcc switch
13643 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13644 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13645 The same as the corresponding gcc switch
13649 @node Output File Control
13650 @subsection Output File Control
13653 By default the output is sent to the file whose name is obtained by appending
13654 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13655 (if the file with this name already exists, it is unconditionally overwritten).
13656 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13657 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13659 The output may be redirected by the following switches:
13662 @item ^-pipe^/STANDARD_OUTPUT^
13663 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13664 Send the output to @code{Standard_Output}
13666 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13667 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13668 Write the output into @var{output_file}.
13669 If @var{output_file} already exists, @command{gnatpp} terminates without
13670 reading or processing the input file.
13672 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13673 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13674 Write the output into @var{output_file}, overwriting the existing file
13675 (if one is present).
13677 @item ^-r^/REPLACE^
13678 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13679 Replace the input source file with the reformatted output, and copy the
13680 original input source into the file whose name is obtained by appending the
13681 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13682 If a file with this name already exists, @command{gnatpp} terminates without
13683 reading or processing the input file.
13685 @item ^-rf^/OVERRIDING_REPLACE^
13686 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13687 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13688 already exists, it is overwritten.
13690 @item ^-rnb^/REPLACE_NO_BACKUP^
13691 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13692 Replace the input source file with the reformatted output without
13693 creating any backup copy of the input source.
13695 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13696 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13697 Specifies the format of the reformatted output file. The @var{xxx}
13698 ^string specified with the switch^option^ may be either
13700 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13701 @item ``@option{^crlf^CRLF^}''
13702 the same as @option{^crlf^CRLF^}
13703 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13704 @item ``@option{^lf^LF^}''
13705 the same as @option{^unix^UNIX^}
13708 @item ^-W^/RESULT_ENCODING=^@var{e}
13709 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13710 Specify the wide character encoding method used to write the code in the
13712 @var{e} is one of the following:
13720 Upper half encoding
13722 @item ^s^SHIFT_JIS^
13732 Brackets encoding (default value)
13738 Options @option{^-pipe^/STANDARD_OUTPUT^},
13739 @option{^-o^/OUTPUT^} and
13740 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13741 contains only one file to reformat.
13743 @option{^--eol^/END_OF_LINE^}
13745 @option{^-W^/RESULT_ENCODING^}
13746 cannot be used together
13747 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13749 @node Other gnatpp Switches
13750 @subsection Other @code{gnatpp} Switches
13753 The additional @command{gnatpp} switches are defined in this subsection.
13756 @item ^-files @var{filename}^/FILES=@var{filename}^
13757 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13758 Take the argument source files from the specified file. This file should be an
13759 ordinary text file containing file names separated by spaces or
13760 line breaks. You can use this switch more than once in the same call to
13761 @command{gnatpp}. You also can combine this switch with an explicit list of
13764 @item ^-v^/VERBOSE^
13765 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13767 @command{gnatpp} generates version information and then
13768 a trace of the actions it takes to produce or obtain the ASIS tree.
13770 @item ^-w^/WARNINGS^
13771 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13773 @command{gnatpp} generates a warning whenever it cannot provide
13774 a required layout in the result source.
13777 @node Formatting Rules
13778 @section Formatting Rules
13781 The following subsections show how @command{gnatpp} treats ``white space'',
13782 comments, program layout, and name casing.
13783 They provide the detailed descriptions of the switches shown above.
13786 * White Space and Empty Lines::
13787 * Formatting Comments::
13788 * Construct Layout::
13792 @node White Space and Empty Lines
13793 @subsection White Space and Empty Lines
13796 @command{gnatpp} does not have an option to control space characters.
13797 It will add or remove spaces according to the style illustrated by the
13798 examples in the @cite{Ada Reference Manual}.
13800 The only format effectors
13801 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13802 that will appear in the output file are platform-specific line breaks,
13803 and also format effectors within (but not at the end of) comments.
13804 In particular, each horizontal tab character that is not inside
13805 a comment will be treated as a space and thus will appear in the
13806 output file as zero or more spaces depending on
13807 the reformatting of the line in which it appears.
13808 The only exception is a Form Feed character, which is inserted after a
13809 pragma @code{Page} when @option{-ff} is set.
13811 The output file will contain no lines with trailing ``white space'' (spaces,
13814 Empty lines in the original source are preserved
13815 only if they separate declarations or statements.
13816 In such contexts, a
13817 sequence of two or more empty lines is replaced by exactly one empty line.
13818 Note that a blank line will be removed if it separates two ``comment blocks''
13819 (a comment block is a sequence of whole-line comments).
13820 In order to preserve a visual separation between comment blocks, use an
13821 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13822 Likewise, if for some reason you wish to have a sequence of empty lines,
13823 use a sequence of empty comments instead.
13825 @node Formatting Comments
13826 @subsection Formatting Comments
13829 Comments in Ada code are of two kinds:
13832 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13833 ``white space'') on a line
13836 an @emph{end-of-line comment}, which follows some other Ada lexical element
13841 The indentation of a whole-line comment is that of either
13842 the preceding or following line in
13843 the formatted source, depending on switch settings as will be described below.
13845 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13846 between the end of the preceding Ada lexical element and the beginning
13847 of the comment as appear in the original source,
13848 unless either the comment has to be split to
13849 satisfy the line length limitation, or else the next line contains a
13850 whole line comment that is considered a continuation of this end-of-line
13851 comment (because it starts at the same position).
13853 cases, the start of the end-of-line comment is moved right to the nearest
13854 multiple of the indentation level.
13855 This may result in a ``line overflow'' (the right-shifted comment extending
13856 beyond the maximum line length), in which case the comment is split as
13859 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13860 (GNAT-style comment line indentation)
13861 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13862 (reference-manual comment line indentation).
13863 With reference-manual style, a whole-line comment is indented as if it
13864 were a declaration or statement at the same place
13865 (i.e., according to the indentation of the preceding line(s)).
13866 With GNAT style, a whole-line comment that is immediately followed by an
13867 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13868 word @b{begin}, is indented based on the construct that follows it.
13871 @smallexample @c ada
13883 Reference-manual indentation produces:
13885 @smallexample @c ada
13897 while GNAT-style indentation produces:
13899 @smallexample @c ada
13911 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13912 (GNAT style comment beginning) has the following
13917 For each whole-line comment that does not end with two hyphens,
13918 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13919 to ensure that there are at least two spaces between these hyphens and the
13920 first non-blank character of the comment.
13924 For an end-of-line comment, if in the original source the next line is a
13925 whole-line comment that starts at the same position
13926 as the end-of-line comment,
13927 then the whole-line comment (and all whole-line comments
13928 that follow it and that start at the same position)
13929 will start at this position in the output file.
13932 That is, if in the original source we have:
13934 @smallexample @c ada
13937 A := B + C; -- B must be in the range Low1..High1
13938 -- C must be in the range Low2..High2
13939 --B+C will be in the range Low1+Low2..High1+High2
13945 Then in the formatted source we get
13947 @smallexample @c ada
13950 A := B + C; -- B must be in the range Low1..High1
13951 -- C must be in the range Low2..High2
13952 -- B+C will be in the range Low1+Low2..High1+High2
13958 A comment that exceeds the line length limit will be split.
13960 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13961 the line belongs to a reformattable block, splitting the line generates a
13962 @command{gnatpp} warning.
13963 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13964 comments may be reformatted in typical
13965 word processor style (that is, moving words between lines and putting as
13966 many words in a line as possible).
13969 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13970 that has a special format (that is, a character that is neither a letter nor digit
13971 not white space nor line break immediately following the leading @code{--} of
13972 the comment) should be without any change moved from the argument source
13973 into reformatted source. This switch allows to preserve comments that are used
13974 as a special marks in the code (e.g.@: SPARK annotation).
13976 @node Construct Layout
13977 @subsection Construct Layout
13980 In several cases the suggested layout in the Ada Reference Manual includes
13981 an extra level of indentation that many programmers prefer to avoid. The
13982 affected cases include:
13986 @item Record type declaration (RM 3.8)
13988 @item Record representation clause (RM 13.5.1)
13990 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13992 @item Block statement in case if a block has a statement identifier (RM 5.6)
13996 In compact mode (when GNAT style layout or compact layout is set),
13997 the pretty printer uses one level of indentation instead
13998 of two. This is achieved in the record definition and record representation
13999 clause cases by putting the @code{record} keyword on the same line as the
14000 start of the declaration or representation clause, and in the block and loop
14001 case by putting the block or loop header on the same line as the statement
14005 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14006 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14007 layout on the one hand, and uncompact layout
14008 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14009 can be illustrated by the following examples:
14013 @multitable @columnfractions .5 .5
14014 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14017 @smallexample @c ada
14024 @smallexample @c ada
14033 @smallexample @c ada
14035 a at 0 range 0 .. 31;
14036 b at 4 range 0 .. 31;
14040 @smallexample @c ada
14043 a at 0 range 0 .. 31;
14044 b at 4 range 0 .. 31;
14049 @smallexample @c ada
14057 @smallexample @c ada
14067 @smallexample @c ada
14068 Clear : for J in 1 .. 10 loop
14073 @smallexample @c ada
14075 for J in 1 .. 10 loop
14086 GNAT style, compact layout Uncompact layout
14088 type q is record type q is
14089 a : integer; record
14090 b : integer; a : integer;
14091 end record; b : integer;
14094 for q use record for q use
14095 a at 0 range 0 .. 31; record
14096 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
14097 end record; b at 4 range 0 .. 31;
14100 Block : declare Block :
14101 A : Integer := 3; declare
14102 begin A : Integer := 3;
14104 end Block; Proc (A, A);
14107 Clear : for J in 1 .. 10 loop Clear :
14108 A (J) := 0; for J in 1 .. 10 loop
14109 end loop Clear; A (J) := 0;
14116 A further difference between GNAT style layout and compact layout is that
14117 GNAT style layout inserts empty lines as separation for
14118 compound statements, return statements and bodies.
14120 Note that the layout specified by
14121 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14122 for named block and loop statements overrides the layout defined by these
14123 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14124 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14125 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14128 @subsection Name Casing
14131 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14132 the same casing as the corresponding defining identifier.
14134 You control the casing for defining occurrences via the
14135 @option{^-n^/NAME_CASING^} switch.
14137 With @option{-nD} (``as declared'', which is the default),
14140 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14142 defining occurrences appear exactly as in the source file
14143 where they are declared.
14144 The other ^values for this switch^options for this qualifier^ ---
14145 @option{^-nU^UPPER_CASE^},
14146 @option{^-nL^LOWER_CASE^},
14147 @option{^-nM^MIXED_CASE^} ---
14149 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14150 If @command{gnatpp} changes the casing of a defining
14151 occurrence, it analogously changes the casing of all the
14152 usage occurrences of this name.
14154 If the defining occurrence of a name is not in the source compilation unit
14155 currently being processed by @command{gnatpp}, the casing of each reference to
14156 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14157 switch (subject to the dictionary file mechanism described below).
14158 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14160 casing for the defining occurrence of the name.
14162 Some names may need to be spelled with casing conventions that are not
14163 covered by the upper-, lower-, and mixed-case transformations.
14164 You can arrange correct casing by placing such names in a
14165 @emph{dictionary file},
14166 and then supplying a @option{^-D^/DICTIONARY^} switch.
14167 The casing of names from dictionary files overrides
14168 any @option{^-n^/NAME_CASING^} switch.
14170 To handle the casing of Ada predefined names and the names from GNAT libraries,
14171 @command{gnatpp} assumes a default dictionary file.
14172 The name of each predefined entity is spelled with the same casing as is used
14173 for the entity in the @cite{Ada Reference Manual}.
14174 The name of each entity in the GNAT libraries is spelled with the same casing
14175 as is used in the declaration of that entity.
14177 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14178 default dictionary file.
14179 Instead, the casing for predefined and GNAT-defined names will be established
14180 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14181 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14182 will appear as just shown,
14183 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14184 To ensure that even such names are rendered in uppercase,
14185 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14186 (or else, less conveniently, place these names in upper case in a dictionary
14189 A dictionary file is
14190 a plain text file; each line in this file can be either a blank line
14191 (containing only space characters and ASCII.HT characters), an Ada comment
14192 line, or the specification of exactly one @emph{casing schema}.
14194 A casing schema is a string that has the following syntax:
14198 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14200 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14205 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14206 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14208 The casing schema string can be followed by white space and/or an Ada-style
14209 comment; any amount of white space is allowed before the string.
14211 If a dictionary file is passed as
14213 the value of a @option{-D@var{file}} switch
14216 an option to the @option{/DICTIONARY} qualifier
14219 simple name and every identifier, @command{gnatpp} checks if the dictionary
14220 defines the casing for the name or for some of its parts (the term ``subword''
14221 is used below to denote the part of a name which is delimited by ``_'' or by
14222 the beginning or end of the word and which does not contain any ``_'' inside):
14226 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14227 the casing defined by the dictionary; no subwords are checked for this word
14230 for every subword @command{gnatpp} checks if the dictionary contains the
14231 corresponding string of the form @code{*@var{simple_identifier}*},
14232 and if it does, the casing of this @var{simple_identifier} is used
14236 if the whole name does not contain any ``_'' inside, and if for this name
14237 the dictionary contains two entries - one of the form @var{identifier},
14238 and another - of the form *@var{simple_identifier}*, then the first one
14239 is applied to define the casing of this name
14242 if more than one dictionary file is passed as @command{gnatpp} switches, each
14243 dictionary adds new casing exceptions and overrides all the existing casing
14244 exceptions set by the previous dictionaries
14247 when @command{gnatpp} checks if the word or subword is in the dictionary,
14248 this check is not case sensitive
14252 For example, suppose we have the following source to reformat:
14254 @smallexample @c ada
14257 name1 : integer := 1;
14258 name4_name3_name2 : integer := 2;
14259 name2_name3_name4 : Boolean;
14262 name2_name3_name4 := name4_name3_name2 > name1;
14268 And suppose we have two dictionaries:
14285 If @command{gnatpp} is called with the following switches:
14289 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14292 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14297 then we will get the following name casing in the @command{gnatpp} output:
14299 @smallexample @c ada
14302 NAME1 : Integer := 1;
14303 Name4_NAME3_Name2 : Integer := 2;
14304 Name2_NAME3_Name4 : Boolean;
14307 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14312 @c *********************************
14313 @node The GNAT Metric Tool gnatmetric
14314 @chapter The GNAT Metric Tool @command{gnatmetric}
14316 @cindex Metric tool
14319 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14320 for computing various program metrics.
14321 It takes an Ada source file as input and generates a file containing the
14322 metrics data as output. Various switches control which
14323 metrics are computed and output.
14325 @command{gnatmetric} generates and uses the ASIS
14326 tree for the input source and thus requires the input to be syntactically and
14327 semantically legal.
14328 If this condition is not met, @command{gnatmetric} will generate
14329 an error message; no metric information for this file will be
14330 computed and reported.
14332 If the compilation unit contained in the input source depends semantically
14333 upon units in files located outside the current directory, you have to provide
14334 the source search path when invoking @command{gnatmetric}.
14335 If it depends semantically upon units that are contained
14336 in files with names that do not follow the GNAT file naming rules, you have to
14337 provide the configuration file describing the corresponding naming scheme (see
14338 the description of the @command{gnatmetric} switches below.)
14339 Alternatively, you may use a project file and invoke @command{gnatmetric}
14340 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14342 The @command{gnatmetric} command has the form
14345 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14346 @c Expanding @ovar macro inline (explanation in macro def comments)
14347 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14354 @var{switches} specify the metrics to compute and define the destination for
14358 Each @var{filename} is the name (including the extension) of a source
14359 file to process. ``Wildcards'' are allowed, and
14360 the file name may contain path information.
14361 If no @var{filename} is supplied, then the @var{switches} list must contain
14363 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14364 Including both a @option{-files} switch and one or more
14365 @var{filename} arguments is permitted.
14368 @samp{@var{gcc_switches}} is a list of switches for
14369 @command{gcc}. They will be passed on to all compiler invocations made by
14370 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14371 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14372 and use the @option{-gnatec} switch to set the configuration file,
14373 use the @option{-gnat05} switch if sources should be compiled in
14378 * Switches for gnatmetric::
14381 @node Switches for gnatmetric
14382 @section Switches for @command{gnatmetric}
14385 The following subsections describe the various switches accepted by
14386 @command{gnatmetric}, organized by category.
14389 * Output Files Control::
14390 * Disable Metrics For Local Units::
14391 * Specifying a set of metrics to compute::
14392 * Other gnatmetric Switches::
14393 * Generate project-wide metrics::
14396 @node Output Files Control
14397 @subsection Output File Control
14398 @cindex Output file control in @command{gnatmetric}
14401 @command{gnatmetric} has two output formats. It can generate a
14402 textual (human-readable) form, and also XML. By default only textual
14403 output is generated.
14405 When generating the output in textual form, @command{gnatmetric} creates
14406 for each Ada source file a corresponding text file
14407 containing the computed metrics, except for the case when the set of metrics
14408 specified by gnatmetric parameters consists only of metrics that are computed
14409 for the whole set of analyzed sources, but not for each Ada source.
14410 By default, this file is placed in the same directory as where the source
14411 file is located, and its name is obtained
14412 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14415 All the output information generated in XML format is placed in a single
14416 file. By default this file is placed in the current directory and has the
14417 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14419 Some of the computed metrics are summed over the units passed to
14420 @command{gnatmetric}; for example, the total number of lines of code.
14421 By default this information is sent to @file{stdout}, but a file
14422 can be specified with the @option{-og} switch.
14424 The following switches control the @command{gnatmetric} output:
14427 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14429 Generate the XML output
14431 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14433 Generate the XML output and the XML schema file that describes the structure
14434 of the XML metric report, this schema is assigned to the XML file. The schema
14435 file has the same name as the XML output file with @file{.xml} suffix replaced
14438 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14439 @item ^-nt^/NO_TEXT^
14440 Do not generate the output in text form (implies @option{^-x^/XML^})
14442 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14443 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14444 Put text files with detailed metrics into @var{output_dir}
14446 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14447 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14448 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14449 in the name of the output file.
14451 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14452 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14453 Put global metrics into @var{file_name}
14455 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14456 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14457 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14459 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14460 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14461 Use ``short'' source file names in the output. (The @command{gnatmetric}
14462 output includes the name(s) of the Ada source file(s) from which the metrics
14463 are computed. By default each name includes the absolute path. The
14464 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14465 to exclude all directory information from the file names that are output.)
14469 @node Disable Metrics For Local Units
14470 @subsection Disable Metrics For Local Units
14471 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14474 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14476 unit per one source file. It computes line metrics for the whole source
14477 file, and it also computes syntax
14478 and complexity metrics for the file's outermost unit.
14480 By default, @command{gnatmetric} will also compute all metrics for certain
14481 kinds of locally declared program units:
14485 subprogram (and generic subprogram) bodies;
14488 package (and generic package) specs and bodies;
14491 task object and type specifications and bodies;
14494 protected object and type specifications and bodies.
14498 These kinds of entities will be referred to as
14499 @emph{eligible local program units}, or simply @emph{eligible local units},
14500 @cindex Eligible local unit (for @command{gnatmetric})
14501 in the discussion below.
14503 Note that a subprogram declaration, generic instantiation,
14504 or renaming declaration only receives metrics
14505 computation when it appear as the outermost entity
14508 Suppression of metrics computation for eligible local units can be
14509 obtained via the following switch:
14512 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14513 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14514 Do not compute detailed metrics for eligible local program units
14518 @node Specifying a set of metrics to compute
14519 @subsection Specifying a set of metrics to compute
14522 By default all the metrics are computed and reported. The switches
14523 described in this subsection allow you to control, on an individual
14524 basis, whether metrics are computed and
14525 reported. If at least one positive metric
14526 switch is specified (that is, a switch that defines that a given
14527 metric or set of metrics is to be computed), then only
14528 explicitly specified metrics are reported.
14531 * Line Metrics Control::
14532 * Syntax Metrics Control::
14533 * Complexity Metrics Control::
14534 * Coupling Metrics Control::
14537 @node Line Metrics Control
14538 @subsubsection Line Metrics Control
14539 @cindex Line metrics control in @command{gnatmetric}
14542 For any (legal) source file, and for each of its
14543 eligible local program units, @command{gnatmetric} computes the following
14548 the total number of lines;
14551 the total number of code lines (i.e., non-blank lines that are not comments)
14554 the number of comment lines
14557 the number of code lines containing end-of-line comments;
14560 the comment percentage: the ratio between the number of lines that contain
14561 comments and the number of all non-blank lines, expressed as a percentage;
14564 the number of empty lines and lines containing only space characters and/or
14565 format effectors (blank lines)
14568 the average number of code lines in subprogram bodies, task bodies, entry
14569 bodies and statement sequences in package bodies (this metric is only computed
14570 across the whole set of the analyzed units)
14575 @command{gnatmetric} sums the values of the line metrics for all the
14576 files being processed and then generates the cumulative results. The tool
14577 also computes for all the files being processed the average number of code
14580 You can use the following switches to select the specific line metrics
14581 to be computed and reported.
14584 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14587 @cindex @option{--no-lines@var{x}}
14590 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14591 Report all the line metrics
14593 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14594 Do not report any of line metrics
14596 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14597 Report the number of all lines
14599 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14600 Do not report the number of all lines
14602 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14603 Report the number of code lines
14605 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14606 Do not report the number of code lines
14608 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14609 Report the number of comment lines
14611 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14612 Do not report the number of comment lines
14614 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14615 Report the number of code lines containing
14616 end-of-line comments
14618 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14619 Do not report the number of code lines containing
14620 end-of-line comments
14622 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14623 Report the comment percentage in the program text
14625 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14626 Do not report the comment percentage in the program text
14628 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14629 Report the number of blank lines
14631 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14632 Do not report the number of blank lines
14634 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14635 Report the average number of code lines in subprogram bodies, task bodies,
14636 entry bodies and statement sequences in package bodies. The metric is computed
14637 and reported for the whole set of processed Ada sources only.
14639 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14640 Do not report the average number of code lines in subprogram bodies,
14641 task bodies, entry bodies and statement sequences in package bodies.
14645 @node Syntax Metrics Control
14646 @subsubsection Syntax Metrics Control
14647 @cindex Syntax metrics control in @command{gnatmetric}
14650 @command{gnatmetric} computes various syntactic metrics for the
14651 outermost unit and for each eligible local unit:
14654 @item LSLOC (``Logical Source Lines Of Code'')
14655 The total number of declarations and the total number of statements. Note
14656 that the definition of declarations is the one given in the reference
14660 ``Each of the following is defined to be a declaration: any basic_declaration;
14661 an enumeration_literal_specification; a discriminant_specification;
14662 a component_declaration; a loop_parameter_specification; a
14663 parameter_specification; a subprogram_body; an entry_declaration;
14664 an entry_index_specification; a choice_parameter_specification;
14665 a generic_formal_parameter_declaration.''
14667 This means for example that each enumeration literal adds one to the count,
14668 as well as each subprogram parameter.
14670 Thus the results from this metric will be significantly greater than might
14671 be expected from a naive view of counting semicolons.
14673 @item Maximal static nesting level of inner program units
14675 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14676 package, a task unit, a protected unit, a
14677 protected entry, a generic unit, or an explicitly declared subprogram other
14678 than an enumeration literal.''
14680 @item Maximal nesting level of composite syntactic constructs
14681 This corresponds to the notion of the
14682 maximum nesting level in the GNAT built-in style checks
14683 (@pxref{Style Checking})
14687 For the outermost unit in the file, @command{gnatmetric} additionally computes
14688 the following metrics:
14691 @item Public subprograms
14692 This metric is computed for package specs. It is the
14693 number of subprograms and generic subprograms declared in the visible
14694 part (including the visible part of nested packages, protected objects, and
14697 @item All subprograms
14698 This metric is computed for bodies and subunits. The
14699 metric is equal to a total number of subprogram bodies in the compilation
14701 Neither generic instantiations nor renamings-as-a-body nor body stubs
14702 are counted. Any subprogram body is counted, independently of its nesting
14703 level and enclosing constructs. Generic bodies and bodies of protected
14704 subprograms are counted in the same way as ``usual'' subprogram bodies.
14707 This metric is computed for package specs and
14708 generic package declarations. It is the total number of types
14709 that can be referenced from outside this compilation unit, plus the
14710 number of types from all the visible parts of all the visible generic
14711 packages. Generic formal types are not counted. Only types, not subtypes,
14715 Along with the total number of public types, the following
14716 types are counted and reported separately:
14723 Root tagged types (abstract, non-abstract, private, non-private). Type
14724 extensions are @emph{not} counted
14727 Private types (including private extensions)
14738 This metric is computed for any compilation unit. It is equal to the total
14739 number of the declarations of different types given in the compilation unit.
14740 The private and the corresponding full type declaration are counted as one
14741 type declaration. Incomplete type declarations and generic formal types
14743 No distinction is made among different kinds of types (abstract,
14744 private etc.); the total number of types is computed and reported.
14749 By default, all the syntax metrics are computed and reported. You can use the
14750 following switches to select specific syntax metrics.
14754 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14757 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14760 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14761 Report all the syntax metrics
14763 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14764 Do not report any of syntax metrics
14766 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14767 Report the total number of declarations
14769 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14770 Do not report the total number of declarations
14772 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14773 Report the total number of statements
14775 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14776 Do not report the total number of statements
14778 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14779 Report the number of public subprograms in a compilation unit
14781 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14782 Do not report the number of public subprograms in a compilation unit
14784 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14785 Report the number of all the subprograms in a compilation unit
14787 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14788 Do not report the number of all the subprograms in a compilation unit
14790 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14791 Report the number of public types in a compilation unit
14793 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14794 Do not report the number of public types in a compilation unit
14796 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14797 Report the number of all the types in a compilation unit
14799 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14800 Do not report the number of all the types in a compilation unit
14802 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14803 Report the maximal program unit nesting level
14805 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14806 Do not report the maximal program unit nesting level
14808 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14809 Report the maximal construct nesting level
14811 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14812 Do not report the maximal construct nesting level
14816 @node Complexity Metrics Control
14817 @subsubsection Complexity Metrics Control
14818 @cindex Complexity metrics control in @command{gnatmetric}
14821 For a program unit that is an executable body (a subprogram body (including
14822 generic bodies), task body, entry body or a package body containing
14823 its own statement sequence) @command{gnatmetric} computes the following
14824 complexity metrics:
14828 McCabe cyclomatic complexity;
14831 McCabe essential complexity;
14834 maximal loop nesting level;
14837 extra exit points (for subprograms);
14841 The McCabe cyclomatic complexity metric is defined
14842 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14844 According to McCabe, both control statements and short-circuit control forms
14845 should be taken into account when computing cyclomatic complexity. For each
14846 body, we compute three metric values:
14850 the complexity introduced by control
14851 statements only, without taking into account short-circuit forms,
14854 the complexity introduced by short-circuit control forms only, and
14858 cyclomatic complexity, which is the sum of these two values.
14863 The origin of cyclomatic complexity metric is the need to estimate the number
14864 of independent paths in the control flow graph that in turn gives the number
14865 of tests needed to satisfy paths coverage testing completeness criterion.
14866 Considered from the testing point of view, a static Ada @code{loop} (that is,
14867 the @code{loop} statement having static subtype in loop parameter
14868 specification) does not add to cyclomatic complexity. By providing
14869 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14870 may specify that such loops should not be counted when computing the
14871 cyclomatic complexity metric
14873 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14874 counted for the code that is reduced by excluding all the pure structural Ada
14875 control statements. An compound statement is considered as a non-structural
14876 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14877 or if it contains a @code{goto} statement that transfers the control outside
14878 the operator. A selective accept statement with @code{terminate} alternative
14879 is considered as non-structural statement. When computing this metric,
14880 @code{exit} statements are treated in the same way as @code{goto}
14881 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14883 The Ada essential complexity metric defined here is intended to quantify
14884 the extent to which the software is unstructured. It is adapted from
14885 the McCabe essential complexity metric defined in
14886 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
14887 suitable for typical Ada usage. For example, short circuit forms
14888 are not penalized as unstructured in the Ada essential complexity metric.
14890 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14891 the code in the exception handlers and in all the nested program units.
14893 By default, all the complexity metrics are computed and reported.
14894 For more fine-grained control you can use
14895 the following switches:
14898 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14901 @cindex @option{--no-complexity@var{x}}
14904 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14905 Report all the complexity metrics
14907 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14908 Do not report any of complexity metrics
14910 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14911 Report the McCabe Cyclomatic Complexity
14913 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14914 Do not report the McCabe Cyclomatic Complexity
14916 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14917 Report the Essential Complexity
14919 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14920 Do not report the Essential Complexity
14922 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14923 Report maximal loop nesting level
14925 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14926 Do not report maximal loop nesting level
14928 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14929 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14930 task bodies, entry bodies and statement sequences in package bodies.
14931 The metric is computed and reported for whole set of processed Ada sources
14934 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14935 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14936 bodies, task bodies, entry bodies and statement sequences in package bodies
14938 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14939 @item ^-ne^/NO_EXITS_AS_GOTOS^
14940 Do not consider @code{exit} statements as @code{goto}s when
14941 computing Essential Complexity
14943 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14944 @item ^--no-static-loop^/NO_STATIC_LOOP^
14945 Do not consider static loops when computing cyclomatic complexity
14947 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14948 Report the extra exit points for subprogram bodies. As an exit point, this
14949 metric counts @code{return} statements and raise statements in case when the
14950 raised exception is not handled in the same body. In case of a function this
14951 metric subtracts 1 from the number of exit points, because a function body
14952 must contain at least one @code{return} statement.
14954 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14955 Do not report the extra exit points for subprogram bodies
14959 @node Coupling Metrics Control
14960 @subsubsection Coupling Metrics Control
14961 @cindex Coupling metrics control in @command{gnatmetric}
14964 @cindex Coupling metrics (in in @command{gnatmetric})
14965 Coupling metrics measure the dependencies between a given entity and other
14966 entities the program consists of. The goal of these metrics is to estimate the
14967 stability of the whole program considered as the collection of entities
14968 (modules, classes etc.).
14970 Gnatmetric computes the following coupling metrics:
14975 @emph{object-oriented coupling} - for classes in traditional object-oriented
14979 @emph{unit coupling} - for all the program units making up a program;
14982 @emph{control coupling} - this metric counts dependencies between a unit and
14983 only those units that define subprograms;
14987 Two kinds of coupling metrics are computed:
14990 @item fan-out coupling (efferent coupling)
14991 @cindex fan-out coupling
14992 @cindex efferent coupling
14993 the number of entities the given entity depends upon. It
14994 estimates in what extent the given entity depends on the changes in
14997 @item fan-in coupling (afferent coupling)
14998 @cindex fan-in coupling
14999 @cindex afferent coupling
15000 the number of entities that depend on a given entity.
15001 It estimates in what extent the ``external world'' depends on the changes in a
15007 Object-oriented coupling metrics are metrics that measure the dependencies
15008 between a given class (or a group of classes) and the other classes in the
15009 program. In this subsection the term ``class'' is used in its traditional
15010 object-oriented programming sense (an instantiable module that contains data
15011 and/or method members). A @emph{category} (of classes) is a group of closely
15012 related classes that are reused and/or modified together.
15014 A class @code{K}'s fan-out coupling is the number of classes
15015 that @code{K} depends upon.
15016 A category's fan-out coupling is the number of classes outside the
15017 category that the classes inside the category depend upon.
15019 A class @code{K}'s fan-in coupling is the number of classes
15020 that depend upon @code{K}.
15021 A category's fan-in coupling is the number of classes outside the
15022 category that depend on classes belonging to the category.
15024 Ada's implementation of the object-oriented paradigm does not use the
15025 traditional class notion, so the definition of the coupling
15026 metrics for Ada maps the class and class category notions
15027 onto Ada constructs.
15029 For the coupling metrics, several kinds of modules -- a library package,
15030 a library generic package, and a library generic package instantiation --
15031 that define a tagged type or an interface type are
15032 considered to be a class. A category consists of a library package (or
15033 a library generic package) that defines a tagged or an interface type,
15034 together with all its descendant (generic) packages that define tagged
15035 or interface types. That is a
15036 category is an Ada hierarchy of library-level program units. So class coupling
15037 in case of Ada is called as tagged coupling, and category coupling - as
15038 hierarchy coupling.
15040 For any package counted as a class, its body and subunits (if any) are
15041 considered together with its spec when counting the dependencies, and coupling
15042 metrics are reported for spec units only. For dependencies between classes,
15043 the Ada semantic dependencies are considered. For object-oriented coupling
15044 metrics, only dependencies on units that are considered as classes, are
15047 For unit and control coupling also not compilation units but program units are
15048 counted. That is, for a package, its spec, its body and its subunits (if any)
15049 are considered as making up one unit, and the dependencies that are counted
15050 are the dependencies of all these compilation units collected together as
15051 the dependencies as a (whole) unit. And metrics are reported for spec
15052 compilation units only (or for a subprogram body unit in case if there is no
15053 separate spec for the given subprogram).
15055 For unit coupling, dependencies between all kinds of program units are
15056 considered. For control coupling, for each unit the dependencies of this unit
15057 upon units that define subprograms are counted, so control fan-out coupling
15058 is reported for all units, but control fan-in coupling - only for the units
15059 that define subprograms.
15061 The following simple example illustrates the difference between unit coupling
15062 and control coupling metrics:
15064 @smallexample @c ada
15066 function F_1 (I : Integer) return Integer;
15070 type T_2 is new Integer;
15073 package body Lib_1 is
15074 function F_1 (I : Integer) return Integer is
15080 with Lib_2; use Lib_2;
15083 function Fun (I : Integer) return Integer;
15086 with Lib_1; use Lib_1;
15087 package body Pack is
15088 function Fun (I : Integer) return Integer is
15096 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
15097 units, the result will be:
15102 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15103 control fan-out coupling : 0
15104 control fan-in coupling : 1
15105 unit fan-out coupling : 0
15106 unit fan-in coupling : 1
15108 Unit Pack (C:\customers\662\L406-007\pack.ads)
15109 control fan-out coupling : 1
15110 control fan-in coupling : 0
15111 unit fan-out coupling : 2
15112 unit fan-in coupling : 0
15114 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15115 control fan-out coupling : 0
15116 unit fan-out coupling : 0
15117 unit fan-in coupling : 1
15121 The result does not contain values for object-oriented
15122 coupling because none of the argument unit contains a tagged type and
15123 therefore none of these units can be treated as a class.
15125 @code{Pack} (considered as a program unit, that is spec+body) depends on two
15126 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
15127 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
15128 well as control fan-in coupling. Only one of the units @code{Pack} depends
15129 upon defines a subprogram, so its control fan-out coupling is 1.
15131 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
15132 not define a subprogram, so control fan-in metric cannot be applied to it,
15133 and there is one unit that depends on it (@code{Pack}), so it has
15134 unit fan-in coupling equals to 1.
15136 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15137 So it has control fan-in coupling equals to 1 (because there is a unit
15140 When computing coupling metrics, @command{gnatmetric} counts only
15141 dependencies between units that are arguments of the @command{gnatmetric}
15142 call. Coupling metrics are program-wide (or project-wide) metrics, so to
15143 get a valid result, you should call @command{gnatmetric} for
15144 the whole set of sources that make up your program. It can be done
15145 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
15146 option (see @ref{The GNAT Driver and Project Files} for details).
15148 By default, all the coupling metrics are disabled. You can use the following
15149 switches to specify the coupling metrics to be computed and reported:
15154 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15155 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15156 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15157 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15161 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
15164 @item ^--coupling-all^/COUPLING_METRICS=ALL^
15165 Report all the coupling metrics
15167 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
15168 Report tagged (class) fan-out coupling
15170 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
15171 Report tagged (class) fan-in coupling
15173 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
15174 Report hierarchy (category) fan-out coupling
15176 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
15177 Report hierarchy (category) fan-in coupling
15179 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
15180 Report unit fan-out coupling
15182 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
15183 Report unit fan-in coupling
15185 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
15186 Report control fan-out coupling
15188 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
15189 Report control fan-in coupling
15192 @node Other gnatmetric Switches
15193 @subsection Other @code{gnatmetric} Switches
15196 Additional @command{gnatmetric} switches are as follows:
15199 @item ^-files @var{filename}^/FILES=@var{filename}^
15200 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15201 Take the argument source files from the specified file. This file should be an
15202 ordinary text file containing file names separated by spaces or
15203 line breaks. You can use this switch more than once in the same call to
15204 @command{gnatmetric}. You also can combine this switch with
15205 an explicit list of files.
15207 @item ^-v^/VERBOSE^
15208 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15210 @command{gnatmetric} generates version information and then
15211 a trace of sources being processed.
15214 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15218 @node Generate project-wide metrics
15219 @subsection Generate project-wide metrics
15221 In order to compute metrics on all units of a given project, you can use
15222 the @command{gnat} driver along with the @option{-P} option:
15228 If the project @code{proj} depends upon other projects, you can compute
15229 the metrics on the project closure using the @option{-U} option:
15231 gnat metric -Pproj -U
15235 Finally, if not all the units are relevant to a particular main
15236 program in the project closure, you can generate metrics for the set
15237 of units needed to create a given main program (unit closure) using
15238 the @option{-U} option followed by the name of the main unit:
15240 gnat metric -Pproj -U main
15244 @c ***********************************
15245 @node File Name Krunching Using gnatkr
15246 @chapter File Name Krunching Using @code{gnatkr}
15250 This chapter discusses the method used by the compiler to shorten
15251 the default file names chosen for Ada units so that they do not
15252 exceed the maximum length permitted. It also describes the
15253 @code{gnatkr} utility that can be used to determine the result of
15254 applying this shortening.
15258 * Krunching Method::
15259 * Examples of gnatkr Usage::
15263 @section About @code{gnatkr}
15266 The default file naming rule in GNAT
15267 is that the file name must be derived from
15268 the unit name. The exact default rule is as follows:
15271 Take the unit name and replace all dots by hyphens.
15273 If such a replacement occurs in the
15274 second character position of a name, and the first character is
15275 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15276 then replace the dot by the character
15277 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15278 instead of a minus.
15280 The reason for this exception is to avoid clashes
15281 with the standard names for children of System, Ada, Interfaces,
15282 and GNAT, which use the prefixes
15283 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15286 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15287 switch of the compiler activates a ``krunching''
15288 circuit that limits file names to nn characters (where nn is a decimal
15289 integer). For example, using OpenVMS,
15290 where the maximum file name length is
15291 39, the value of nn is usually set to 39, but if you want to generate
15292 a set of files that would be usable if ported to a system with some
15293 different maximum file length, then a different value can be specified.
15294 The default value of 39 for OpenVMS need not be specified.
15296 The @code{gnatkr} utility can be used to determine the krunched name for
15297 a given file, when krunched to a specified maximum length.
15300 @section Using @code{gnatkr}
15303 The @code{gnatkr} command has the form
15307 @c $ gnatkr @var{name} @ovar{length}
15308 @c Expanding @ovar macro inline (explanation in macro def comments)
15309 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15315 $ gnatkr @var{name} /COUNT=nn
15320 @var{name} is the uncrunched file name, derived from the name of the unit
15321 in the standard manner described in the previous section (i.e., in particular
15322 all dots are replaced by hyphens). The file name may or may not have an
15323 extension (defined as a suffix of the form period followed by arbitrary
15324 characters other than period). If an extension is present then it will
15325 be preserved in the output. For example, when krunching @file{hellofile.ads}
15326 to eight characters, the result will be hellofil.ads.
15328 Note: for compatibility with previous versions of @code{gnatkr} dots may
15329 appear in the name instead of hyphens, but the last dot will always be
15330 taken as the start of an extension. So if @code{gnatkr} is given an argument
15331 such as @file{Hello.World.adb} it will be treated exactly as if the first
15332 period had been a hyphen, and for example krunching to eight characters
15333 gives the result @file{hellworl.adb}.
15335 Note that the result is always all lower case (except on OpenVMS where it is
15336 all upper case). Characters of the other case are folded as required.
15338 @var{length} represents the length of the krunched name. The default
15339 when no argument is given is ^8^39^ characters. A length of zero stands for
15340 unlimited, in other words do not chop except for system files where the
15341 implied crunching length is always eight characters.
15344 The output is the krunched name. The output has an extension only if the
15345 original argument was a file name with an extension.
15347 @node Krunching Method
15348 @section Krunching Method
15351 The initial file name is determined by the name of the unit that the file
15352 contains. The name is formed by taking the full expanded name of the
15353 unit and replacing the separating dots with hyphens and
15354 using ^lowercase^uppercase^
15355 for all letters, except that a hyphen in the second character position is
15356 replaced by a ^tilde^dollar sign^ if the first character is
15357 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15358 The extension is @code{.ads} for a
15359 spec and @code{.adb} for a body.
15360 Krunching does not affect the extension, but the file name is shortened to
15361 the specified length by following these rules:
15365 The name is divided into segments separated by hyphens, tildes or
15366 underscores and all hyphens, tildes, and underscores are
15367 eliminated. If this leaves the name short enough, we are done.
15370 If the name is too long, the longest segment is located (left-most
15371 if there are two of equal length), and shortened by dropping
15372 its last character. This is repeated until the name is short enough.
15374 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15375 to fit the name into 8 characters as required by some operating systems.
15378 our-strings-wide_fixed 22
15379 our strings wide fixed 19
15380 our string wide fixed 18
15381 our strin wide fixed 17
15382 our stri wide fixed 16
15383 our stri wide fixe 15
15384 our str wide fixe 14
15385 our str wid fixe 13
15391 Final file name: oustwifi.adb
15395 The file names for all predefined units are always krunched to eight
15396 characters. The krunching of these predefined units uses the following
15397 special prefix replacements:
15401 replaced by @file{^a^A^-}
15404 replaced by @file{^g^G^-}
15407 replaced by @file{^i^I^-}
15410 replaced by @file{^s^S^-}
15413 These system files have a hyphen in the second character position. That
15414 is why normal user files replace such a character with a
15415 ^tilde^dollar sign^, to
15416 avoid confusion with system file names.
15418 As an example of this special rule, consider
15419 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15422 ada-strings-wide_fixed 22
15423 a- strings wide fixed 18
15424 a- string wide fixed 17
15425 a- strin wide fixed 16
15426 a- stri wide fixed 15
15427 a- stri wide fixe 14
15428 a- str wide fixe 13
15434 Final file name: a-stwifi.adb
15438 Of course no file shortening algorithm can guarantee uniqueness over all
15439 possible unit names, and if file name krunching is used then it is your
15440 responsibility to ensure that no name clashes occur. The utility
15441 program @code{gnatkr} is supplied for conveniently determining the
15442 krunched name of a file.
15444 @node Examples of gnatkr Usage
15445 @section Examples of @code{gnatkr} Usage
15452 $ gnatkr very_long_unit_name.ads --> velounna.ads
15453 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15454 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15455 $ gnatkr grandparent-parent-child --> grparchi
15457 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15458 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15461 @node Preprocessing Using gnatprep
15462 @chapter Preprocessing Using @code{gnatprep}
15466 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15468 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15469 special GNAT features.
15470 For further discussion of conditional compilation in general, see
15471 @ref{Conditional Compilation}.
15474 * Preprocessing Symbols::
15476 * Switches for gnatprep::
15477 * Form of Definitions File::
15478 * Form of Input Text for gnatprep::
15481 @node Preprocessing Symbols
15482 @section Preprocessing Symbols
15485 Preprocessing symbols are defined in definition files and referred to in
15486 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15487 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15488 all characters need to be in the ASCII set (no accented letters).
15490 @node Using gnatprep
15491 @section Using @code{gnatprep}
15494 To call @code{gnatprep} use
15497 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15498 @c Expanding @ovar macro inline (explanation in macro def comments)
15499 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15506 is an optional sequence of switches as described in the next section.
15509 is the full name of the input file, which is an Ada source
15510 file containing preprocessor directives.
15513 is the full name of the output file, which is an Ada source
15514 in standard Ada form. When used with GNAT, this file name will
15515 normally have an ads or adb suffix.
15518 is the full name of a text file containing definitions of
15519 preprocessing symbols to be referenced by the preprocessor. This argument is
15520 optional, and can be replaced by the use of the @option{-D} switch.
15524 @node Switches for gnatprep
15525 @section Switches for @code{gnatprep}
15530 @item ^-b^/BLANK_LINES^
15531 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15532 Causes both preprocessor lines and the lines deleted by
15533 preprocessing to be replaced by blank lines in the output source file,
15534 preserving line numbers in the output file.
15536 @item ^-c^/COMMENTS^
15537 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15538 Causes both preprocessor lines and the lines deleted
15539 by preprocessing to be retained in the output source as comments marked
15540 with the special string @code{"--! "}. This option will result in line numbers
15541 being preserved in the output file.
15543 @item ^-C^/REPLACE_IN_COMMENTS^
15544 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15545 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15546 If this option is specified, then comments are scanned and any $symbol
15547 substitutions performed as in program text. This is particularly useful
15548 when structured comments are used (e.g., when writing programs in the
15549 SPARK dialect of Ada). Note that this switch is not available when
15550 doing integrated preprocessing (it would be useless in this context
15551 since comments are ignored by the compiler in any case).
15553 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15554 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15555 Defines a new preprocessing symbol, associated with value. If no value is given
15556 on the command line, then symbol is considered to be @code{True}. This switch
15557 can be used in place of a definition file.
15561 @cindex @option{/REMOVE} (@command{gnatprep})
15562 This is the default setting which causes lines deleted by preprocessing
15563 to be entirely removed from the output file.
15566 @item ^-r^/REFERENCE^
15567 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15568 Causes a @code{Source_Reference} pragma to be generated that
15569 references the original input file, so that error messages will use
15570 the file name of this original file. The use of this switch implies
15571 that preprocessor lines are not to be removed from the file, so its
15572 use will force @option{^-b^/BLANK_LINES^} mode if
15573 @option{^-c^/COMMENTS^}
15574 has not been specified explicitly.
15576 Note that if the file to be preprocessed contains multiple units, then
15577 it will be necessary to @code{gnatchop} the output file from
15578 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15579 in the preprocessed file, it will be respected by
15580 @code{gnatchop ^-r^/REFERENCE^}
15581 so that the final chopped files will correctly refer to the original
15582 input source file for @code{gnatprep}.
15584 @item ^-s^/SYMBOLS^
15585 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15586 Causes a sorted list of symbol names and values to be
15587 listed on the standard output file.
15589 @item ^-u^/UNDEFINED^
15590 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15591 Causes undefined symbols to be treated as having the value FALSE in the context
15592 of a preprocessor test. In the absence of this option, an undefined symbol in
15593 a @code{#if} or @code{#elsif} test will be treated as an error.
15599 Note: if neither @option{-b} nor @option{-c} is present,
15600 then preprocessor lines and
15601 deleted lines are completely removed from the output, unless -r is
15602 specified, in which case -b is assumed.
15605 @node Form of Definitions File
15606 @section Form of Definitions File
15609 The definitions file contains lines of the form
15616 where symbol is a preprocessing symbol, and value is one of the following:
15620 Empty, corresponding to a null substitution
15622 A string literal using normal Ada syntax
15624 Any sequence of characters from the set
15625 (letters, digits, period, underline).
15629 Comment lines may also appear in the definitions file, starting with
15630 the usual @code{--},
15631 and comments may be added to the definitions lines.
15633 @node Form of Input Text for gnatprep
15634 @section Form of Input Text for @code{gnatprep}
15637 The input text may contain preprocessor conditional inclusion lines,
15638 as well as general symbol substitution sequences.
15640 The preprocessor conditional inclusion commands have the form
15645 #if @i{expression} @r{[}then@r{]}
15647 #elsif @i{expression} @r{[}then@r{]}
15649 #elsif @i{expression} @r{[}then@r{]}
15660 In this example, @i{expression} is defined by the following grammar:
15662 @i{expression} ::= <symbol>
15663 @i{expression} ::= <symbol> = "<value>"
15664 @i{expression} ::= <symbol> = <symbol>
15665 @i{expression} ::= <symbol> 'Defined
15666 @i{expression} ::= not @i{expression}
15667 @i{expression} ::= @i{expression} and @i{expression}
15668 @i{expression} ::= @i{expression} or @i{expression}
15669 @i{expression} ::= @i{expression} and then @i{expression}
15670 @i{expression} ::= @i{expression} or else @i{expression}
15671 @i{expression} ::= ( @i{expression} )
15674 The following restriction exists: it is not allowed to have "and" or "or"
15675 following "not" in the same expression without parentheses. For example, this
15682 This should be one of the following:
15690 For the first test (@i{expression} ::= <symbol>) the symbol must have
15691 either the value true or false, that is to say the right-hand of the
15692 symbol definition must be one of the (case-insensitive) literals
15693 @code{True} or @code{False}. If the value is true, then the
15694 corresponding lines are included, and if the value is false, they are
15697 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15698 the symbol has been defined in the definition file or by a @option{-D}
15699 switch on the command line. Otherwise, the test is false.
15701 The equality tests are case insensitive, as are all the preprocessor lines.
15703 If the symbol referenced is not defined in the symbol definitions file,
15704 then the effect depends on whether or not switch @option{-u}
15705 is specified. If so, then the symbol is treated as if it had the value
15706 false and the test fails. If this switch is not specified, then
15707 it is an error to reference an undefined symbol. It is also an error to
15708 reference a symbol that is defined with a value other than @code{True}
15711 The use of the @code{not} operator inverts the sense of this logical test.
15712 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15713 operators, without parentheses. For example, "if not X or Y then" is not
15714 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15716 The @code{then} keyword is optional as shown
15718 The @code{#} must be the first non-blank character on a line, but
15719 otherwise the format is free form. Spaces or tabs may appear between
15720 the @code{#} and the keyword. The keywords and the symbols are case
15721 insensitive as in normal Ada code. Comments may be used on a
15722 preprocessor line, but other than that, no other tokens may appear on a
15723 preprocessor line. Any number of @code{elsif} clauses can be present,
15724 including none at all. The @code{else} is optional, as in Ada.
15726 The @code{#} marking the start of a preprocessor line must be the first
15727 non-blank character on the line, i.e., it must be preceded only by
15728 spaces or horizontal tabs.
15730 Symbol substitution outside of preprocessor lines is obtained by using
15738 anywhere within a source line, except in a comment or within a
15739 string literal. The identifier
15740 following the @code{$} must match one of the symbols defined in the symbol
15741 definition file, and the result is to substitute the value of the
15742 symbol in place of @code{$symbol} in the output file.
15744 Note that although the substitution of strings within a string literal
15745 is not possible, it is possible to have a symbol whose defined value is
15746 a string literal. So instead of setting XYZ to @code{hello} and writing:
15749 Header : String := "$XYZ";
15753 you should set XYZ to @code{"hello"} and write:
15756 Header : String := $XYZ;
15760 and then the substitution will occur as desired.
15762 @node The GNAT Library Browser gnatls
15763 @chapter The GNAT Library Browser @code{gnatls}
15765 @cindex Library browser
15768 @code{gnatls} is a tool that outputs information about compiled
15769 units. It gives the relationship between objects, unit names and source
15770 files. It can also be used to check the source dependencies of a unit
15771 as well as various characteristics.
15773 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15774 driver (see @ref{The GNAT Driver and Project Files}).
15778 * Switches for gnatls::
15779 * Examples of gnatls Usage::
15782 @node Running gnatls
15783 @section Running @code{gnatls}
15786 The @code{gnatls} command has the form
15789 $ gnatls switches @var{object_or_ali_file}
15793 The main argument is the list of object or @file{ali} files
15794 (@pxref{The Ada Library Information Files})
15795 for which information is requested.
15797 In normal mode, without additional option, @code{gnatls} produces a
15798 four-column listing. Each line represents information for a specific
15799 object. The first column gives the full path of the object, the second
15800 column gives the name of the principal unit in this object, the third
15801 column gives the status of the source and the fourth column gives the
15802 full path of the source representing this unit.
15803 Here is a simple example of use:
15807 ^./^[]^demo1.o demo1 DIF demo1.adb
15808 ^./^[]^demo2.o demo2 OK demo2.adb
15809 ^./^[]^hello.o h1 OK hello.adb
15810 ^./^[]^instr-child.o instr.child MOK instr-child.adb
15811 ^./^[]^instr.o instr OK instr.adb
15812 ^./^[]^tef.o tef DIF tef.adb
15813 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
15814 ^./^[]^tgef.o tgef DIF tgef.adb
15818 The first line can be interpreted as follows: the main unit which is
15820 object file @file{demo1.o} is demo1, whose main source is in
15821 @file{demo1.adb}. Furthermore, the version of the source used for the
15822 compilation of demo1 has been modified (DIF). Each source file has a status
15823 qualifier which can be:
15826 @item OK (unchanged)
15827 The version of the source file used for the compilation of the
15828 specified unit corresponds exactly to the actual source file.
15830 @item MOK (slightly modified)
15831 The version of the source file used for the compilation of the
15832 specified unit differs from the actual source file but not enough to
15833 require recompilation. If you use gnatmake with the qualifier
15834 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15835 MOK will not be recompiled.
15837 @item DIF (modified)
15838 No version of the source found on the path corresponds to the source
15839 used to build this object.
15841 @item ??? (file not found)
15842 No source file was found for this unit.
15844 @item HID (hidden, unchanged version not first on PATH)
15845 The version of the source that corresponds exactly to the source used
15846 for compilation has been found on the path but it is hidden by another
15847 version of the same source that has been modified.
15851 @node Switches for gnatls
15852 @section Switches for @code{gnatls}
15855 @code{gnatls} recognizes the following switches:
15859 @cindex @option{--version} @command{gnatls}
15860 Display Copyright and version, then exit disregarding all other options.
15863 @cindex @option{--help} @command{gnatls}
15864 If @option{--version} was not used, display usage, then exit disregarding
15867 @item ^-a^/ALL_UNITS^
15868 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15869 Consider all units, including those of the predefined Ada library.
15870 Especially useful with @option{^-d^/DEPENDENCIES^}.
15872 @item ^-d^/DEPENDENCIES^
15873 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15874 List sources from which specified units depend on.
15876 @item ^-h^/OUTPUT=OPTIONS^
15877 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15878 Output the list of options.
15880 @item ^-o^/OUTPUT=OBJECTS^
15881 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15882 Only output information about object files.
15884 @item ^-s^/OUTPUT=SOURCES^
15885 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15886 Only output information about source files.
15888 @item ^-u^/OUTPUT=UNITS^
15889 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15890 Only output information about compilation units.
15892 @item ^-files^/FILES^=@var{file}
15893 @cindex @option{^-files^/FILES^} (@code{gnatls})
15894 Take as arguments the files listed in text file @var{file}.
15895 Text file @var{file} may contain empty lines that are ignored.
15896 Each nonempty line should contain the name of an existing file.
15897 Several such switches may be specified simultaneously.
15899 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15900 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15901 @itemx ^-I^/SEARCH=^@var{dir}
15902 @itemx ^-I-^/NOCURRENT_DIRECTORY^
15904 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15905 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15906 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15907 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15908 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15909 flags (@pxref{Switches for gnatmake}).
15911 @item --RTS=@var{rts-path}
15912 @cindex @option{--RTS} (@code{gnatls})
15913 Specifies the default location of the runtime library. Same meaning as the
15914 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15916 @item ^-v^/OUTPUT=VERBOSE^
15917 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15918 Verbose mode. Output the complete source, object and project paths. Do not use
15919 the default column layout but instead use long format giving as much as
15920 information possible on each requested units, including special
15921 characteristics such as:
15924 @item Preelaborable
15925 The unit is preelaborable in the Ada sense.
15928 No elaboration code has been produced by the compiler for this unit.
15931 The unit is pure in the Ada sense.
15933 @item Elaborate_Body
15934 The unit contains a pragma Elaborate_Body.
15937 The unit contains a pragma Remote_Types.
15939 @item Shared_Passive
15940 The unit contains a pragma Shared_Passive.
15943 This unit is part of the predefined environment and cannot be modified
15946 @item Remote_Call_Interface
15947 The unit contains a pragma Remote_Call_Interface.
15953 @node Examples of gnatls Usage
15954 @section Example of @code{gnatls} Usage
15958 Example of using the verbose switch. Note how the source and
15959 object paths are affected by the -I switch.
15962 $ gnatls -v -I.. demo1.o
15964 GNATLS 5.03w (20041123-34)
15965 Copyright 1997-2004 Free Software Foundation, Inc.
15967 Source Search Path:
15968 <Current_Directory>
15970 /home/comar/local/adainclude/
15972 Object Search Path:
15973 <Current_Directory>
15975 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15977 Project Search Path:
15978 <Current_Directory>
15979 /home/comar/local/lib/gnat/
15984 Kind => subprogram body
15985 Flags => No_Elab_Code
15986 Source => demo1.adb modified
15990 The following is an example of use of the dependency list.
15991 Note the use of the -s switch
15992 which gives a straight list of source files. This can be useful for
15993 building specialized scripts.
15996 $ gnatls -d demo2.o
15997 ./demo2.o demo2 OK demo2.adb
16003 $ gnatls -d -s -a demo1.o
16005 /home/comar/local/adainclude/ada.ads
16006 /home/comar/local/adainclude/a-finali.ads
16007 /home/comar/local/adainclude/a-filico.ads
16008 /home/comar/local/adainclude/a-stream.ads
16009 /home/comar/local/adainclude/a-tags.ads
16012 /home/comar/local/adainclude/gnat.ads
16013 /home/comar/local/adainclude/g-io.ads
16015 /home/comar/local/adainclude/system.ads
16016 /home/comar/local/adainclude/s-exctab.ads
16017 /home/comar/local/adainclude/s-finimp.ads
16018 /home/comar/local/adainclude/s-finroo.ads
16019 /home/comar/local/adainclude/s-secsta.ads
16020 /home/comar/local/adainclude/s-stalib.ads
16021 /home/comar/local/adainclude/s-stoele.ads
16022 /home/comar/local/adainclude/s-stratt.ads
16023 /home/comar/local/adainclude/s-tasoli.ads
16024 /home/comar/local/adainclude/s-unstyp.ads
16025 /home/comar/local/adainclude/unchconv.ads
16031 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16033 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16034 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16035 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16036 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16037 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16041 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16042 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16044 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16045 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16046 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16047 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16048 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16049 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16050 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16051 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16052 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16053 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16054 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16058 @node Cleaning Up Using gnatclean
16059 @chapter Cleaning Up Using @code{gnatclean}
16061 @cindex Cleaning tool
16064 @code{gnatclean} is a tool that allows the deletion of files produced by the
16065 compiler, binder and linker, including ALI files, object files, tree files,
16066 expanded source files, library files, interface copy source files, binder
16067 generated files and executable files.
16070 * Running gnatclean::
16071 * Switches for gnatclean::
16072 @c * Examples of gnatclean Usage::
16075 @node Running gnatclean
16076 @section Running @code{gnatclean}
16079 The @code{gnatclean} command has the form:
16082 $ gnatclean switches @var{names}
16086 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16087 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16088 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16091 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16092 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16093 the linker. In informative-only mode, specified by switch
16094 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16095 normal mode is listed, but no file is actually deleted.
16097 @node Switches for gnatclean
16098 @section Switches for @code{gnatclean}
16101 @code{gnatclean} recognizes the following switches:
16105 @cindex @option{--version} @command{gnatclean}
16106 Display Copyright and version, then exit disregarding all other options.
16109 @cindex @option{--help} @command{gnatclean}
16110 If @option{--version} was not used, display usage, then exit disregarding
16113 @item ^--subdirs^/SUBDIRS^=subdir
16114 Actual object directory of each project file is the subdirectory subdir of the
16115 object directory specified or defaulted in the project file.
16117 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
16118 By default, shared library projects are not allowed to import static library
16119 projects. When this switch is used on the command line, this restriction is
16122 @item ^-c^/COMPILER_FILES_ONLY^
16123 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16124 Only attempt to delete the files produced by the compiler, not those produced
16125 by the binder or the linker. The files that are not to be deleted are library
16126 files, interface copy files, binder generated files and executable files.
16128 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16129 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16130 Indicate that ALI and object files should normally be found in directory
16133 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16134 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16135 When using project files, if some errors or warnings are detected during
16136 parsing and verbose mode is not in effect (no use of switch
16137 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16138 file, rather than its simple file name.
16141 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16142 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16144 @item ^-n^/NODELETE^
16145 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16146 Informative-only mode. Do not delete any files. Output the list of the files
16147 that would have been deleted if this switch was not specified.
16149 @item ^-P^/PROJECT_FILE=^@var{project}
16150 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16151 Use project file @var{project}. Only one such switch can be used.
16152 When cleaning a project file, the files produced by the compilation of the
16153 immediate sources or inherited sources of the project files are to be
16154 deleted. This is not depending on the presence or not of executable names
16155 on the command line.
16158 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16159 Quiet output. If there are no errors, do not output anything, except in
16160 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16161 (switch ^-n^/NODELETE^).
16163 @item ^-r^/RECURSIVE^
16164 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16165 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16166 clean all imported and extended project files, recursively. If this switch
16167 is not specified, only the files related to the main project file are to be
16168 deleted. This switch has no effect if no project file is specified.
16170 @item ^-v^/VERBOSE^
16171 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16174 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16175 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16176 Indicates the verbosity of the parsing of GNAT project files.
16177 @xref{Switches Related to Project Files}.
16179 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16180 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16181 Indicates that external variable @var{name} has the value @var{value}.
16182 The Project Manager will use this value for occurrences of
16183 @code{external(name)} when parsing the project file.
16184 @xref{Switches Related to Project Files}.
16186 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16187 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16188 When searching for ALI and object files, look in directory
16191 @item ^-I^/SEARCH=^@var{dir}
16192 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16193 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16195 @item ^-I-^/NOCURRENT_DIRECTORY^
16196 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16197 @cindex Source files, suppressing search
16198 Do not look for ALI or object files in the directory
16199 where @code{gnatclean} was invoked.
16203 @c @node Examples of gnatclean Usage
16204 @c @section Examples of @code{gnatclean} Usage
16207 @node GNAT and Libraries
16208 @chapter GNAT and Libraries
16209 @cindex Library, building, installing, using
16212 This chapter describes how to build and use libraries with GNAT, and also shows
16213 how to recompile the GNAT run-time library. You should be familiar with the
16214 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16218 * Introduction to Libraries in GNAT::
16219 * General Ada Libraries::
16220 * Stand-alone Ada Libraries::
16221 * Rebuilding the GNAT Run-Time Library::
16224 @node Introduction to Libraries in GNAT
16225 @section Introduction to Libraries in GNAT
16228 A library is, conceptually, a collection of objects which does not have its
16229 own main thread of execution, but rather provides certain services to the
16230 applications that use it. A library can be either statically linked with the
16231 application, in which case its code is directly included in the application,
16232 or, on platforms that support it, be dynamically linked, in which case
16233 its code is shared by all applications making use of this library.
16235 GNAT supports both types of libraries.
16236 In the static case, the compiled code can be provided in different ways. The
16237 simplest approach is to provide directly the set of objects resulting from
16238 compilation of the library source files. Alternatively, you can group the
16239 objects into an archive using whatever commands are provided by the operating
16240 system. For the latter case, the objects are grouped into a shared library.
16242 In the GNAT environment, a library has three types of components:
16248 @xref{The Ada Library Information Files}.
16250 Object files, an archive or a shared library.
16254 A GNAT library may expose all its source files, which is useful for
16255 documentation purposes. Alternatively, it may expose only the units needed by
16256 an external user to make use of the library. That is to say, the specs
16257 reflecting the library services along with all the units needed to compile
16258 those specs, which can include generic bodies or any body implementing an
16259 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16260 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16262 All compilation units comprising an application, including those in a library,
16263 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16264 computes the elaboration order from the @file{ALI} files and this is why they
16265 constitute a mandatory part of GNAT libraries.
16266 @emph{Stand-alone libraries} are the exception to this rule because a specific
16267 library elaboration routine is produced independently of the application(s)
16270 @node General Ada Libraries
16271 @section General Ada Libraries
16274 * Building a library::
16275 * Installing a library::
16276 * Using a library::
16279 @node Building a library
16280 @subsection Building a library
16283 The easiest way to build a library is to use the Project Manager,
16284 which supports a special type of project called a @emph{Library Project}
16285 (@pxref{Library Projects}).
16287 A project is considered a library project, when two project-level attributes
16288 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16289 control different aspects of library configuration, additional optional
16290 project-level attributes can be specified:
16293 This attribute controls whether the library is to be static or dynamic
16295 @item Library_Version
16296 This attribute specifies the library version; this value is used
16297 during dynamic linking of shared libraries to determine if the currently
16298 installed versions of the binaries are compatible.
16300 @item Library_Options
16302 These attributes specify additional low-level options to be used during
16303 library generation, and redefine the actual application used to generate
16308 The GNAT Project Manager takes full care of the library maintenance task,
16309 including recompilation of the source files for which objects do not exist
16310 or are not up to date, assembly of the library archive, and installation of
16311 the library (i.e., copying associated source, object and @file{ALI} files
16312 to the specified location).
16314 Here is a simple library project file:
16315 @smallexample @c ada
16317 for Source_Dirs use ("src1", "src2");
16318 for Object_Dir use "obj";
16319 for Library_Name use "mylib";
16320 for Library_Dir use "lib";
16321 for Library_Kind use "dynamic";
16326 and the compilation command to build and install the library:
16328 @smallexample @c ada
16329 $ gnatmake -Pmy_lib
16333 It is not entirely trivial to perform manually all the steps required to
16334 produce a library. We recommend that you use the GNAT Project Manager
16335 for this task. In special cases where this is not desired, the necessary
16336 steps are discussed below.
16338 There are various possibilities for compiling the units that make up the
16339 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16340 with a conventional script. For simple libraries, it is also possible to create
16341 a dummy main program which depends upon all the packages that comprise the
16342 interface of the library. This dummy main program can then be given to
16343 @command{gnatmake}, which will ensure that all necessary objects are built.
16345 After this task is accomplished, you should follow the standard procedure
16346 of the underlying operating system to produce the static or shared library.
16348 Here is an example of such a dummy program:
16349 @smallexample @c ada
16351 with My_Lib.Service1;
16352 with My_Lib.Service2;
16353 with My_Lib.Service3;
16354 procedure My_Lib_Dummy is
16362 Here are the generic commands that will build an archive or a shared library.
16365 # compiling the library
16366 $ gnatmake -c my_lib_dummy.adb
16368 # we don't need the dummy object itself
16369 $ rm my_lib_dummy.o my_lib_dummy.ali
16371 # create an archive with the remaining objects
16372 $ ar rc libmy_lib.a *.o
16373 # some systems may require "ranlib" to be run as well
16375 # or create a shared library
16376 $ gcc -shared -o libmy_lib.so *.o
16377 # some systems may require the code to have been compiled with -fPIC
16379 # remove the object files that are now in the library
16382 # Make the ALI files read-only so that gnatmake will not try to
16383 # regenerate the objects that are in the library
16388 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16389 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16390 be accessed by the directive @option{-l@var{xxx}} at link time.
16392 @node Installing a library
16393 @subsection Installing a library
16394 @cindex @code{ADA_PROJECT_PATH}
16395 @cindex @code{GPR_PROJECT_PATH}
16398 If you use project files, library installation is part of the library build
16399 process (@pxref{Installing a library with project files}).
16401 When project files are not an option, it is also possible, but not recommended,
16402 to install the library so that the sources needed to use the library are on the
16403 Ada source path and the ALI files & libraries be on the Ada Object path (see
16404 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16405 administrator can place general-purpose libraries in the default compiler
16406 paths, by specifying the libraries' location in the configuration files
16407 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16408 must be located in the GNAT installation tree at the same place as the gcc spec
16409 file. The location of the gcc spec file can be determined as follows:
16415 The configuration files mentioned above have a simple format: each line
16416 must contain one unique directory name.
16417 Those names are added to the corresponding path
16418 in their order of appearance in the file. The names can be either absolute
16419 or relative; in the latter case, they are relative to where theses files
16422 The files @file{ada_source_path} and @file{ada_object_path} might not be
16424 GNAT installation, in which case, GNAT will look for its run-time library in
16425 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16426 objects and @file{ALI} files). When the files exist, the compiler does not
16427 look in @file{adainclude} and @file{adalib}, and thus the
16428 @file{ada_source_path} file
16429 must contain the location for the GNAT run-time sources (which can simply
16430 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16431 contain the location for the GNAT run-time objects (which can simply
16434 You can also specify a new default path to the run-time library at compilation
16435 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16436 the run-time library you want your program to be compiled with. This switch is
16437 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16438 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16440 It is possible to install a library before or after the standard GNAT
16441 library, by reordering the lines in the configuration files. In general, a
16442 library must be installed before the GNAT library if it redefines
16445 @node Using a library
16446 @subsection Using a library
16448 @noindent Once again, the project facility greatly simplifies the use of
16449 libraries. In this context, using a library is just a matter of adding a
16450 @code{with} clause in the user project. For instance, to make use of the
16451 library @code{My_Lib} shown in examples in earlier sections, you can
16454 @smallexample @c projectfile
16461 Even if you have a third-party, non-Ada library, you can still use GNAT's
16462 Project Manager facility to provide a wrapper for it. For example, the
16463 following project, when @code{with}ed by your main project, will link with the
16464 third-party library @file{liba.a}:
16466 @smallexample @c projectfile
16469 for Externally_Built use "true";
16470 for Source_Files use ();
16471 for Library_Dir use "lib";
16472 for Library_Name use "a";
16473 for Library_Kind use "static";
16477 This is an alternative to the use of @code{pragma Linker_Options}. It is
16478 especially interesting in the context of systems with several interdependent
16479 static libraries where finding a proper linker order is not easy and best be
16480 left to the tools having visibility over project dependence information.
16483 In order to use an Ada library manually, you need to make sure that this
16484 library is on both your source and object path
16485 (see @ref{Search Paths and the Run-Time Library (RTL)}
16486 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16487 in an archive or a shared library, you need to specify the desired
16488 library at link time.
16490 For example, you can use the library @file{mylib} installed in
16491 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16494 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16499 This can be expressed more simply:
16504 when the following conditions are met:
16507 @file{/dir/my_lib_src} has been added by the user to the environment
16508 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16509 @file{ada_source_path}
16511 @file{/dir/my_lib_obj} has been added by the user to the environment
16512 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16513 @file{ada_object_path}
16515 a pragma @code{Linker_Options} has been added to one of the sources.
16518 @smallexample @c ada
16519 pragma Linker_Options ("-lmy_lib");
16523 @node Stand-alone Ada Libraries
16524 @section Stand-alone Ada Libraries
16525 @cindex Stand-alone library, building, using
16528 * Introduction to Stand-alone Libraries::
16529 * Building a Stand-alone Library::
16530 * Creating a Stand-alone Library to be used in a non-Ada context::
16531 * Restrictions in Stand-alone Libraries::
16534 @node Introduction to Stand-alone Libraries
16535 @subsection Introduction to Stand-alone Libraries
16538 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16540 elaborate the Ada units that are included in the library. In contrast with
16541 an ordinary library, which consists of all sources, objects and @file{ALI}
16543 library, a SAL may specify a restricted subset of compilation units
16544 to serve as a library interface. In this case, the fully
16545 self-sufficient set of files will normally consist of an objects
16546 archive, the sources of interface units' specs, and the @file{ALI}
16547 files of interface units.
16548 If an interface spec contains a generic unit or an inlined subprogram,
16550 source must also be provided; if the units that must be provided in the source
16551 form depend on other units, the source and @file{ALI} files of those must
16554 The main purpose of a SAL is to minimize the recompilation overhead of client
16555 applications when a new version of the library is installed. Specifically,
16556 if the interface sources have not changed, client applications do not need to
16557 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16558 version, controlled by @code{Library_Version} attribute, is not changed,
16559 then the clients do not need to be relinked.
16561 SALs also allow the library providers to minimize the amount of library source
16562 text exposed to the clients. Such ``information hiding'' might be useful or
16563 necessary for various reasons.
16565 Stand-alone libraries are also well suited to be used in an executable whose
16566 main routine is not written in Ada.
16568 @node Building a Stand-alone Library
16569 @subsection Building a Stand-alone Library
16572 GNAT's Project facility provides a simple way of building and installing
16573 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16574 To be a Stand-alone Library Project, in addition to the two attributes
16575 that make a project a Library Project (@code{Library_Name} and
16576 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16577 @code{Library_Interface} must be defined. For example:
16579 @smallexample @c projectfile
16581 for Library_Dir use "lib_dir";
16582 for Library_Name use "dummy";
16583 for Library_Interface use ("int1", "int1.child");
16588 Attribute @code{Library_Interface} has a non-empty string list value,
16589 each string in the list designating a unit contained in an immediate source
16590 of the project file.
16592 When a Stand-alone Library is built, first the binder is invoked to build
16593 a package whose name depends on the library name
16594 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16595 This binder-generated package includes initialization and
16596 finalization procedures whose
16597 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16599 above). The object corresponding to this package is included in the library.
16601 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16602 calling of these procedures if a static SAL is built, or if a shared SAL
16604 with the project-level attribute @code{Library_Auto_Init} set to
16607 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16608 (those that are listed in attribute @code{Library_Interface}) are copied to
16609 the Library Directory. As a consequence, only the Interface Units may be
16610 imported from Ada units outside of the library. If other units are imported,
16611 the binding phase will fail.
16614 It is also possible to build an encapsulated library where not only
16615 the code to elaborate and finalize the library is embedded but also
16616 ensuring that the library is linked only against static
16617 libraries. So an encapsulated library only depends on system
16618 libraries, all other code, including the GNAT runtime, is embedded. To
16619 build an encapsulated library the attribute
16620 @code{Library_Standalone} must be set to @code{encapsulated}:
16622 @smallexample @c projectfile
16624 for Library_Dir use "lib_dir";
16625 for Library_Name use "dummy";
16626 for Library_Interface use ("int1", "int1.child");
16627 for Library_Standalone use "encapsulated";
16632 The default value for this attribute is @code{standard} in which case
16633 a stand-alone library is built.
16635 The attribute @code{Library_Src_Dir} may be specified for a
16636 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16637 single string value. Its value must be the path (absolute or relative to the
16638 project directory) of an existing directory. This directory cannot be the
16639 object directory or one of the source directories, but it can be the same as
16640 the library directory. The sources of the Interface
16641 Units of the library that are needed by an Ada client of the library will be
16642 copied to the designated directory, called the Interface Copy directory.
16643 These sources include the specs of the Interface Units, but they may also
16644 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16645 are used, or when there is a generic unit in the spec. Before the sources
16646 are copied to the Interface Copy directory, an attempt is made to delete all
16647 files in the Interface Copy directory.
16649 Building stand-alone libraries by hand is somewhat tedious, but for those
16650 occasions when it is necessary here are the steps that you need to perform:
16653 Compile all library sources.
16656 Invoke the binder with the switch @option{-n} (No Ada main program),
16657 with all the @file{ALI} files of the interfaces, and
16658 with the switch @option{-L} to give specific names to the @code{init}
16659 and @code{final} procedures. For example:
16661 gnatbind -n int1.ali int2.ali -Lsal1
16665 Compile the binder generated file:
16671 Link the dynamic library with all the necessary object files,
16672 indicating to the linker the names of the @code{init} (and possibly
16673 @code{final}) procedures for automatic initialization (and finalization).
16674 The built library should be placed in a directory different from
16675 the object directory.
16678 Copy the @code{ALI} files of the interface to the library directory,
16679 add in this copy an indication that it is an interface to a SAL
16680 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16681 with letter ``P'') and make the modified copy of the @file{ALI} file
16686 Using SALs is not different from using other libraries
16687 (see @ref{Using a library}).
16689 @node Creating a Stand-alone Library to be used in a non-Ada context
16690 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16693 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16696 The only extra step required is to ensure that library interface subprograms
16697 are compatible with the main program, by means of @code{pragma Export}
16698 or @code{pragma Convention}.
16700 Here is an example of simple library interface for use with C main program:
16702 @smallexample @c ada
16703 package My_Package is
16705 procedure Do_Something;
16706 pragma Export (C, Do_Something, "do_something");
16708 procedure Do_Something_Else;
16709 pragma Export (C, Do_Something_Else, "do_something_else");
16715 On the foreign language side, you must provide a ``foreign'' view of the
16716 library interface; remember that it should contain elaboration routines in
16717 addition to interface subprograms.
16719 The example below shows the content of @code{mylib_interface.h} (note
16720 that there is no rule for the naming of this file, any name can be used)
16722 /* the library elaboration procedure */
16723 extern void mylibinit (void);
16725 /* the library finalization procedure */
16726 extern void mylibfinal (void);
16728 /* the interface exported by the library */
16729 extern void do_something (void);
16730 extern void do_something_else (void);
16734 Libraries built as explained above can be used from any program, provided
16735 that the elaboration procedures (named @code{mylibinit} in the previous
16736 example) are called before the library services are used. Any number of
16737 libraries can be used simultaneously, as long as the elaboration
16738 procedure of each library is called.
16740 Below is an example of a C program that uses the @code{mylib} library.
16743 #include "mylib_interface.h"
16748 /* First, elaborate the library before using it */
16751 /* Main program, using the library exported entities */
16753 do_something_else ();
16755 /* Library finalization at the end of the program */
16762 Note that invoking any library finalization procedure generated by
16763 @code{gnatbind} shuts down the Ada run-time environment.
16765 finalization of all Ada libraries must be performed at the end of the program.
16766 No call to these libraries or to the Ada run-time library should be made
16767 after the finalization phase.
16769 @node Restrictions in Stand-alone Libraries
16770 @subsection Restrictions in Stand-alone Libraries
16773 The pragmas listed below should be used with caution inside libraries,
16774 as they can create incompatibilities with other Ada libraries:
16776 @item pragma @code{Locking_Policy}
16777 @item pragma @code{Queuing_Policy}
16778 @item pragma @code{Task_Dispatching_Policy}
16779 @item pragma @code{Unreserve_All_Interrupts}
16783 When using a library that contains such pragmas, the user must make sure
16784 that all libraries use the same pragmas with the same values. Otherwise,
16785 @code{Program_Error} will
16786 be raised during the elaboration of the conflicting
16787 libraries. The usage of these pragmas and its consequences for the user
16788 should therefore be well documented.
16790 Similarly, the traceback in the exception occurrence mechanism should be
16791 enabled or disabled in a consistent manner across all libraries.
16792 Otherwise, Program_Error will be raised during the elaboration of the
16793 conflicting libraries.
16795 If the @code{Version} or @code{Body_Version}
16796 attributes are used inside a library, then you need to
16797 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16798 libraries, so that version identifiers can be properly computed.
16799 In practice these attributes are rarely used, so this is unlikely
16800 to be a consideration.
16802 @node Rebuilding the GNAT Run-Time Library
16803 @section Rebuilding the GNAT Run-Time Library
16804 @cindex GNAT Run-Time Library, rebuilding
16805 @cindex Building the GNAT Run-Time Library
16806 @cindex Rebuilding the GNAT Run-Time Library
16807 @cindex Run-Time Library, rebuilding
16810 It may be useful to recompile the GNAT library in various contexts, the
16811 most important one being the use of partition-wide configuration pragmas
16812 such as @code{Normalize_Scalars}. A special Makefile called
16813 @code{Makefile.adalib} is provided to that effect and can be found in
16814 the directory containing the GNAT library. The location of this
16815 directory depends on the way the GNAT environment has been installed and can
16816 be determined by means of the command:
16823 The last entry in the object search path usually contains the
16824 gnat library. This Makefile contains its own documentation and in
16825 particular the set of instructions needed to rebuild a new library and
16828 @node Using the GNU make Utility
16829 @chapter Using the GNU @code{make} Utility
16833 This chapter offers some examples of makefiles that solve specific
16834 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16835 make, make, GNU @code{make}}), nor does it try to replace the
16836 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16838 All the examples in this section are specific to the GNU version of
16839 make. Although @command{make} is a standard utility, and the basic language
16840 is the same, these examples use some advanced features found only in
16844 * Using gnatmake in a Makefile::
16845 * Automatically Creating a List of Directories::
16846 * Generating the Command Line Switches::
16847 * Overcoming Command Line Length Limits::
16850 @node Using gnatmake in a Makefile
16851 @section Using gnatmake in a Makefile
16856 Complex project organizations can be handled in a very powerful way by
16857 using GNU make combined with gnatmake. For instance, here is a Makefile
16858 which allows you to build each subsystem of a big project into a separate
16859 shared library. Such a makefile allows you to significantly reduce the link
16860 time of very big applications while maintaining full coherence at
16861 each step of the build process.
16863 The list of dependencies are handled automatically by
16864 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16865 the appropriate directories.
16867 Note that you should also read the example on how to automatically
16868 create the list of directories
16869 (@pxref{Automatically Creating a List of Directories})
16870 which might help you in case your project has a lot of subdirectories.
16875 @font@heightrm=cmr8
16878 ## This Makefile is intended to be used with the following directory
16880 ## - The sources are split into a series of csc (computer software components)
16881 ## Each of these csc is put in its own directory.
16882 ## Their name are referenced by the directory names.
16883 ## They will be compiled into shared library (although this would also work
16884 ## with static libraries
16885 ## - The main program (and possibly other packages that do not belong to any
16886 ## csc is put in the top level directory (where the Makefile is).
16887 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16888 ## \_ second_csc (sources) __ lib (will contain the library)
16890 ## Although this Makefile is build for shared library, it is easy to modify
16891 ## to build partial link objects instead (modify the lines with -shared and
16894 ## With this makefile, you can change any file in the system or add any new
16895 ## file, and everything will be recompiled correctly (only the relevant shared
16896 ## objects will be recompiled, and the main program will be re-linked).
16898 # The list of computer software component for your project. This might be
16899 # generated automatically.
16902 # Name of the main program (no extension)
16905 # If we need to build objects with -fPIC, uncomment the following line
16908 # The following variable should give the directory containing libgnat.so
16909 # You can get this directory through 'gnatls -v'. This is usually the last
16910 # directory in the Object_Path.
16913 # The directories for the libraries
16914 # (This macro expands the list of CSC to the list of shared libraries, you
16915 # could simply use the expanded form:
16916 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16917 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16919 $@{MAIN@}: objects $@{LIB_DIR@}
16920 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16921 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16924 # recompile the sources
16925 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16927 # Note: In a future version of GNAT, the following commands will be simplified
16928 # by a new tool, gnatmlib
16930 mkdir -p $@{dir $@@ @}
16931 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16932 cd $@{dir $@@ @} && cp -f ../*.ali .
16934 # The dependencies for the modules
16935 # Note that we have to force the expansion of *.o, since in some cases
16936 # make won't be able to do it itself.
16937 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16938 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16939 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16941 # Make sure all of the shared libraries are in the path before starting the
16944 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16947 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16948 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16949 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16950 $@{RM@} *.o *.ali $@{MAIN@}
16953 @node Automatically Creating a List of Directories
16954 @section Automatically Creating a List of Directories
16957 In most makefiles, you will have to specify a list of directories, and
16958 store it in a variable. For small projects, it is often easier to
16959 specify each of them by hand, since you then have full control over what
16960 is the proper order for these directories, which ones should be
16963 However, in larger projects, which might involve hundreds of
16964 subdirectories, it might be more convenient to generate this list
16967 The example below presents two methods. The first one, although less
16968 general, gives you more control over the list. It involves wildcard
16969 characters, that are automatically expanded by @command{make}. Its
16970 shortcoming is that you need to explicitly specify some of the
16971 organization of your project, such as for instance the directory tree
16972 depth, whether some directories are found in a separate tree, @enddots{}
16974 The second method is the most general one. It requires an external
16975 program, called @command{find}, which is standard on all Unix systems. All
16976 the directories found under a given root directory will be added to the
16982 @font@heightrm=cmr8
16985 # The examples below are based on the following directory hierarchy:
16986 # All the directories can contain any number of files
16987 # ROOT_DIRECTORY -> a -> aa -> aaa
16990 # -> b -> ba -> baa
16993 # This Makefile creates a variable called DIRS, that can be reused any time
16994 # you need this list (see the other examples in this section)
16996 # The root of your project's directory hierarchy
17000 # First method: specify explicitly the list of directories
17001 # This allows you to specify any subset of all the directories you need.
17004 DIRS := a/aa/ a/ab/ b/ba/
17007 # Second method: use wildcards
17008 # Note that the argument(s) to wildcard below should end with a '/'.
17009 # Since wildcards also return file names, we have to filter them out
17010 # to avoid duplicate directory names.
17011 # We thus use make's @code{dir} and @code{sort} functions.
17012 # It sets DIRs to the following value (note that the directories aaa and baa
17013 # are not given, unless you change the arguments to wildcard).
17014 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17017 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17018 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17021 # Third method: use an external program
17022 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17023 # This is the most complete command: it sets DIRs to the following value:
17024 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17027 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17031 @node Generating the Command Line Switches
17032 @section Generating the Command Line Switches
17035 Once you have created the list of directories as explained in the
17036 previous section (@pxref{Automatically Creating a List of Directories}),
17037 you can easily generate the command line arguments to pass to gnatmake.
17039 For the sake of completeness, this example assumes that the source path
17040 is not the same as the object path, and that you have two separate lists
17044 # see "Automatically creating a list of directories" to create
17049 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17050 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17053 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17056 @node Overcoming Command Line Length Limits
17057 @section Overcoming Command Line Length Limits
17060 One problem that might be encountered on big projects is that many
17061 operating systems limit the length of the command line. It is thus hard to give
17062 gnatmake the list of source and object directories.
17064 This example shows how you can set up environment variables, which will
17065 make @command{gnatmake} behave exactly as if the directories had been
17066 specified on the command line, but have a much higher length limit (or
17067 even none on most systems).
17069 It assumes that you have created a list of directories in your Makefile,
17070 using one of the methods presented in
17071 @ref{Automatically Creating a List of Directories}.
17072 For the sake of completeness, we assume that the object
17073 path (where the ALI files are found) is different from the sources patch.
17075 Note a small trick in the Makefile below: for efficiency reasons, we
17076 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17077 expanded immediately by @code{make}. This way we overcome the standard
17078 make behavior which is to expand the variables only when they are
17081 On Windows, if you are using the standard Windows command shell, you must
17082 replace colons with semicolons in the assignments to these variables.
17087 @font@heightrm=cmr8
17090 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17091 # This is the same thing as putting the -I arguments on the command line.
17092 # (the equivalent of using -aI on the command line would be to define
17093 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17094 # You can of course have different values for these variables.
17096 # Note also that we need to keep the previous values of these variables, since
17097 # they might have been set before running 'make' to specify where the GNAT
17098 # library is installed.
17100 # see "Automatically creating a list of directories" to create these
17106 space:=$@{empty@} $@{empty@}
17107 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17108 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17109 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17110 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17111 export ADA_INCLUDE_PATH
17112 export ADA_OBJECTS_PATH
17119 @node Memory Management Issues
17120 @chapter Memory Management Issues
17123 This chapter describes some useful memory pools provided in the GNAT library
17124 and in particular the GNAT Debug Pool facility, which can be used to detect
17125 incorrect uses of access values (including ``dangling references'').
17127 It also describes the @command{gnatmem} tool, which can be used to track down
17132 * Some Useful Memory Pools::
17133 * The GNAT Debug Pool Facility::
17135 * The gnatmem Tool::
17139 @node Some Useful Memory Pools
17140 @section Some Useful Memory Pools
17141 @findex Memory Pool
17142 @cindex storage, pool
17145 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17146 storage pool. Allocations use the standard system call @code{malloc} while
17147 deallocations use the standard system call @code{free}. No reclamation is
17148 performed when the pool goes out of scope. For performance reasons, the
17149 standard default Ada allocators/deallocators do not use any explicit storage
17150 pools but if they did, they could use this storage pool without any change in
17151 behavior. That is why this storage pool is used when the user
17152 manages to make the default implicit allocator explicit as in this example:
17153 @smallexample @c ada
17154 type T1 is access Something;
17155 -- no Storage pool is defined for T2
17156 type T2 is access Something_Else;
17157 for T2'Storage_Pool use T1'Storage_Pool;
17158 -- the above is equivalent to
17159 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17163 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17164 pool. The allocation strategy is similar to @code{Pool_Local}'s
17165 except that the all
17166 storage allocated with this pool is reclaimed when the pool object goes out of
17167 scope. This pool provides a explicit mechanism similar to the implicit one
17168 provided by several Ada 83 compilers for allocations performed through a local
17169 access type and whose purpose was to reclaim memory when exiting the
17170 scope of a given local access. As an example, the following program does not
17171 leak memory even though it does not perform explicit deallocation:
17173 @smallexample @c ada
17174 with System.Pool_Local;
17175 procedure Pooloc1 is
17176 procedure Internal is
17177 type A is access Integer;
17178 X : System.Pool_Local.Unbounded_Reclaim_Pool;
17179 for A'Storage_Pool use X;
17182 for I in 1 .. 50 loop
17187 for I in 1 .. 100 loop
17194 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17195 @code{Storage_Size} is specified for an access type.
17196 The whole storage for the pool is
17197 allocated at once, usually on the stack at the point where the access type is
17198 elaborated. It is automatically reclaimed when exiting the scope where the
17199 access type is defined. This package is not intended to be used directly by the
17200 user and it is implicitly used for each such declaration:
17202 @smallexample @c ada
17203 type T1 is access Something;
17204 for T1'Storage_Size use 10_000;
17207 @node The GNAT Debug Pool Facility
17208 @section The GNAT Debug Pool Facility
17210 @cindex storage, pool, memory corruption
17213 The use of unchecked deallocation and unchecked conversion can easily
17214 lead to incorrect memory references. The problems generated by such
17215 references are usually difficult to tackle because the symptoms can be
17216 very remote from the origin of the problem. In such cases, it is
17217 very helpful to detect the problem as early as possible. This is the
17218 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17220 In order to use the GNAT specific debugging pool, the user must
17221 associate a debug pool object with each of the access types that may be
17222 related to suspected memory problems. See Ada Reference Manual 13.11.
17223 @smallexample @c ada
17224 type Ptr is access Some_Type;
17225 Pool : GNAT.Debug_Pools.Debug_Pool;
17226 for Ptr'Storage_Pool use Pool;
17230 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17231 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17232 allow the user to redefine allocation and deallocation strategies. They
17233 also provide a checkpoint for each dereference, through the use of
17234 the primitive operation @code{Dereference} which is implicitly called at
17235 each dereference of an access value.
17237 Once an access type has been associated with a debug pool, operations on
17238 values of the type may raise four distinct exceptions,
17239 which correspond to four potential kinds of memory corruption:
17242 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17244 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17246 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17248 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17252 For types associated with a Debug_Pool, dynamic allocation is performed using
17253 the standard GNAT allocation routine. References to all allocated chunks of
17254 memory are kept in an internal dictionary. Several deallocation strategies are
17255 provided, whereupon the user can choose to release the memory to the system,
17256 keep it allocated for further invalid access checks, or fill it with an easily
17257 recognizable pattern for debug sessions. The memory pattern is the old IBM
17258 hexadecimal convention: @code{16#DEADBEEF#}.
17260 See the documentation in the file g-debpoo.ads for more information on the
17261 various strategies.
17263 Upon each dereference, a check is made that the access value denotes a
17264 properly allocated memory location. Here is a complete example of use of
17265 @code{Debug_Pools}, that includes typical instances of memory corruption:
17266 @smallexample @c ada
17270 with Gnat.Io; use Gnat.Io;
17271 with Unchecked_Deallocation;
17272 with Unchecked_Conversion;
17273 with GNAT.Debug_Pools;
17274 with System.Storage_Elements;
17275 with Ada.Exceptions; use Ada.Exceptions;
17276 procedure Debug_Pool_Test is
17278 type T is access Integer;
17279 type U is access all T;
17281 P : GNAT.Debug_Pools.Debug_Pool;
17282 for T'Storage_Pool use P;
17284 procedure Free is new Unchecked_Deallocation (Integer, T);
17285 function UC is new Unchecked_Conversion (U, T);
17288 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17298 Put_Line (Integer'Image(B.all));
17300 when E : others => Put_Line ("raised: " & Exception_Name (E));
17305 when E : others => Put_Line ("raised: " & Exception_Name (E));
17309 Put_Line (Integer'Image(B.all));
17311 when E : others => Put_Line ("raised: " & Exception_Name (E));
17316 when E : others => Put_Line ("raised: " & Exception_Name (E));
17319 end Debug_Pool_Test;
17323 The debug pool mechanism provides the following precise diagnostics on the
17324 execution of this erroneous program:
17327 Total allocated bytes : 0
17328 Total deallocated bytes : 0
17329 Current Water Mark: 0
17333 Total allocated bytes : 8
17334 Total deallocated bytes : 0
17335 Current Water Mark: 8
17338 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17339 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17340 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17341 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17343 Total allocated bytes : 8
17344 Total deallocated bytes : 4
17345 Current Water Mark: 4
17350 @node The gnatmem Tool
17351 @section The @command{gnatmem} Tool
17355 The @code{gnatmem} utility monitors dynamic allocation and
17356 deallocation activity in a program, and displays information about
17357 incorrect deallocations and possible sources of memory leaks.
17358 It is designed to work in association with a static runtime library
17359 only and in this context provides three types of information:
17362 General information concerning memory management, such as the total
17363 number of allocations and deallocations, the amount of allocated
17364 memory and the high water mark, i.e.@: the largest amount of allocated
17365 memory in the course of program execution.
17368 Backtraces for all incorrect deallocations, that is to say deallocations
17369 which do not correspond to a valid allocation.
17372 Information on each allocation that is potentially the origin of a memory
17377 * Running gnatmem::
17378 * Switches for gnatmem::
17379 * Example of gnatmem Usage::
17382 @node Running gnatmem
17383 @subsection Running @code{gnatmem}
17386 @code{gnatmem} makes use of the output created by the special version of
17387 allocation and deallocation routines that record call information. This
17388 allows to obtain accurate dynamic memory usage history at a minimal cost to
17389 the execution speed. Note however, that @code{gnatmem} is not supported on
17390 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17391 Solaris and Windows NT/2000/XP (x86).
17394 The @code{gnatmem} command has the form
17397 @c $ gnatmem @ovar{switches} user_program
17398 @c Expanding @ovar macro inline (explanation in macro def comments)
17399 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17403 The program must have been linked with the instrumented version of the
17404 allocation and deallocation routines. This is done by linking with the
17405 @file{libgmem.a} library. For correct symbolic backtrace information,
17406 the user program should be compiled with debugging options
17407 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17410 $ gnatmake -g my_program -largs -lgmem
17414 As library @file{libgmem.a} contains an alternate body for package
17415 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17416 when an executable is linked with library @file{libgmem.a}. It is then not
17417 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17420 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17421 This file contains information about all allocations and deallocations
17422 performed by the program. It is produced by the instrumented allocations and
17423 deallocations routines and will be used by @code{gnatmem}.
17425 In order to produce symbolic backtrace information for allocations and
17426 deallocations performed by the GNAT run-time library, you need to use a
17427 version of that library that has been compiled with the @option{-g} switch
17428 (see @ref{Rebuilding the GNAT Run-Time Library}).
17430 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17431 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17432 @option{-i} switch, gnatmem will assume that this file can be found in the
17433 current directory. For example, after you have executed @file{my_program},
17434 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17437 $ gnatmem my_program
17441 This will produce the output with the following format:
17443 *************** debut cc
17445 $ gnatmem my_program
17449 Total number of allocations : 45
17450 Total number of deallocations : 6
17451 Final Water Mark (non freed mem) : 11.29 Kilobytes
17452 High Water Mark : 11.40 Kilobytes
17457 Allocation Root # 2
17458 -------------------
17459 Number of non freed allocations : 11
17460 Final Water Mark (non freed mem) : 1.16 Kilobytes
17461 High Water Mark : 1.27 Kilobytes
17463 my_program.adb:23 my_program.alloc
17469 The first block of output gives general information. In this case, the
17470 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17471 Unchecked_Deallocation routine occurred.
17474 Subsequent paragraphs display information on all allocation roots.
17475 An allocation root is a specific point in the execution of the program
17476 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17477 construct. This root is represented by an execution backtrace (or subprogram
17478 call stack). By default the backtrace depth for allocations roots is 1, so
17479 that a root corresponds exactly to a source location. The backtrace can
17480 be made deeper, to make the root more specific.
17482 @node Switches for gnatmem
17483 @subsection Switches for @code{gnatmem}
17486 @code{gnatmem} recognizes the following switches:
17491 @cindex @option{-q} (@code{gnatmem})
17492 Quiet. Gives the minimum output needed to identify the origin of the
17493 memory leaks. Omits statistical information.
17496 @cindex @var{N} (@code{gnatmem})
17497 N is an integer literal (usually between 1 and 10) which controls the
17498 depth of the backtraces defining allocation root. The default value for
17499 N is 1. The deeper the backtrace, the more precise the localization of
17500 the root. Note that the total number of roots can depend on this
17501 parameter. This parameter must be specified @emph{before} the name of the
17502 executable to be analyzed, to avoid ambiguity.
17505 @cindex @option{-b} (@code{gnatmem})
17506 This switch has the same effect as just depth parameter.
17508 @item -i @var{file}
17509 @cindex @option{-i} (@code{gnatmem})
17510 Do the @code{gnatmem} processing starting from @file{file}, rather than
17511 @file{gmem.out} in the current directory.
17514 @cindex @option{-m} (@code{gnatmem})
17515 This switch causes @code{gnatmem} to mask the allocation roots that have less
17516 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17517 examine even the roots that didn't result in leaks.
17520 @cindex @option{-s} (@code{gnatmem})
17521 This switch causes @code{gnatmem} to sort the allocation roots according to the
17522 specified order of sort criteria, each identified by a single letter. The
17523 currently supported criteria are @code{n, h, w} standing respectively for
17524 number of unfreed allocations, high watermark, and final watermark
17525 corresponding to a specific root. The default order is @code{nwh}.
17529 @node Example of gnatmem Usage
17530 @subsection Example of @code{gnatmem} Usage
17533 The following example shows the use of @code{gnatmem}
17534 on a simple memory-leaking program.
17535 Suppose that we have the following Ada program:
17537 @smallexample @c ada
17540 with Unchecked_Deallocation;
17541 procedure Test_Gm is
17543 type T is array (1..1000) of Integer;
17544 type Ptr is access T;
17545 procedure Free is new Unchecked_Deallocation (T, Ptr);
17548 procedure My_Alloc is
17553 procedure My_DeAlloc is
17561 for I in 1 .. 5 loop
17562 for J in I .. 5 loop
17573 The program needs to be compiled with debugging option and linked with
17574 @code{gmem} library:
17577 $ gnatmake -g test_gm -largs -lgmem
17581 Then we execute the program as usual:
17588 Then @code{gnatmem} is invoked simply with
17594 which produces the following output (result may vary on different platforms):
17599 Total number of allocations : 18
17600 Total number of deallocations : 5
17601 Final Water Mark (non freed mem) : 53.00 Kilobytes
17602 High Water Mark : 56.90 Kilobytes
17604 Allocation Root # 1
17605 -------------------
17606 Number of non freed allocations : 11
17607 Final Water Mark (non freed mem) : 42.97 Kilobytes
17608 High Water Mark : 46.88 Kilobytes
17610 test_gm.adb:11 test_gm.my_alloc
17612 Allocation Root # 2
17613 -------------------
17614 Number of non freed allocations : 1
17615 Final Water Mark (non freed mem) : 10.02 Kilobytes
17616 High Water Mark : 10.02 Kilobytes
17618 s-secsta.adb:81 system.secondary_stack.ss_init
17620 Allocation Root # 3
17621 -------------------
17622 Number of non freed allocations : 1
17623 Final Water Mark (non freed mem) : 12 Bytes
17624 High Water Mark : 12 Bytes
17626 s-secsta.adb:181 system.secondary_stack.ss_init
17630 Note that the GNAT run time contains itself a certain number of
17631 allocations that have no corresponding deallocation,
17632 as shown here for root #2 and root
17633 #3. This is a normal behavior when the number of non-freed allocations
17634 is one, it allocates dynamic data structures that the run time needs for
17635 the complete lifetime of the program. Note also that there is only one
17636 allocation root in the user program with a single line back trace:
17637 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17638 program shows that 'My_Alloc' is called at 2 different points in the
17639 source (line 21 and line 24). If those two allocation roots need to be
17640 distinguished, the backtrace depth parameter can be used:
17643 $ gnatmem 3 test_gm
17647 which will give the following output:
17652 Total number of allocations : 18
17653 Total number of deallocations : 5
17654 Final Water Mark (non freed mem) : 53.00 Kilobytes
17655 High Water Mark : 56.90 Kilobytes
17657 Allocation Root # 1
17658 -------------------
17659 Number of non freed allocations : 10
17660 Final Water Mark (non freed mem) : 39.06 Kilobytes
17661 High Water Mark : 42.97 Kilobytes
17663 test_gm.adb:11 test_gm.my_alloc
17664 test_gm.adb:24 test_gm
17665 b_test_gm.c:52 main
17667 Allocation Root # 2
17668 -------------------
17669 Number of non freed allocations : 1
17670 Final Water Mark (non freed mem) : 10.02 Kilobytes
17671 High Water Mark : 10.02 Kilobytes
17673 s-secsta.adb:81 system.secondary_stack.ss_init
17674 s-secsta.adb:283 <system__secondary_stack___elabb>
17675 b_test_gm.c:33 adainit
17677 Allocation Root # 3
17678 -------------------
17679 Number of non freed allocations : 1
17680 Final Water Mark (non freed mem) : 3.91 Kilobytes
17681 High Water Mark : 3.91 Kilobytes
17683 test_gm.adb:11 test_gm.my_alloc
17684 test_gm.adb:21 test_gm
17685 b_test_gm.c:52 main
17687 Allocation Root # 4
17688 -------------------
17689 Number of non freed allocations : 1
17690 Final Water Mark (non freed mem) : 12 Bytes
17691 High Water Mark : 12 Bytes
17693 s-secsta.adb:181 system.secondary_stack.ss_init
17694 s-secsta.adb:283 <system__secondary_stack___elabb>
17695 b_test_gm.c:33 adainit
17699 The allocation root #1 of the first example has been split in 2 roots #1
17700 and #3 thanks to the more precise associated backtrace.
17704 @node Stack Related Facilities
17705 @chapter Stack Related Facilities
17708 This chapter describes some useful tools associated with stack
17709 checking and analysis. In
17710 particular, it deals with dynamic and static stack usage measurements.
17713 * Stack Overflow Checking::
17714 * Static Stack Usage Analysis::
17715 * Dynamic Stack Usage Analysis::
17718 @node Stack Overflow Checking
17719 @section Stack Overflow Checking
17720 @cindex Stack Overflow Checking
17721 @cindex -fstack-check
17724 For most operating systems, @command{gcc} does not perform stack overflow
17725 checking by default. This means that if the main environment task or
17726 some other task exceeds the available stack space, then unpredictable
17727 behavior will occur. Most native systems offer some level of protection by
17728 adding a guard page at the end of each task stack. This mechanism is usually
17729 not enough for dealing properly with stack overflow situations because
17730 a large local variable could ``jump'' above the guard page.
17731 Furthermore, when the
17732 guard page is hit, there may not be any space left on the stack for executing
17733 the exception propagation code. Enabling stack checking avoids
17736 To activate stack checking, compile all units with the gcc option
17737 @option{-fstack-check}. For example:
17740 gcc -c -fstack-check package1.adb
17744 Units compiled with this option will generate extra instructions to check
17745 that any use of the stack (for procedure calls or for declaring local
17746 variables in declare blocks) does not exceed the available stack space.
17747 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17749 For declared tasks, the stack size is controlled by the size
17750 given in an applicable @code{Storage_Size} pragma or by the value specified
17751 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17752 the default size as defined in the GNAT runtime otherwise.
17754 For the environment task, the stack size depends on
17755 system defaults and is unknown to the compiler. Stack checking
17756 may still work correctly if a fixed
17757 size stack is allocated, but this cannot be guaranteed.
17759 To ensure that a clean exception is signalled for stack
17760 overflow, set the environment variable
17761 @env{GNAT_STACK_LIMIT} to indicate the maximum
17762 stack area that can be used, as in:
17763 @cindex GNAT_STACK_LIMIT
17766 SET GNAT_STACK_LIMIT 1600
17770 The limit is given in kilobytes, so the above declaration would
17771 set the stack limit of the environment task to 1.6 megabytes.
17772 Note that the only purpose of this usage is to limit the amount
17773 of stack used by the environment task. If it is necessary to
17774 increase the amount of stack for the environment task, then this
17775 is an operating systems issue, and must be addressed with the
17776 appropriate operating systems commands.
17779 To have a fixed size stack in the environment task, the stack must be put
17780 in the P0 address space and its size specified. Use these switches to
17784 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17788 The quotes are required to keep case. The number after @samp{STACK=} is the
17789 size of the environmental task stack in pagelets (512 bytes). In this example
17790 the stack size is about 2 megabytes.
17793 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17794 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
17795 more details about the @option{/p0image} qualifier and the @option{stack}
17799 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17800 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17801 stack in kilobytes. For example:
17804 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17808 @node Static Stack Usage Analysis
17809 @section Static Stack Usage Analysis
17810 @cindex Static Stack Usage Analysis
17811 @cindex -fstack-usage
17814 A unit compiled with @option{-fstack-usage} will generate an extra file
17816 the maximum amount of stack used, on a per-function basis.
17817 The file has the same
17818 basename as the target object file with a @file{.su} extension.
17819 Each line of this file is made up of three fields:
17823 The name of the function.
17827 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17830 The second field corresponds to the size of the known part of the function
17833 The qualifier @code{static} means that the function frame size
17835 It usually means that all local variables have a static size.
17836 In this case, the second field is a reliable measure of the function stack
17839 The qualifier @code{dynamic} means that the function frame size is not static.
17840 It happens mainly when some local variables have a dynamic size. When this
17841 qualifier appears alone, the second field is not a reliable measure
17842 of the function stack analysis. When it is qualified with @code{bounded}, it
17843 means that the second field is a reliable maximum of the function stack
17846 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17847 subprogram whose stack usage might be larger than the specified amount of
17848 bytes. The wording is in keeping with the qualifier documented above.
17850 @node Dynamic Stack Usage Analysis
17851 @section Dynamic Stack Usage Analysis
17854 It is possible to measure the maximum amount of stack used by a task, by
17855 adding a switch to @command{gnatbind}, as:
17858 $ gnatbind -u0 file
17862 With this option, at each task termination, its stack usage is output on
17864 It is not always convenient to output the stack usage when the program
17865 is still running. Hence, it is possible to delay this output until program
17866 termination. for a given number of tasks specified as the argument of the
17867 @option{-u} option. For instance:
17870 $ gnatbind -u100 file
17874 will buffer the stack usage information of the first 100 tasks to terminate and
17875 output this info at program termination. Results are displayed in four
17879 Index | Task Name | Stack Size | Stack Usage
17886 is a number associated with each task.
17889 is the name of the task analyzed.
17892 is the maximum size for the stack.
17895 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17896 is not entirely analyzed, and it's not possible to know exactly how
17897 much has actually been used.
17902 The environment task stack, e.g., the stack that contains the main unit, is
17903 only processed when the environment variable GNAT_STACK_LIMIT is set.
17906 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17907 stack usage reports at run-time. See its body for the details.
17909 @c *********************************
17911 @c *********************************
17912 @node Verifying Properties Using gnatcheck
17913 @chapter Verifying Properties Using @command{gnatcheck}
17915 @cindex @command{gnatcheck}
17918 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17919 of Ada source files according to a given set of semantic rules.
17922 In order to check compliance with a given rule, @command{gnatcheck} has to
17923 semantically analyze the Ada sources.
17924 Therefore, checks can only be performed on
17925 legal Ada units. Moreover, when a unit depends semantically upon units located
17926 outside the current directory, the source search path has to be provided when
17927 calling @command{gnatcheck}, either through a specified project file or
17928 through @command{gnatcheck} switches.
17930 For full details, refer to @cite{GNATcheck Reference Manual} document.
17933 @c *********************************
17934 @node Creating Sample Bodies Using gnatstub
17935 @chapter Creating Sample Bodies Using @command{gnatstub}
17939 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17940 for library unit declarations.
17942 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17943 driver (see @ref{The GNAT Driver and Project Files}).
17945 To create a body stub, @command{gnatstub} has to compile the library
17946 unit declaration. Therefore, bodies can be created only for legal
17947 library units. Moreover, if a library unit depends semantically upon
17948 units located outside the current directory, you have to provide
17949 the source search path when calling @command{gnatstub}, see the description
17950 of @command{gnatstub} switches below.
17952 By default, all the program unit body stubs generated by @code{gnatstub}
17953 raise the predefined @code{Program_Error} exception, which will catch
17954 accidental calls of generated stubs. This behavior can be changed with
17955 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17958 * Running gnatstub::
17959 * Switches for gnatstub::
17962 @node Running gnatstub
17963 @section Running @command{gnatstub}
17966 @command{gnatstub} has a command-line interface of the form:
17969 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17970 @c Expanding @ovar macro inline (explanation in macro def comments)
17971 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17978 is the name of the source file that contains a library unit declaration
17979 for which a body must be created. The file name may contain the path
17981 The file name does not have to follow the GNAT file name conventions. If the
17983 does not follow GNAT file naming conventions, the name of the body file must
17985 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17986 If the file name follows the GNAT file naming
17987 conventions and the name of the body file is not provided,
17990 of the body file from the argument file name by replacing the @file{.ads}
17992 with the @file{.adb} suffix.
17995 indicates the directory in which the body stub is to be placed (the default
17999 @item @samp{@var{gcc_switches}} is a list of switches for
18000 @command{gcc}. They will be passed on to all compiler invocations made by
18001 @command{gnatstub} to generate the ASIS trees. Here you can provide
18002 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18003 use the @option{-gnatec} switch to set the configuration file,
18004 use the @option{-gnat05} switch if sources should be compiled in
18008 is an optional sequence of switches as described in the next section
18011 @node Switches for gnatstub
18012 @section Switches for @command{gnatstub}
18018 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18019 If the destination directory already contains a file with the name of the
18021 for the argument spec file, replace it with the generated body stub.
18023 @item ^-hs^/HEADER=SPEC^
18024 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18025 Put the comment header (i.e., all the comments preceding the
18026 compilation unit) from the source of the library unit declaration
18027 into the body stub.
18029 @item ^-hg^/HEADER=GENERAL^
18030 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18031 Put a sample comment header into the body stub.
18033 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
18034 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
18035 Use the content of the file as the comment header for a generated body stub.
18039 @cindex @option{-IDIR} (@command{gnatstub})
18041 @cindex @option{-I-} (@command{gnatstub})
18044 @item /NOCURRENT_DIRECTORY
18045 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18047 ^These switches have ^This switch has^ the same meaning as in calls to
18049 ^They define ^It defines ^ the source search path in the call to
18050 @command{gcc} issued
18051 by @command{gnatstub} to compile an argument source file.
18053 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18054 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18055 This switch has the same meaning as in calls to @command{gcc}.
18056 It defines the additional configuration file to be passed to the call to
18057 @command{gcc} issued
18058 by @command{gnatstub} to compile an argument source file.
18060 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18061 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18062 (@var{n} is a non-negative integer). Set the maximum line length in the
18063 body stub to @var{n}; the default is 79. The maximum value that can be
18064 specified is 32767. Note that in the special case of configuration
18065 pragma files, the maximum is always 32767 regardless of whether or
18066 not this switch appears.
18068 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18069 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18070 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18071 the generated body sample to @var{n}.
18072 The default indentation is 3.
18074 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18075 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18076 Order local bodies alphabetically. (By default local bodies are ordered
18077 in the same way as the corresponding local specs in the argument spec file.)
18079 @item ^-i^/INDENTATION=^@var{n}
18080 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18081 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18083 @item ^-k^/TREE_FILE=SAVE^
18084 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18085 Do not remove the tree file (i.e., the snapshot of the compiler internal
18086 structures used by @command{gnatstub}) after creating the body stub.
18088 @item ^-l^/LINE_LENGTH=^@var{n}
18089 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18090 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18092 @item ^--no-exception^/NO_EXCEPTION^
18093 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
18094 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18095 This is not always possible for function stubs.
18097 @item ^--no-local-header^/NO_LOCAL_HEADER^
18098 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
18099 Do not place local comment header with unit name before body stub for a
18102 @item ^-o ^/BODY=^@var{body-name}
18103 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18104 Body file name. This should be set if the argument file name does not
18106 the GNAT file naming
18107 conventions. If this switch is omitted the default name for the body will be
18109 from the argument file name according to the GNAT file naming conventions.
18112 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18113 Quiet mode: do not generate a confirmation when a body is
18114 successfully created, and do not generate a message when a body is not
18118 @item ^-r^/TREE_FILE=REUSE^
18119 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18120 Reuse the tree file (if it exists) instead of creating it. Instead of
18121 creating the tree file for the library unit declaration, @command{gnatstub}
18122 tries to find it in the current directory and use it for creating
18123 a body. If the tree file is not found, no body is created. This option
18124 also implies @option{^-k^/SAVE^}, whether or not
18125 the latter is set explicitly.
18127 @item ^-t^/TREE_FILE=OVERWRITE^
18128 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18129 Overwrite the existing tree file. If the current directory already
18130 contains the file which, according to the GNAT file naming rules should
18131 be considered as a tree file for the argument source file,
18133 will refuse to create the tree file needed to create a sample body
18134 unless this option is set.
18136 @item ^-v^/VERBOSE^
18137 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18138 Verbose mode: generate version information.
18142 @c *********************************
18143 @node Creating Unit Tests Using gnattest
18144 @chapter Creating Unit Tests Using @command{gnattest}
18148 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18149 as well as a test driver infrastructure (harness). @command{gnattest} creates
18150 a skeleton for each visible subprogram in the packages under consideration when
18151 they do not exist already.
18153 In order to process source files from a project, @command{gnattest} has to
18154 semantically analyze the sources. Therefore, test skeletons can only be
18155 generated for legal Ada units. If a unit is dependent on other units,
18156 those units should be among the source files of the project or of other projects
18157 imported by this one.
18159 Generated skeletons and harnesses are based on the AUnit testing framework.
18160 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18161 for Java or CppUnit for C++. While it is advised that gnattest users read
18162 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18163 For correct operation of @command{gnattest}, AUnit should be installed and
18164 aunit.gpr must be on the project path. This happens automatically when Aunit
18165 is installed at its default location.
18167 * Running gnattest::
18168 * Switches for gnattest::
18169 * Project Attributes for gnattest::
18171 * Setting Up and Tearing Down the Testing Environment::
18172 * Regenerating Tests::
18173 * Default Test Behavior::
18174 * Testing Primitive Operations of Tagged Types::
18175 * Testing Inheritance::
18176 * Tagged Types Substitutability Testing::
18177 * Testing with Contracts::
18178 * Additional Tests::
18180 * Support for other platforms/run-times::
18182 * Current Limitations::
18185 @node Running gnattest
18186 @section Running @command{gnattest}
18189 @command{gnattest} has a command-line interface of the form
18192 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
18193 @c Expanding @ovar macro inline (explanation in macro def comments)
18194 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18202 specifies the project defining the location of source files. When no
18203 file names are provided on the command line, all sources in the project
18204 are used as input. This switch is required.
18207 is the name of the source file containing the library unit package declaration
18208 for which a test package will be created. The file name may be given with a
18211 @item @samp{@var{gcc_switches}}
18212 is a list of switches for
18213 @command{gcc}. These switches will be passed on to all compiler invocations
18214 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
18215 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18216 use the @option{-gnatec} switch to set the configuration file,
18217 use the @option{-gnat05} switch if sources should be compiled in
18218 Ada 2005 mode, etc.
18221 is an optional sequence of switches as described in the next section.
18225 @command{gnattest} results can be found in two different places.
18228 @item automatic harness:
18229 the harness code, which is located by default in "gnattest/harness" directory
18230 that is created in the object directory of corresponding project file. All of
18231 this code is generated completely automatically and can be destroyed and
18232 regenerated at will. It is not recommended to modify this code manually, since
18233 it could easily be overridden by mistake. The entry point in the harness code is
18234 the project file named @command{test_driver.gpr}. Tests can be compiled and run
18235 using a command such as:
18238 gnatmake -P<harness-dir>/test_driver
18242 Note that you might need to specify the necessary values of scenario variables
18243 when you are not using the AUnit defaults.
18245 @item actual unit test skeletons:
18246 a test skeleton for each visible subprogram is created in a separate file, if it
18247 doesn't exist already. By default, those separate test files are located in a
18248 "gnattest/tests" directory that is created in the object directory of
18249 corresponding project file. For example, if a source file my_unit.ads in
18250 directory src contains a visible subprogram Proc, then the corresponding unit
18251 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
18252 <code> is a signature encoding used to differentiate test names in case of
18255 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
18256 this will cause a name conflict with the generated test package.
18259 @node Switches for gnattest
18260 @section Switches for @command{gnattest}
18265 @item --harness-only
18266 @cindex @option{--harness-only} (@command{gnattest})
18267 When this option is given, @command{gnattest} creates a harness for all
18268 sources, treating them as test packages.
18270 @item --additional-tests=@var{projname}
18271 @cindex @option{--additional-tests} (@command{gnattest})
18272 Sources described in @var{projname} are considered potential additional
18273 manual tests to be added to the test suite.
18276 @cindex @option{-r} (@command{gnattest})
18277 Recursively consider all sources from all projects.
18279 @item -X@var{name=value}
18280 @cindex @option{-X} (@command{gnattest})
18281 Indicate that external variable @var{name} has the value @var{value}.
18284 @cindex @option{-q} (@command{gnattest})
18285 Suppresses noncritical output messages.
18288 @cindex @option{-v} (@command{gnattest})
18289 Verbose mode: generates version information.
18291 @item --validate-type-extensions
18292 @cindex @option{--validate-type-extensions} (@command{gnattest})
18293 Enables substitution check: run all tests from all parents in order
18294 to check substitutability.
18296 @item --skeleton-default=@var{val}
18297 @cindex @option{--skeleton-default} (@command{gnattest})
18298 Specifies the default behavior of generated skeletons. @var{val} can be either
18299 "fail" or "pass", "fail" being the default.
18301 @item --tests-root=@var{dirname}
18302 @cindex @option{--tests-root} (@command{gnattest})
18303 The directory hierarchy of tested sources is recreated in the @var{dirname}
18304 directory, and test packages are placed in corresponding directories.
18305 If the @var{dirname} is a relative path, it is considered relative to the object
18306 directory of the project file. When all sources from all projects are taken
18307 recursively from all projects, directory hierarchies of tested sources are
18308 recreated for each project in their object directories and test packages are
18309 placed accordingly.
18311 @item --subdir=@var{dirname}
18312 @cindex @option{--subdir} (@command{gnattest})
18313 Test packages are placed in subdirectories.
18315 @item --tests-dir=@var{dirname}
18316 @cindex @option{--tests-dir} (@command{gnattest})
18317 All test packages are placed in the @var{dirname} directory.
18318 If the @var{dirname} is a relative path, it is considered relative to the object
18319 directory of the project file. When all sources from all projects are taken
18320 recursively from all projects, @var{dirname} directories are created for each
18321 project in their object directories and test packages are placed accordingly.
18323 @item --harness-dir=@var{dirname}
18324 @cindex @option{--harness-dir} (@command{gnattest})
18325 specifies the directory that will hold the harness packages and project file
18326 for the test driver. If the @var{dirname} is a relative path, it is considered
18327 relative to the object directory of the project file.
18331 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
18332 mutually exclusive.
18334 @node Project Attributes for gnattest
18335 @section Project Attributes for @command{gnattest}
18339 Most of the command-line options can also be passed to the tool by adding
18340 special attributes to the project file. Those attributes should be put in
18341 package gnattest. Here is the list of attributes:
18346 is used to select the same output mode as with the --tests-root option.
18347 This attribute cannot be used together with Subdir or Tests_Dir.
18350 is used to select the same output mode as with the --subdir option.
18351 This attribute cannot be used together with Tests_Root or Tests_Dir.
18354 is used to select the same output mode as with the --tests-dir option.
18355 This attribute cannot be used together with Subdir or Tests_Root.
18358 is used to specify the directory in which to place harness packages and project
18359 file for the test driver, otherwise specified by --harness-dir.
18361 @item Additional_Tests
18362 is used to specify the project file, otherwise given by
18363 --additional-tests switch.
18365 @item Skeletons_Default
18366 is used to specify the default behaviour of test skeletons, otherwise
18367 specified by --skeleton-default option. The value of this attribute
18368 should be either "pass" or "fail".
18372 Each of those attributes can be overridden from the command line if needed.
18373 Other @command{gnattest} switches can also be passed via the project
18374 file as an attribute list called GNATtest_Switches.
18376 @node Simple Example
18377 @section Simple Example
18381 Let's take a very simple example using the first @command{gnattest} example
18385 <install_prefix>/share/examples/gnattest/simple
18388 This project contains a simple package containing one subprogram. By running gnattest:
18391 $ gnattest --harness-dir=driver -Psimple.gpr
18394 a test driver is created in directory "driver". It can be compiled and run:
18398 $ gprbuild -Ptest_driver
18402 One failed test with diagnosis "test not implemented" is reported.
18403 Since no special output option was specified, the test package Simple.Tests
18407 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
18410 For each package containing visible subprograms, a child test package is
18411 generated. It contains one test routine per tested subprogram. Each
18412 declaration of a test subprogram has a comment specifying which tested
18413 subprogram it corresponds to. All of the test routines have separate bodies.
18414 The test routine located at simple-test_data-tests-test_inc_5eaee3.adb contains
18415 a single statement: a call to procedure Assert. It has two arguments:
18416 the Boolean expression we want to check and the diagnosis message to display if
18417 the condition is false.
18419 That is where actual testing code should be written after a proper setup.
18420 An actual check can be performed by replacing the Assert call with:
18422 @smallexample @c ada
18423 Assert (Inc (1) = 2, "wrong incrementation");
18426 After recompiling and running the test driver, one successfully passed test
18429 @node Setting Up and Tearing Down the Testing Environment
18430 @section Setting Up and Tearing Down the Testing Environment
18434 Besides test routines themselves, each test package has a parent package
18435 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
18436 overwritten by the tool. Set_Up is called before each test routine of the
18437 package and Tear_Down is called after each test routine. Those two procedures
18438 can be used to perform necessary initialization and finalization,
18439 memory allocation, etc. Test type declared in Test_Data package is parent type
18440 for the test type of test package and can have user-defined components whose
18441 values can be set by Set_Up routine and used in test routines afterwards.
18443 @node Regenerating Tests
18444 @section Regenerating Tests
18448 Bodies of test routines and test_data packages are never overridden after they
18449 have been created once. As long as the name of the subprogram, full expanded Ada
18450 names, and the order of its parameters is the same, the old test routine will
18451 fit in its place and no test skeleton will be generated for the subprogram.
18453 This can be demonstrated with the previous example. By uncommenting declaration
18454 and body of function Dec in simple.ads and simple.adb, running
18455 @command{gnattest} on the project, and then running the test driver:
18458 gnattest --harness-dir=driver -Psimple.gpr
18460 gprbuild -Ptest_driver
18464 the old test is not replaced with a stub, nor is it lost, but a new test
18465 skeleton is created for function Dec.
18467 The only way of regenerating tests skeletons is to remove the previously created
18470 @node Default Test Behavior
18471 @section Default Test Behavior
18475 The generated test driver can treat unimplemented tests in two ways:
18476 either count them all as failed (this is useful to see which tests are still
18477 left to implement) or as passed (to sort out unimplemented ones from those
18480 The test driver accepts a switch to specify this behavior:
18481 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
18482 @command{gnattest}).
18484 The default behavior of the test driver is set with the same switch
18485 as passed to gnattest when generating the test driver.
18487 Passing it to the driver generated on the first example:
18490 test_runner --skeleton-default=pass
18493 makes both tests pass, even the unimplemented one.
18495 @node Testing Primitive Operations of Tagged Types
18496 @section Testing Primitive Operations of Tagged Types
18500 Creation of test skeletons for primitive operations of tagged types entails
18501 a number of features. Test routines for all primitives of a given tagged type
18502 are placed in a separate child package named according to the tagged type. For
18503 example, if you have tagged type T in package P, all tests for primitives
18504 of T will be in P.T_Test_Data.T_Tests.
18506 Consider running gnattest on the second example (note: actual tests for this
18507 example already exist, so there's no need to worry if the tool reports that
18508 no new stubs were generated):
18511 cd <install_prefix>/share/examples/gnattest/tagged_rec
18512 gnattest --harness-dir=driver -Ptagged_rec.gpr
18515 Taking a closer look at the test type declared in the test package
18516 Speed1.Controller_Test_Data is necessary. It is declared in:
18519 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
18522 Test types are direct or indirect descendants of
18523 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18524 subprograms, the user doesn't need to be concerned with them. However,
18525 when generating test packages for primitive operations, there are some things
18526 the user needs to know.
18528 Type Test_Controller has components that allow assignment of various
18529 derivations of type Controller. And if you look at the specification of
18530 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18531 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18532 Thus, test types mirror the hierarchy of tested types.
18534 The Set_Up procedure of Test_Data package corresponding to a test package
18535 of primitive operations of type T assigns to Fixture a reference to an
18536 object of that exact type T. Notice, however, that if the tagged type has
18537 discriminants, the Set_Up only has a commented template for setting
18538 up the fixture, since filling the discriminant with actual value is up
18541 The knowledge of the structure of test types allows additional testing
18542 without additional effort. Those possibilities are described below.
18544 @node Testing Inheritance
18545 @section Testing Inheritance
18549 Since the test type hierarchy mimics the hierarchy of tested types, the
18550 inheritance of tests takes place. An example of such inheritance can be
18551 seen by running the test driver generated for the second example. As previously
18552 mentioned, actual tests are already written for this example.
18556 gprbuild -Ptest_driver
18560 There are 6 passed tests while there are only 5 testable subprograms. The test
18561 routine for function Speed has been inherited and run against objects of the
18564 @node Tagged Types Substitutability Testing
18565 @section Tagged Types Substitutability Testing
18569 Tagged Types Substitutability Testing is a way of verifying the global type
18570 consistency by testing. Global type consistency is a principle stating that if
18571 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18572 then objects of type T may be replaced with objects of type S (that is,
18573 objects of type S may be substituted for objects of type T), without
18574 altering any of the desirable properties of the program. When the properties
18575 of the program are expressed in the form of subprogram preconditions and
18576 postconditions (let's call them pre and post), the principle is formulated as
18577 relations between the pre and post of primitive operations and the pre and post
18578 of their derived operations. The pre of a derived operation should not be
18579 stronger than the original pre, and the post of the derived operation should
18580 not be weaker than the original post. Those relations ensure that verifying if
18581 a dispatching call is safe can be done just by using the pre and post of the
18584 Verifying global type consistency by testing consists of running all the unit
18585 tests associated with the primitives of a given tagged type with objects of its
18588 In the example used in the previous section, there was clearly a violation of
18589 type consistency. The overriding primitive Adjust_Speed in package Speed2
18590 removes the functionality of the overridden primitive and thus doesn't respect
18591 the consistency principle.
18592 Gnattest has a special option to run overridden parent tests against objects
18593 of the type which have overriding primitives:
18596 gnattest --harness-dir=driver --liskov -Ptagged_rec.gpr
18598 gprbuild -Ptest_driver
18602 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18603 against objects of the derived type.
18605 Non-overridden tests are already inherited for derived test types, so the
18606 --validate-type-extensions enables the application of overriden tests to objects
18609 @node Testing with Contracts
18610 @section Testing with Contracts
18614 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
18615 as well as corresponding aspects.
18616 Test routines are generated, one per each Test_Case associated with a tested
18617 subprogram. Those test routines have special wrappers for tested functions
18618 that have composition of pre- and postcondition of the subprogram with
18619 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18620 either count for Nominal mode or do not count for Robustness mode).
18622 The third example demonstrates how this works:
18625 cd <install_prefix>/share/examples/gnattest/contracts
18626 gnattest --harness-dir=driver -Pcontracts.gpr
18629 Putting actual checks within the range of the contract does not cause any
18630 error reports. For example, for the test routine which corresponds to
18633 @smallexample @c ada
18634 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18637 and for the test routine corresponding to test case 2:
18639 @smallexample @c ada
18640 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18647 gprbuild -Ptest_driver
18651 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18652 a precondition violation for test case one. Also, by using any otherwise
18653 correct but positive pair of numbers in the second test routine, you can also
18654 get a precondition violation. Postconditions are checked and reported
18657 @node Additional Tests
18658 @section Additional Tests
18661 @command{gnattest} can add user-written tests to the main suite of the test
18662 driver. @command{gnattest} traverses the given packages and searches for test
18663 routines. All procedures with a single in out parameter of a type which is
18664 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18665 specifications are added to the suites and are then executed by the test driver.
18666 (Set_Up and Tear_Down are filtered out.)
18668 An example illustrates two ways of creating test harnesses for user-written
18669 tests. Directory additional_tests contains an AUnit-based test driver written
18673 <install_prefix>/share/examples/gnattest/additional_tests/
18676 To create a test driver for already-written tests, use the --harness-only
18680 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18682 gnatmake -Pharness_only/test_driver.gpr
18683 harness_only/test_runner
18686 Additional tests can also be executed together with generated tests:
18689 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18690 --harness-dir=mixing
18691 gnatmake -Pmixing/test_driver.gpr
18696 @node Support for other platforms/run-times
18697 @section Support for other platforms/run-times
18700 @command{gnattest} can be used to generate the test harness for platforms
18701 and run-time libraries others than the default native target with the
18702 default full run-time. For example, when using a limited run-time library
18703 such as Zero FootPrint (ZFP), a simplified harness is generated.
18705 Two variables are used to tell the underlying AUnit framework how to generate
18706 the test harness: @code{PLATFORM}, which identifies the target, and
18707 @code{RUNTIME}, used to determine the run-time library for which the harness
18708 is generated. Corresponding prefix should also be used when calling
18709 @command{gnattest} for non-native targets. For example, the following options
18710 are used to generate the AUnit test harness for a PowerPC ELF target using
18711 the ZFP run-time library:
18714 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
18718 @node Current Limitations
18719 @section Current Limitations
18723 The tool currently does not support following features:
18726 @item generic tests for generic packages and package instantiations
18727 @item tests for protected subprograms and entries
18731 @c *********************************
18732 @node Performing Dimensionality Analysis in GNAT
18733 @chapter Performing Dimensionality Analysis in GNAT
18735 The GNAT compiler now supports dimensionality checking. The user can
18736 specify physical units for objects, and the compiler will verify that uses
18737 of these objects are compatible with their dimensions, in a fashion that is
18738 familiar to engineering practice. The dimensions of algebraic expressions
18739 (including powers with static exponents) are computed from their consistuents.
18741 This feature depends on Ada 2012 aspect specifications, and is available from
18742 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
18743 the user to define a system of units; the aspect Dimension then allows the user
18744 to declare dimensioned quantities within a given system.
18746 The major advantage of this model is that it does not require the declaration of
18747 multiple operators for all possible combinations of types: it is only necessary
18748 to use the proper subtypes in object declarations.
18750 The simplest way to impose dimensionality checking on a computation is to make
18751 use of the package System.Dim.Mks, which is part of the GNAT library. This
18752 package defines a floating-point type MKS_Type, for which a sequence of
18753 dimension names are specified, together with their conventional abbreviations.
18754 The following should be read together with the full specification of the
18755 package, in file s-dimmks.ads.
18757 @smallexample @c ada
18758 type Mks_Type is new Long_Long_Float
18760 Dimension_System => (
18761 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
18762 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
18763 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
18764 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
18765 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
18766 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
18767 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
18771 The package then defines a series of subtypes that correspond to these
18772 conventional units. For example:
18773 @smallexample @c ada
18774 subtype Length is Mks_Type
18776 Dimension => (Symbol => 'm',
18781 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
18782 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
18785 The package also defines conventional names for values of each unit, for
18788 @smallexample @c ada
18789 m : constant Length := 1.0;
18790 kg : constant Mass := 1.0;
18791 s : constant Time := 1.0;
18792 A : constant Electric_Current := 1.0;
18796 as well as useful multiples of these units:
18798 @smallexample @c ada
18799 cm : constant Length := 1.0E-02;
18800 g : constant Mass := 1.0E-03;
18801 min : constant Time := 60.0;
18802 day : constant TIme := 60.0 * 24.0 * min;
18807 The user can then define a derived unit by providing the aspect that
18808 specifies its dimensions within the MKS system, as well as the string to
18809 be used for output of a value of that unit:
18811 @smallexample @c ada
18812 subtype Acceleration is Mks_Type
18813 with Dimension => ("m/sec^^^2", Meter => 1, Second => -2, others => 0);
18817 Here is a complete example of use:
18819 @smallexample @c ada
18820 with System.Dim.MKS; use System.Dim.Mks;
18821 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
18822 with Text_IO; use Text_IO;
18823 procedure Free_Fall is
18824 subtype Acceleration is Mks_Type
18825 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
18826 G : constant acceleration := 9.81 * m / (s ** 2);
18827 T : Time := 10.0*s;
18830 Put ("Gravitational constant: ");
18831 Put (G, Aft => 2, Exp => 0); Put_Line ("");
18832 Distance := 0.5 * G * T ** 2;
18833 Put ("distance travelled in 10 seconds of free fall ");
18834 Put (Distance, Aft => 2, Exp => 0);
18840 Execution of this program yields:
18842 Gravitational constant: 9.81 m/sec^^^2
18843 distance travelled in 10 seconds of free fall 490.50 m
18847 However, incorrect assignments such as:
18849 @smallexample @c ada
18851 Distance := 5.0 * kg:
18855 are rejected with the following diagnoses:
18859 >>> dimensions mismatch in assignment
18860 >>> left-hand side has dimension [L]
18861 >>> right-hand side is dimensionless
18863 Distance := 5.0 * kg:
18864 >>> dimensions mismatch in assignment
18865 >>> left-hand side has dimension [L]
18866 >>> right-hand side has dimension [M]
18870 The dimensions of an expression are properly displayed, even if there is
18871 no explicit subtype for it. If we add to the program:
18873 @smallexample @c ada
18874 Put ("Final velocity: ");
18875 Put (G * T, Aft =>2, Exp =>0);
18880 then the output includes:
18882 Final velocity: 98.10 m.s**(-1)
18885 @c *********************************
18886 @node Generating Ada Bindings for C and C++ headers
18887 @chapter Generating Ada Bindings for C and C++ headers
18891 GNAT now comes with a binding generator for C and C++ headers which is
18892 intended to do 95% of the tedious work of generating Ada specs from C
18893 or C++ header files.
18895 Note that this capability is not intended to generate 100% correct Ada specs,
18896 and will is some cases require manual adjustments, although it can often
18897 be used out of the box in practice.
18899 Some of the known limitations include:
18902 @item only very simple character constant macros are translated into Ada
18903 constants. Function macros (macros with arguments) are partially translated
18904 as comments, to be completed manually if needed.
18905 @item some extensions (e.g. vector types) are not supported
18906 @item pointers to pointers or complex structures are mapped to System.Address
18907 @item identifiers with identical name (except casing) will generate compilation
18908 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
18911 The code generated is using the Ada 2005 syntax, which makes it
18912 easier to interface with other languages than previous versions of Ada.
18915 * Running the binding generator::
18916 * Generating bindings for C++ headers::
18920 @node Running the binding generator
18921 @section Running the binding generator
18924 The binding generator is part of the @command{gcc} compiler and can be
18925 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18926 spec files for the header files specified on the command line, and all
18927 header files needed by these files transitively. For example:
18930 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18931 $ gcc -c -gnat05 *.ads
18934 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18935 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18936 correspond to the files @file{/usr/include/time.h},
18937 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18938 mode these Ada specs.
18940 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18941 and will attempt to generate corresponding Ada comments.
18943 If you want to generate a single Ada file and not the transitive closure, you
18944 can use instead the @option{-fdump-ada-spec-slim} switch.
18946 You can optionally specify a parent unit, of which all generated units will
18947 be children, using @code{-fada-spec-parent=}@var{unit}.
18949 Note that we recommend when possible to use the @command{g++} driver to
18950 generate bindings, even for most C headers, since this will in general
18951 generate better Ada specs. For generating bindings for C++ headers, it is
18952 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18953 is equivalent in this case. If @command{g++} cannot work on your C headers
18954 because of incompatibilities between C and C++, then you can fallback to
18955 @command{gcc} instead.
18957 For an example of better bindings generated from the C++ front-end,
18958 the name of the parameters (when available) are actually ignored by the C
18959 front-end. Consider the following C header:
18962 extern void foo (int variable);
18965 with the C front-end, @code{variable} is ignored, and the above is handled as:
18968 extern void foo (int);
18971 generating a generic:
18974 procedure foo (param1 : int);
18977 with the C++ front-end, the name is available, and we generate:
18980 procedure foo (variable : int);
18983 In some cases, the generated bindings will be more complete or more meaningful
18984 when defining some macros, which you can do via the @option{-D} switch. This
18985 is for example the case with @file{Xlib.h} under GNU/Linux:
18988 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18991 The above will generate more complete bindings than a straight call without
18992 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18994 In other cases, it is not possible to parse a header file in a stand-alone
18995 manner, because other include files need to be included first. In this
18996 case, the solution is to create a small header file including the needed
18997 @code{#include} and possible @code{#define} directives. For example, to
18998 generate Ada bindings for @file{readline/readline.h}, you need to first
18999 include @file{stdio.h}, so you can create a file with the following two
19000 lines in e.g. @file{readline1.h}:
19004 #include <readline/readline.h>
19007 and then generate Ada bindings from this file:
19010 $ g++ -c -fdump-ada-spec readline1.h
19013 @node Generating bindings for C++ headers
19014 @section Generating bindings for C++ headers
19017 Generating bindings for C++ headers is done using the same options, always
19018 with the @command{g++} compiler.
19020 In this mode, C++ classes will be mapped to Ada tagged types, constructors
19021 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
19022 multiple inheritance of abstract classes will be mapped to Ada interfaces
19023 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
19024 information on interfacing to C++).
19026 For example, given the following C++ header file:
19033 virtual int Number_Of_Teeth () = 0;
19038 virtual void Set_Owner (char* Name) = 0;
19044 virtual void Set_Age (int New_Age);
19047 class Dog : Animal, Carnivore, Domestic @{
19052 virtual int Number_Of_Teeth ();
19053 virtual void Set_Owner (char* Name);
19061 The corresponding Ada code is generated:
19063 @smallexample @c ada
19066 package Class_Carnivore is
19067 type Carnivore is limited interface;
19068 pragma Import (CPP, Carnivore);
19070 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
19072 use Class_Carnivore;
19074 package Class_Domestic is
19075 type Domestic is limited interface;
19076 pragma Import (CPP, Domestic);
19078 procedure Set_Owner
19079 (this : access Domestic;
19080 Name : Interfaces.C.Strings.chars_ptr) is abstract;
19082 use Class_Domestic;
19084 package Class_Animal is
19085 type Animal is tagged limited record
19086 Age_Count : aliased int;
19088 pragma Import (CPP, Animal);
19090 procedure Set_Age (this : access Animal; New_Age : int);
19091 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
19095 package Class_Dog is
19096 type Dog is new Animal and Carnivore and Domestic with record
19097 Tooth_Count : aliased int;
19098 Owner : Interfaces.C.Strings.chars_ptr;
19100 pragma Import (CPP, Dog);
19102 function Number_Of_Teeth (this : access Dog) return int;
19103 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
19105 procedure Set_Owner
19106 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
19107 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
19109 function New_Dog return Dog;
19110 pragma CPP_Constructor (New_Dog);
19111 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
19122 @item -fdump-ada-spec
19123 @cindex @option{-fdump-ada-spec} (@command{gcc})
19124 Generate Ada spec files for the given header files transitively (including
19125 all header files that these headers depend upon).
19127 @item -fdump-ada-spec-slim
19128 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
19129 Generate Ada spec files for the header files specified on the command line
19132 @item -fada-spec-parent=@var{unit}
19133 @cindex -fada-spec-parent (@command{gcc})
19134 Specifies that all files generated by @option{-fdump-ada-spec-slim} are
19135 to be child units of the specified parent unit.
19138 @cindex @option{-C} (@command{gcc})
19139 Extract comments from headers and generate Ada comments in the Ada spec files.
19142 @node Other Utility Programs
19143 @chapter Other Utility Programs
19146 This chapter discusses some other utility programs available in the Ada
19150 * Using Other Utility Programs with GNAT::
19151 * The External Symbol Naming Scheme of GNAT::
19152 * Converting Ada Files to html with gnathtml::
19153 * Installing gnathtml::
19160 @node Using Other Utility Programs with GNAT
19161 @section Using Other Utility Programs with GNAT
19164 The object files generated by GNAT are in standard system format and in
19165 particular the debugging information uses this format. This means
19166 programs generated by GNAT can be used with existing utilities that
19167 depend on these formats.
19170 In general, any utility program that works with C will also often work with
19171 Ada programs generated by GNAT. This includes software utilities such as
19172 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19176 @node The External Symbol Naming Scheme of GNAT
19177 @section The External Symbol Naming Scheme of GNAT
19180 In order to interpret the output from GNAT, when using tools that are
19181 originally intended for use with other languages, it is useful to
19182 understand the conventions used to generate link names from the Ada
19185 All link names are in all lowercase letters. With the exception of library
19186 procedure names, the mechanism used is simply to use the full expanded
19187 Ada name with dots replaced by double underscores. For example, suppose
19188 we have the following package spec:
19190 @smallexample @c ada
19201 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19202 the corresponding link name is @code{qrs__mn}.
19204 Of course if a @code{pragma Export} is used this may be overridden:
19206 @smallexample @c ada
19211 pragma Export (Var1, C, External_Name => "var1_name");
19213 pragma Export (Var2, C, Link_Name => "var2_link_name");
19220 In this case, the link name for @var{Var1} is whatever link name the
19221 C compiler would assign for the C function @var{var1_name}. This typically
19222 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19223 system conventions, but other possibilities exist. The link name for
19224 @var{Var2} is @var{var2_link_name}, and this is not operating system
19228 One exception occurs for library level procedures. A potential ambiguity
19229 arises between the required name @code{_main} for the C main program,
19230 and the name we would otherwise assign to an Ada library level procedure
19231 called @code{Main} (which might well not be the main program).
19233 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19234 names. So if we have a library level procedure such as
19236 @smallexample @c ada
19239 procedure Hello (S : String);
19245 the external name of this procedure will be @var{_ada_hello}.
19248 @node Converting Ada Files to html with gnathtml
19249 @section Converting Ada Files to HTML with @code{gnathtml}
19252 This @code{Perl} script allows Ada source files to be browsed using
19253 standard Web browsers. For installation procedure, see the section
19254 @xref{Installing gnathtml}.
19256 Ada reserved keywords are highlighted in a bold font and Ada comments in
19257 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19258 switch to suppress the generation of cross-referencing information, user
19259 defined variables and types will appear in a different color; you will
19260 be able to click on any identifier and go to its declaration.
19262 The command line is as follow:
19264 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
19265 @c Expanding @ovar macro inline (explanation in macro def comments)
19266 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
19270 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19271 an html file for every ada file, and a global file called @file{index.htm}.
19272 This file is an index of every identifier defined in the files.
19274 The available ^switches^options^ are the following ones:
19278 @cindex @option{-83} (@code{gnathtml})
19279 Only the Ada 83 subset of keywords will be highlighted.
19281 @item -cc @var{color}
19282 @cindex @option{-cc} (@code{gnathtml})
19283 This option allows you to change the color used for comments. The default
19284 value is green. The color argument can be any name accepted by html.
19287 @cindex @option{-d} (@code{gnathtml})
19288 If the Ada files depend on some other files (for instance through
19289 @code{with} clauses, the latter files will also be converted to html.
19290 Only the files in the user project will be converted to html, not the files
19291 in the run-time library itself.
19294 @cindex @option{-D} (@code{gnathtml})
19295 This command is the same as @option{-d} above, but @command{gnathtml} will
19296 also look for files in the run-time library, and generate html files for them.
19298 @item -ext @var{extension}
19299 @cindex @option{-ext} (@code{gnathtml})
19300 This option allows you to change the extension of the generated HTML files.
19301 If you do not specify an extension, it will default to @file{htm}.
19304 @cindex @option{-f} (@code{gnathtml})
19305 By default, gnathtml will generate html links only for global entities
19306 ('with'ed units, global variables and types,@dots{}). If you specify
19307 @option{-f} on the command line, then links will be generated for local
19310 @item -l @var{number}
19311 @cindex @option{-l} (@code{gnathtml})
19312 If this ^switch^option^ is provided and @var{number} is not 0, then
19313 @code{gnathtml} will number the html files every @var{number} line.
19316 @cindex @option{-I} (@code{gnathtml})
19317 Specify a directory to search for library files (@file{.ALI} files) and
19318 source files. You can provide several -I switches on the command line,
19319 and the directories will be parsed in the order of the command line.
19322 @cindex @option{-o} (@code{gnathtml})
19323 Specify the output directory for html files. By default, gnathtml will
19324 saved the generated html files in a subdirectory named @file{html/}.
19326 @item -p @var{file}
19327 @cindex @option{-p} (@code{gnathtml})
19328 If you are using Emacs and the most recent Emacs Ada mode, which provides
19329 a full Integrated Development Environment for compiling, checking,
19330 running and debugging applications, you may use @file{.gpr} files
19331 to give the directories where Emacs can find sources and object files.
19333 Using this ^switch^option^, you can tell gnathtml to use these files.
19334 This allows you to get an html version of your application, even if it
19335 is spread over multiple directories.
19337 @item -sc @var{color}
19338 @cindex @option{-sc} (@code{gnathtml})
19339 This ^switch^option^ allows you to change the color used for symbol
19341 The default value is red. The color argument can be any name accepted by html.
19343 @item -t @var{file}
19344 @cindex @option{-t} (@code{gnathtml})
19345 This ^switch^option^ provides the name of a file. This file contains a list of
19346 file names to be converted, and the effect is exactly as though they had
19347 appeared explicitly on the command line. This
19348 is the recommended way to work around the command line length limit on some
19353 @node Installing gnathtml
19354 @section Installing @code{gnathtml}
19357 @code{Perl} needs to be installed on your machine to run this script.
19358 @code{Perl} is freely available for almost every architecture and
19359 Operating System via the Internet.
19361 On Unix systems, you may want to modify the first line of the script
19362 @code{gnathtml}, to explicitly tell the Operating system where Perl
19363 is. The syntax of this line is:
19365 #!full_path_name_to_perl
19369 Alternatively, you may run the script using the following command line:
19372 @c $ perl gnathtml.pl @ovar{switches} @var{files}
19373 @c Expanding @ovar macro inline (explanation in macro def comments)
19374 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
19383 The GNAT distribution provides an Ada 95 template for the HP Language
19384 Sensitive Editor (LSE), a component of DECset. In order to
19385 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19392 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19393 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19394 the collection phase with the /DEBUG qualifier.
19397 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19398 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19399 $ RUN/DEBUG <PROGRAM_NAME>
19405 @c ******************************
19406 @node Code Coverage and Profiling
19407 @chapter Code Coverage and Profiling
19408 @cindex Code Coverage
19412 This chapter describes how to use @code{gcov} - coverage testing tool - and
19413 @code{gprof} - profiler tool - on your Ada programs.
19416 * Code Coverage of Ada Programs using gcov::
19417 * Profiling an Ada Program using gprof::
19420 @node Code Coverage of Ada Programs using gcov
19421 @section Code Coverage of Ada Programs using gcov
19423 @cindex -fprofile-arcs
19424 @cindex -ftest-coverage
19426 @cindex Code Coverage
19429 @code{gcov} is a test coverage program: it analyzes the execution of a given
19430 program on selected tests, to help you determine the portions of the program
19431 that are still untested.
19433 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
19434 User's Guide. You can refer to this documentation for a more complete
19437 This chapter provides a quick startup guide, and
19438 details some Gnat-specific features.
19441 * Quick startup guide::
19445 @node Quick startup guide
19446 @subsection Quick startup guide
19448 In order to perform coverage analysis of a program using @code{gcov}, 3
19453 Code instrumentation during the compilation process
19455 Execution of the instrumented program
19457 Execution of the @code{gcov} tool to generate the result.
19460 The code instrumentation needed by gcov is created at the object level:
19461 The source code is not modified in any way, because the instrumentation code is
19462 inserted by gcc during the compilation process. To compile your code with code
19463 coverage activated, you need to recompile your whole project using the
19465 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19466 @code{-fprofile-arcs}.
19469 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19470 -largs -fprofile-arcs
19473 This compilation process will create @file{.gcno} files together with
19474 the usual object files.
19476 Once the program is compiled with coverage instrumentation, you can
19477 run it as many times as needed - on portions of a test suite for
19478 example. The first execution will produce @file{.gcda} files at the
19479 same location as the @file{.gcno} files. The following executions
19480 will update those files, so that a cumulative result of the covered
19481 portions of the program is generated.
19483 Finally, you need to call the @code{gcov} tool. The different options of
19484 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
19486 This will create annotated source files with a @file{.gcov} extension:
19487 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
19489 @node Gnat specifics
19490 @subsection Gnat specifics
19492 Because Ada semantics, portions of the source code may be shared among
19493 several object files. This is the case for example when generics are
19494 involved, when inlining is active or when declarations generate initialisation
19495 calls. In order to take
19496 into account this shared code, you need to call @code{gcov} on all
19497 source files of the tested program at once.
19499 The list of source files might exceed the system's maximum command line
19500 length. In order to bypass this limitation, a new mechanism has been
19501 implemented in @code{gcov}: you can now list all your project's files into a
19502 text file, and provide this file to gcov as a parameter, preceded by a @@
19503 (e.g. @samp{gcov @@mysrclist.txt}).
19505 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
19506 not supported as there can be unresolved symbols during the final link.
19508 @node Profiling an Ada Program using gprof
19509 @section Profiling an Ada Program using gprof
19515 This section is not meant to be an exhaustive documentation of @code{gprof}.
19516 Full documentation for it can be found in the GNU Profiler User's Guide
19517 documentation that is part of this GNAT distribution.
19519 Profiling a program helps determine the parts of a program that are executed
19520 most often, and are therefore the most time-consuming.
19522 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19523 better handle Ada programs and multitasking.
19524 It is currently supported on the following platforms
19529 solaris sparc/sparc64/x86
19535 In order to profile a program using @code{gprof}, 3 steps are needed:
19539 Code instrumentation, requiring a full recompilation of the project with the
19542 Execution of the program under the analysis conditions, i.e. with the desired
19545 Analysis of the results using the @code{gprof} tool.
19549 The following sections detail the different steps, and indicate how
19550 to interpret the results:
19552 * Compilation for profiling::
19553 * Program execution::
19555 * Interpretation of profiling results::
19558 @node Compilation for profiling
19559 @subsection Compilation for profiling
19563 In order to profile a program the first step is to tell the compiler
19564 to generate the necessary profiling information. The compiler switch to be used
19565 is @code{-pg}, which must be added to other compilation switches. This
19566 switch needs to be specified both during compilation and link stages, and can
19567 be specified once when using gnatmake:
19570 gnatmake -f -pg -P my_project
19574 Note that only the objects that were compiled with the @samp{-pg} switch will
19575 be profiled; if you need to profile your whole project, use the @samp{-f}
19576 gnatmake switch to force full recompilation.
19578 @node Program execution
19579 @subsection Program execution
19582 Once the program has been compiled for profiling, you can run it as usual.
19584 The only constraint imposed by profiling is that the program must terminate
19585 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19588 Once the program completes execution, a data file called @file{gmon.out} is
19589 generated in the directory where the program was launched from. If this file
19590 already exists, it will be overwritten.
19592 @node Running gprof
19593 @subsection Running gprof
19596 The @code{gprof} tool is called as follow:
19599 gprof my_prog gmon.out
19610 The complete form of the gprof command line is the following:
19613 gprof [^switches^options^] [executable [data-file]]
19617 @code{gprof} supports numerous ^switch^options^. The order of these
19618 ^switch^options^ does not matter. The full list of options can be found in
19619 the GNU Profiler User's Guide documentation that comes with this documentation.
19621 The following is the subset of those switches that is most relevant:
19625 @item --demangle[=@var{style}]
19626 @itemx --no-demangle
19627 @cindex @option{--demangle} (@code{gprof})
19628 These options control whether symbol names should be demangled when
19629 printing output. The default is to demangle C++ symbols. The
19630 @code{--no-demangle} option may be used to turn off demangling. Different
19631 compilers have different mangling styles. The optional demangling style
19632 argument can be used to choose an appropriate demangling style for your
19633 compiler, in particular Ada symbols generated by GNAT can be demangled using
19634 @code{--demangle=gnat}.
19636 @item -e @var{function_name}
19637 @cindex @option{-e} (@code{gprof})
19638 The @samp{-e @var{function}} option tells @code{gprof} not to print
19639 information about the function @var{function_name} (and its
19640 children@dots{}) in the call graph. The function will still be listed
19641 as a child of any functions that call it, but its index number will be
19642 shown as @samp{[not printed]}. More than one @samp{-e} option may be
19643 given; only one @var{function_name} may be indicated with each @samp{-e}
19646 @item -E @var{function_name}
19647 @cindex @option{-E} (@code{gprof})
19648 The @code{-E @var{function}} option works like the @code{-e} option, but
19649 execution time spent in the function (and children who were not called from
19650 anywhere else), will not be used to compute the percentages-of-time for
19651 the call graph. More than one @samp{-E} option may be given; only one
19652 @var{function_name} may be indicated with each @samp{-E} option.
19654 @item -f @var{function_name}
19655 @cindex @option{-f} (@code{gprof})
19656 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19657 call graph to the function @var{function_name} and its children (and
19658 their children@dots{}). More than one @samp{-f} option may be given;
19659 only one @var{function_name} may be indicated with each @samp{-f}
19662 @item -F @var{function_name}
19663 @cindex @option{-F} (@code{gprof})
19664 The @samp{-F @var{function}} option works like the @code{-f} option, but
19665 only time spent in the function and its children (and their
19666 children@dots{}) will be used to determine total-time and
19667 percentages-of-time for the call graph. More than one @samp{-F} option
19668 may be given; only one @var{function_name} may be indicated with each
19669 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
19673 @node Interpretation of profiling results
19674 @subsection Interpretation of profiling results
19678 The results of the profiling analysis are represented by two arrays: the
19679 'flat profile' and the 'call graph'. Full documentation of those outputs
19680 can be found in the GNU Profiler User's Guide.
19682 The flat profile shows the time spent in each function of the program, and how
19683 many time it has been called. This allows you to locate easily the most
19684 time-consuming functions.
19686 The call graph shows, for each subprogram, the subprograms that call it,
19687 and the subprograms that it calls. It also provides an estimate of the time
19688 spent in each of those callers/called subprograms.
19691 @c ******************************
19692 @node Running and Debugging Ada Programs
19693 @chapter Running and Debugging Ada Programs
19697 This chapter discusses how to debug Ada programs.
19699 It applies to GNAT on the Alpha OpenVMS platform;
19700 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19701 since HP has implemented Ada support in the OpenVMS debugger on I64.
19704 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19708 The illegality may be a violation of the static semantics of Ada. In
19709 that case GNAT diagnoses the constructs in the program that are illegal.
19710 It is then a straightforward matter for the user to modify those parts of
19714 The illegality may be a violation of the dynamic semantics of Ada. In
19715 that case the program compiles and executes, but may generate incorrect
19716 results, or may terminate abnormally with some exception.
19719 When presented with a program that contains convoluted errors, GNAT
19720 itself may terminate abnormally without providing full diagnostics on
19721 the incorrect user program.
19725 * The GNAT Debugger GDB::
19727 * Introduction to GDB Commands::
19728 * Using Ada Expressions::
19729 * Calling User-Defined Subprograms::
19730 * Using the Next Command in a Function::
19733 * Debugging Generic Units::
19734 * Remote Debugging using gdbserver::
19735 * GNAT Abnormal Termination or Failure to Terminate::
19736 * Naming Conventions for GNAT Source Files::
19737 * Getting Internal Debugging Information::
19738 * Stack Traceback::
19744 @node The GNAT Debugger GDB
19745 @section The GNAT Debugger GDB
19748 @code{GDB} is a general purpose, platform-independent debugger that
19749 can be used to debug mixed-language programs compiled with @command{gcc},
19750 and in particular is capable of debugging Ada programs compiled with
19751 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19752 complex Ada data structures.
19754 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19756 located in the GNU:[DOCS] directory,
19758 for full details on the usage of @code{GDB}, including a section on
19759 its usage on programs. This manual should be consulted for full
19760 details. The section that follows is a brief introduction to the
19761 philosophy and use of @code{GDB}.
19763 When GNAT programs are compiled, the compiler optionally writes debugging
19764 information into the generated object file, including information on
19765 line numbers, and on declared types and variables. This information is
19766 separate from the generated code. It makes the object files considerably
19767 larger, but it does not add to the size of the actual executable that
19768 will be loaded into memory, and has no impact on run-time performance. The
19769 generation of debug information is triggered by the use of the
19770 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19771 used to carry out the compilations. It is important to emphasize that
19772 the use of these options does not change the generated code.
19774 The debugging information is written in standard system formats that
19775 are used by many tools, including debuggers and profilers. The format
19776 of the information is typically designed to describe C types and
19777 semantics, but GNAT implements a translation scheme which allows full
19778 details about Ada types and variables to be encoded into these
19779 standard C formats. Details of this encoding scheme may be found in
19780 the file exp_dbug.ads in the GNAT source distribution. However, the
19781 details of this encoding are, in general, of no interest to a user,
19782 since @code{GDB} automatically performs the necessary decoding.
19784 When a program is bound and linked, the debugging information is
19785 collected from the object files, and stored in the executable image of
19786 the program. Again, this process significantly increases the size of
19787 the generated executable file, but it does not increase the size of
19788 the executable program itself. Furthermore, if this program is run in
19789 the normal manner, it runs exactly as if the debug information were
19790 not present, and takes no more actual memory.
19792 However, if the program is run under control of @code{GDB}, the
19793 debugger is activated. The image of the program is loaded, at which
19794 point it is ready to run. If a run command is given, then the program
19795 will run exactly as it would have if @code{GDB} were not present. This
19796 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
19797 entirely non-intrusive until a breakpoint is encountered. If no
19798 breakpoint is ever hit, the program will run exactly as it would if no
19799 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19800 the debugging information and can respond to user commands to inspect
19801 variables, and more generally to report on the state of execution.
19805 @section Running GDB
19808 This section describes how to initiate the debugger.
19809 @c The above sentence is really just filler, but it was otherwise
19810 @c clumsy to get the first paragraph nonindented given the conditional
19811 @c nature of the description
19814 The debugger can be launched from a @code{GPS} menu or
19815 directly from the command line. The description below covers the latter use.
19816 All the commands shown can be used in the @code{GPS} debug console window,
19817 but there are usually more GUI-based ways to achieve the same effect.
19820 The command to run @code{GDB} is
19823 $ ^gdb program^GDB PROGRAM^
19827 where @code{^program^PROGRAM^} is the name of the executable file. This
19828 activates the debugger and results in a prompt for debugger commands.
19829 The simplest command is simply @code{run}, which causes the program to run
19830 exactly as if the debugger were not present. The following section
19831 describes some of the additional commands that can be given to @code{GDB}.
19833 @c *******************************
19834 @node Introduction to GDB Commands
19835 @section Introduction to GDB Commands
19838 @code{GDB} contains a large repertoire of commands. @xref{Top,,
19839 Debugging with GDB, gdb, Debugging with GDB},
19841 located in the GNU:[DOCS] directory,
19843 for extensive documentation on the use
19844 of these commands, together with examples of their use. Furthermore,
19845 the command @command{help} invoked from within GDB activates a simple help
19846 facility which summarizes the available commands and their options.
19847 In this section we summarize a few of the most commonly
19848 used commands to give an idea of what @code{GDB} is about. You should create
19849 a simple program with debugging information and experiment with the use of
19850 these @code{GDB} commands on the program as you read through the
19854 @item set args @var{arguments}
19855 The @var{arguments} list above is a list of arguments to be passed to
19856 the program on a subsequent run command, just as though the arguments
19857 had been entered on a normal invocation of the program. The @code{set args}
19858 command is not needed if the program does not require arguments.
19861 The @code{run} command causes execution of the program to start from
19862 the beginning. If the program is already running, that is to say if
19863 you are currently positioned at a breakpoint, then a prompt will ask
19864 for confirmation that you want to abandon the current execution and
19867 @item breakpoint @var{location}
19868 The breakpoint command sets a breakpoint, that is to say a point at which
19869 execution will halt and @code{GDB} will await further
19870 commands. @var{location} is
19871 either a line number within a file, given in the format @code{file:linenumber},
19872 or it is the name of a subprogram. If you request that a breakpoint be set on
19873 a subprogram that is overloaded, a prompt will ask you to specify on which of
19874 those subprograms you want to breakpoint. You can also
19875 specify that all of them should be breakpointed. If the program is run
19876 and execution encounters the breakpoint, then the program
19877 stops and @code{GDB} signals that the breakpoint was encountered by
19878 printing the line of code before which the program is halted.
19880 @item catch exception @var{name}
19881 This command causes the program execution to stop whenever exception
19882 @var{name} is raised. If @var{name} is omitted, then the execution is
19883 suspended when any exception is raised.
19885 @item print @var{expression}
19886 This will print the value of the given expression. Most simple
19887 Ada expression formats are properly handled by @code{GDB}, so the expression
19888 can contain function calls, variables, operators, and attribute references.
19891 Continues execution following a breakpoint, until the next breakpoint or the
19892 termination of the program.
19895 Executes a single line after a breakpoint. If the next statement
19896 is a subprogram call, execution continues into (the first statement of)
19897 the called subprogram.
19900 Executes a single line. If this line is a subprogram call, executes and
19901 returns from the call.
19904 Lists a few lines around the current source location. In practice, it
19905 is usually more convenient to have a separate edit window open with the
19906 relevant source file displayed. Successive applications of this command
19907 print subsequent lines. The command can be given an argument which is a
19908 line number, in which case it displays a few lines around the specified one.
19911 Displays a backtrace of the call chain. This command is typically
19912 used after a breakpoint has occurred, to examine the sequence of calls that
19913 leads to the current breakpoint. The display includes one line for each
19914 activation record (frame) corresponding to an active subprogram.
19917 At a breakpoint, @code{GDB} can display the values of variables local
19918 to the current frame. The command @code{up} can be used to
19919 examine the contents of other active frames, by moving the focus up
19920 the stack, that is to say from callee to caller, one frame at a time.
19923 Moves the focus of @code{GDB} down from the frame currently being
19924 examined to the frame of its callee (the reverse of the previous command),
19926 @item frame @var{n}
19927 Inspect the frame with the given number. The value 0 denotes the frame
19928 of the current breakpoint, that is to say the top of the call stack.
19933 The above list is a very short introduction to the commands that
19934 @code{GDB} provides. Important additional capabilities, including conditional
19935 breakpoints, the ability to execute command sequences on a breakpoint,
19936 the ability to debug at the machine instruction level and many other
19937 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19938 Debugging with GDB}. Note that most commands can be abbreviated
19939 (for example, c for continue, bt for backtrace).
19941 @node Using Ada Expressions
19942 @section Using Ada Expressions
19943 @cindex Ada expressions
19946 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19947 extensions. The philosophy behind the design of this subset is
19951 That @code{GDB} should provide basic literals and access to operations for
19952 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19953 leaving more sophisticated computations to subprograms written into the
19954 program (which therefore may be called from @code{GDB}).
19957 That type safety and strict adherence to Ada language restrictions
19958 are not particularly important to the @code{GDB} user.
19961 That brevity is important to the @code{GDB} user.
19965 Thus, for brevity, the debugger acts as if there were
19966 implicit @code{with} and @code{use} clauses in effect for all user-written
19967 packages, thus making it unnecessary to fully qualify most names with
19968 their packages, regardless of context. Where this causes ambiguity,
19969 @code{GDB} asks the user's intent.
19971 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19972 GDB, gdb, Debugging with GDB}.
19974 @node Calling User-Defined Subprograms
19975 @section Calling User-Defined Subprograms
19978 An important capability of @code{GDB} is the ability to call user-defined
19979 subprograms while debugging. This is achieved simply by entering
19980 a subprogram call statement in the form:
19983 call subprogram-name (parameters)
19987 The keyword @code{call} can be omitted in the normal case where the
19988 @code{subprogram-name} does not coincide with any of the predefined
19989 @code{GDB} commands.
19991 The effect is to invoke the given subprogram, passing it the
19992 list of parameters that is supplied. The parameters can be expressions and
19993 can include variables from the program being debugged. The
19994 subprogram must be defined
19995 at the library level within your program, and @code{GDB} will call the
19996 subprogram within the environment of your program execution (which
19997 means that the subprogram is free to access or even modify variables
19998 within your program).
20000 The most important use of this facility is in allowing the inclusion of
20001 debugging routines that are tailored to particular data structures
20002 in your program. Such debugging routines can be written to provide a suitably
20003 high-level description of an abstract type, rather than a low-level dump
20004 of its physical layout. After all, the standard
20005 @code{GDB print} command only knows the physical layout of your
20006 types, not their abstract meaning. Debugging routines can provide information
20007 at the desired semantic level and are thus enormously useful.
20009 For example, when debugging GNAT itself, it is crucial to have access to
20010 the contents of the tree nodes used to represent the program internally.
20011 But tree nodes are represented simply by an integer value (which in turn
20012 is an index into a table of nodes).
20013 Using the @code{print} command on a tree node would simply print this integer
20014 value, which is not very useful. But the PN routine (defined in file
20015 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20016 a useful high level representation of the tree node, which includes the
20017 syntactic category of the node, its position in the source, the integers
20018 that denote descendant nodes and parent node, as well as varied
20019 semantic information. To study this example in more detail, you might want to
20020 look at the body of the PN procedure in the stated file.
20022 @node Using the Next Command in a Function
20023 @section Using the Next Command in a Function
20026 When you use the @code{next} command in a function, the current source
20027 location will advance to the next statement as usual. A special case
20028 arises in the case of a @code{return} statement.
20030 Part of the code for a return statement is the ``epilog'' of the function.
20031 This is the code that returns to the caller. There is only one copy of
20032 this epilog code, and it is typically associated with the last return
20033 statement in the function if there is more than one return. In some
20034 implementations, this epilog is associated with the first statement
20037 The result is that if you use the @code{next} command from a return
20038 statement that is not the last return statement of the function you
20039 may see a strange apparent jump to the last return statement or to
20040 the start of the function. You should simply ignore this odd jump.
20041 The value returned is always that from the first return statement
20042 that was stepped through.
20044 @node Ada Exceptions
20045 @section Stopping when Ada Exceptions are Raised
20049 You can set catchpoints that stop the program execution when your program
20050 raises selected exceptions.
20053 @item catch exception
20054 Set a catchpoint that stops execution whenever (any task in the) program
20055 raises any exception.
20057 @item catch exception @var{name}
20058 Set a catchpoint that stops execution whenever (any task in the) program
20059 raises the exception @var{name}.
20061 @item catch exception unhandled
20062 Set a catchpoint that stops executing whenever (any task in the) program
20063 raises an exception for which there is no handler.
20065 @item info exceptions
20066 @itemx info exceptions @var{regexp}
20067 The @code{info exceptions} command permits the user to examine all defined
20068 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20069 argument, prints out only those exceptions whose name matches @var{regexp}.
20077 @code{GDB} allows the following task-related commands:
20081 This command shows a list of current Ada tasks, as in the following example:
20088 ID TID P-ID Thread Pri State Name
20089 1 8088000 0 807e000 15 Child Activation Wait main_task
20090 2 80a4000 1 80ae000 15 Accept/Select Wait b
20091 3 809a800 1 80a4800 15 Child Activation Wait a
20092 * 4 80ae800 3 80b8000 15 Running c
20096 In this listing, the asterisk before the first task indicates it to be the
20097 currently running task. The first column lists the task ID that is used
20098 to refer to tasks in the following commands.
20100 @item break @var{linespec} task @var{taskid}
20101 @itemx break @var{linespec} task @var{taskid} if @dots{}
20102 @cindex Breakpoints and tasks
20103 These commands are like the @code{break @dots{} thread @dots{}}.
20104 @var{linespec} specifies source lines.
20106 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20107 to specify that you only want @code{GDB} to stop the program when a
20108 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20109 numeric task identifiers assigned by @code{GDB}, shown in the first
20110 column of the @samp{info tasks} display.
20112 If you do not specify @samp{task @var{taskid}} when you set a
20113 breakpoint, the breakpoint applies to @emph{all} tasks of your
20116 You can use the @code{task} qualifier on conditional breakpoints as
20117 well; in this case, place @samp{task @var{taskid}} before the
20118 breakpoint condition (before the @code{if}).
20120 @item task @var{taskno}
20121 @cindex Task switching
20123 This command allows to switch to the task referred by @var{taskno}. In
20124 particular, This allows to browse the backtrace of the specified
20125 task. It is advised to switch back to the original task before
20126 continuing execution otherwise the scheduling of the program may be
20131 For more detailed information on the tasking support,
20132 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
20134 @node Debugging Generic Units
20135 @section Debugging Generic Units
20136 @cindex Debugging Generic Units
20140 GNAT always uses code expansion for generic instantiation. This means that
20141 each time an instantiation occurs, a complete copy of the original code is
20142 made, with appropriate substitutions of formals by actuals.
20144 It is not possible to refer to the original generic entities in
20145 @code{GDB}, but it is always possible to debug a particular instance of
20146 a generic, by using the appropriate expanded names. For example, if we have
20148 @smallexample @c ada
20153 generic package k is
20154 procedure kp (v1 : in out integer);
20158 procedure kp (v1 : in out integer) is
20164 package k1 is new k;
20165 package k2 is new k;
20167 var : integer := 1;
20180 Then to break on a call to procedure kp in the k2 instance, simply
20184 (gdb) break g.k2.kp
20188 When the breakpoint occurs, you can step through the code of the
20189 instance in the normal manner and examine the values of local variables, as for
20192 @node Remote Debugging using gdbserver
20193 @section Remote Debugging using gdbserver
20194 @cindex Remote Debugging using gdbserver
20197 On platforms where gdbserver is supported, it is possible to use this tool
20198 to debug your application remotely. This can be useful in situations
20199 where the program needs to be run on a target host that is different
20200 from the host used for development, particularly when the target has
20201 a limited amount of resources (either CPU and/or memory).
20203 To do so, start your program using gdbserver on the target machine.
20204 gdbserver then automatically suspends the execution of your program
20205 at its entry point, waiting for a debugger to connect to it. The
20206 following commands starts an application and tells gdbserver to
20207 wait for a connection with the debugger on localhost port 4444.
20210 $ gdbserver localhost:4444 program
20211 Process program created; pid = 5685
20212 Listening on port 4444
20215 Once gdbserver has started listening, we can tell the debugger to establish
20216 a connection with this gdbserver, and then start the same debugging session
20217 as if the program was being debugged on the same host, directly under
20218 the control of GDB.
20222 (gdb) target remote targethost:4444
20223 Remote debugging using targethost:4444
20224 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
20226 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
20230 Breakpoint 1, foo () at foo.adb:4
20234 It is also possible to use gdbserver to attach to an already running
20235 program, in which case the execution of that program is simply suspended
20236 until the connection between the debugger and gdbserver is established.
20238 For more information on how to use gdbserver, @ref{Top, Server, Using
20239 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
20240 for gdbserver on x86-linux, x86-windows and x86_64-linux.
20242 @node GNAT Abnormal Termination or Failure to Terminate
20243 @section GNAT Abnormal Termination or Failure to Terminate
20244 @cindex GNAT Abnormal Termination or Failure to Terminate
20247 When presented with programs that contain serious errors in syntax
20249 GNAT may on rare occasions experience problems in operation, such
20251 segmentation fault or illegal memory access, raising an internal
20252 exception, terminating abnormally, or failing to terminate at all.
20253 In such cases, you can activate
20254 various features of GNAT that can help you pinpoint the construct in your
20255 program that is the likely source of the problem.
20257 The following strategies are presented in increasing order of
20258 difficulty, corresponding to your experience in using GNAT and your
20259 familiarity with compiler internals.
20263 Run @command{gcc} with the @option{-gnatf}. This first
20264 switch causes all errors on a given line to be reported. In its absence,
20265 only the first error on a line is displayed.
20267 The @option{-gnatdO} switch causes errors to be displayed as soon as they
20268 are encountered, rather than after compilation is terminated. If GNAT
20269 terminates prematurely or goes into an infinite loop, the last error
20270 message displayed may help to pinpoint the culprit.
20273 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
20274 mode, @command{gcc} produces ongoing information about the progress of the
20275 compilation and provides the name of each procedure as code is
20276 generated. This switch allows you to find which Ada procedure was being
20277 compiled when it encountered a code generation problem.
20280 @cindex @option{-gnatdc} switch
20281 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
20282 switch that does for the front-end what @option{^-v^VERBOSE^} does
20283 for the back end. The system prints the name of each unit,
20284 either a compilation unit or nested unit, as it is being analyzed.
20286 Finally, you can start
20287 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
20288 front-end of GNAT, and can be run independently (normally it is just
20289 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
20290 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
20291 @code{where} command is the first line of attack; the variable
20292 @code{lineno} (seen by @code{print lineno}), used by the second phase of
20293 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
20294 which the execution stopped, and @code{input_file name} indicates the name of
20298 @node Naming Conventions for GNAT Source Files
20299 @section Naming Conventions for GNAT Source Files
20302 In order to examine the workings of the GNAT system, the following
20303 brief description of its organization may be helpful:
20307 Files with prefix @file{^sc^SC^} contain the lexical scanner.
20310 All files prefixed with @file{^par^PAR^} are components of the parser. The
20311 numbers correspond to chapters of the Ada Reference Manual. For example,
20312 parsing of select statements can be found in @file{par-ch9.adb}.
20315 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
20316 numbers correspond to chapters of the Ada standard. For example, all
20317 issues involving context clauses can be found in @file{sem_ch10.adb}. In
20318 addition, some features of the language require sufficient special processing
20319 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
20320 dynamic dispatching, etc.
20323 All files prefixed with @file{^exp^EXP^} perform normalization and
20324 expansion of the intermediate representation (abstract syntax tree, or AST).
20325 these files use the same numbering scheme as the parser and semantics files.
20326 For example, the construction of record initialization procedures is done in
20327 @file{exp_ch3.adb}.
20330 The files prefixed with @file{^bind^BIND^} implement the binder, which
20331 verifies the consistency of the compilation, determines an order of
20332 elaboration, and generates the bind file.
20335 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20336 data structures used by the front-end.
20339 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20340 the abstract syntax tree as produced by the parser.
20343 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20344 all entities, computed during semantic analysis.
20347 Library management issues are dealt with in files with prefix
20353 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20354 defined in Annex A.
20359 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20360 defined in Annex B.
20364 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20365 both language-defined children and GNAT run-time routines.
20369 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
20370 general-purpose packages, fully documented in their specs. All
20371 the other @file{.c} files are modifications of common @command{gcc} files.
20374 @node Getting Internal Debugging Information
20375 @section Getting Internal Debugging Information
20378 Most compilers have internal debugging switches and modes. GNAT
20379 does also, except GNAT internal debugging switches and modes are not
20380 secret. A summary and full description of all the compiler and binder
20381 debug flags are in the file @file{debug.adb}. You must obtain the
20382 sources of the compiler to see the full detailed effects of these flags.
20384 The switches that print the source of the program (reconstructed from
20385 the internal tree) are of general interest for user programs, as are the
20387 the full internal tree, and the entity table (the symbol table
20388 information). The reconstructed source provides a readable version of the
20389 program after the front-end has completed analysis and expansion,
20390 and is useful when studying the performance of specific constructs.
20391 For example, constraint checks are indicated, complex aggregates
20392 are replaced with loops and assignments, and tasking primitives
20393 are replaced with run-time calls.
20395 @node Stack Traceback
20396 @section Stack Traceback
20398 @cindex stack traceback
20399 @cindex stack unwinding
20402 Traceback is a mechanism to display the sequence of subprogram calls that
20403 leads to a specified execution point in a program. Often (but not always)
20404 the execution point is an instruction at which an exception has been raised.
20405 This mechanism is also known as @i{stack unwinding} because it obtains
20406 its information by scanning the run-time stack and recovering the activation
20407 records of all active subprograms. Stack unwinding is one of the most
20408 important tools for program debugging.
20410 The first entry stored in traceback corresponds to the deepest calling level,
20411 that is to say the subprogram currently executing the instruction
20412 from which we want to obtain the traceback.
20414 Note that there is no runtime performance penalty when stack traceback
20415 is enabled, and no exception is raised during program execution.
20418 * Non-Symbolic Traceback::
20419 * Symbolic Traceback::
20422 @node Non-Symbolic Traceback
20423 @subsection Non-Symbolic Traceback
20424 @cindex traceback, non-symbolic
20427 Note: this feature is not supported on all platforms. See
20428 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20432 * Tracebacks From an Unhandled Exception::
20433 * Tracebacks From Exception Occurrences (non-symbolic)::
20434 * Tracebacks From Anywhere in a Program (non-symbolic)::
20437 @node Tracebacks From an Unhandled Exception
20438 @subsubsection Tracebacks From an Unhandled Exception
20441 A runtime non-symbolic traceback is a list of addresses of call instructions.
20442 To enable this feature you must use the @option{-E}
20443 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20444 of exception information. You can retrieve this information using the
20445 @code{addr2line} tool.
20447 Here is a simple example:
20449 @smallexample @c ada
20455 raise Constraint_Error;
20470 $ gnatmake stb -bargs -E
20473 Execution terminated by unhandled exception
20474 Exception name: CONSTRAINT_ERROR
20476 Call stack traceback locations:
20477 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20481 As we see the traceback lists a sequence of addresses for the unhandled
20482 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20483 guess that this exception come from procedure P1. To translate these
20484 addresses into the source lines where the calls appear, the
20485 @code{addr2line} tool, described below, is invaluable. The use of this tool
20486 requires the program to be compiled with debug information.
20489 $ gnatmake -g stb -bargs -E
20492 Execution terminated by unhandled exception
20493 Exception name: CONSTRAINT_ERROR
20495 Call stack traceback locations:
20496 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20498 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20499 0x4011f1 0x77e892a4
20501 00401373 at d:/stb/stb.adb:5
20502 0040138B at d:/stb/stb.adb:10
20503 0040139C at d:/stb/stb.adb:14
20504 00401335 at d:/stb/b~stb.adb:104
20505 004011C4 at /build/@dots{}/crt1.c:200
20506 004011F1 at /build/@dots{}/crt1.c:222
20507 77E892A4 in ?? at ??:0
20511 The @code{addr2line} tool has several other useful options:
20515 to get the function name corresponding to any location
20517 @item --demangle=gnat
20518 to use the gnat decoding mode for the function names. Note that
20519 for binutils version 2.9.x the option is simply @option{--demangle}.
20523 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20524 0x40139c 0x401335 0x4011c4 0x4011f1
20526 00401373 in stb.p1 at d:/stb/stb.adb:5
20527 0040138B in stb.p2 at d:/stb/stb.adb:10
20528 0040139C in stb at d:/stb/stb.adb:14
20529 00401335 in main at d:/stb/b~stb.adb:104
20530 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
20531 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
20535 From this traceback we can see that the exception was raised in
20536 @file{stb.adb} at line 5, which was reached from a procedure call in
20537 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20538 which contains the call to the main program.
20539 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20540 and the output will vary from platform to platform.
20542 It is also possible to use @code{GDB} with these traceback addresses to debug
20543 the program. For example, we can break at a given code location, as reported
20544 in the stack traceback:
20550 Furthermore, this feature is not implemented inside Windows DLL. Only
20551 the non-symbolic traceback is reported in this case.
20554 (gdb) break *0x401373
20555 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20559 It is important to note that the stack traceback addresses
20560 do not change when debug information is included. This is particularly useful
20561 because it makes it possible to release software without debug information (to
20562 minimize object size), get a field report that includes a stack traceback
20563 whenever an internal bug occurs, and then be able to retrieve the sequence
20564 of calls with the same program compiled with debug information.
20566 @node Tracebacks From Exception Occurrences (non-symbolic)
20567 @subsubsection Tracebacks From Exception Occurrences
20570 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20571 The stack traceback is attached to the exception information string, and can
20572 be retrieved in an exception handler within the Ada program, by means of the
20573 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20575 @smallexample @c ada
20577 with Ada.Exceptions;
20582 use Ada.Exceptions;
20590 Text_IO.Put_Line (Exception_Information (E));
20604 This program will output:
20609 Exception name: CONSTRAINT_ERROR
20610 Message: stb.adb:12
20611 Call stack traceback locations:
20612 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20615 @node Tracebacks From Anywhere in a Program (non-symbolic)
20616 @subsubsection Tracebacks From Anywhere in a Program
20619 It is also possible to retrieve a stack traceback from anywhere in a
20620 program. For this you need to
20621 use the @code{GNAT.Traceback} API. This package includes a procedure called
20622 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20623 display procedures described below. It is not necessary to use the
20624 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20625 is invoked explicitly.
20628 In the following example we compute a traceback at a specific location in
20629 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20630 convert addresses to strings:
20632 @smallexample @c ada
20634 with GNAT.Traceback;
20635 with GNAT.Debug_Utilities;
20641 use GNAT.Traceback;
20644 TB : Tracebacks_Array (1 .. 10);
20645 -- We are asking for a maximum of 10 stack frames.
20647 -- Len will receive the actual number of stack frames returned.
20649 Call_Chain (TB, Len);
20651 Text_IO.Put ("In STB.P1 : ");
20653 for K in 1 .. Len loop
20654 Text_IO.Put (Debug_Utilities.Image (TB (K)));
20675 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20676 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20680 You can then get further information by invoking the @code{addr2line}
20681 tool as described earlier (note that the hexadecimal addresses
20682 need to be specified in C format, with a leading ``0x'').
20684 @node Symbolic Traceback
20685 @subsection Symbolic Traceback
20686 @cindex traceback, symbolic
20689 A symbolic traceback is a stack traceback in which procedure names are
20690 associated with each code location.
20693 Note that this feature is not supported on all platforms. See
20694 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20695 list of currently supported platforms.
20698 Note that the symbolic traceback requires that the program be compiled
20699 with debug information. If it is not compiled with debug information
20700 only the non-symbolic information will be valid.
20703 * Tracebacks From Exception Occurrences (symbolic)::
20704 * Tracebacks From Anywhere in a Program (symbolic)::
20707 @node Tracebacks From Exception Occurrences (symbolic)
20708 @subsubsection Tracebacks From Exception Occurrences
20710 @smallexample @c ada
20712 with GNAT.Traceback.Symbolic;
20718 raise Constraint_Error;
20735 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20740 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20743 0040149F in stb.p1 at stb.adb:8
20744 004014B7 in stb.p2 at stb.adb:13
20745 004014CF in stb.p3 at stb.adb:18
20746 004015DD in ada.stb at stb.adb:22
20747 00401461 in main at b~stb.adb:168
20748 004011C4 in __mingw_CRTStartup at crt1.c:200
20749 004011F1 in mainCRTStartup at crt1.c:222
20750 77E892A4 in ?? at ??:0
20754 In the above example the ``.\'' syntax in the @command{gnatmake} command
20755 is currently required by @command{addr2line} for files that are in
20756 the current working directory.
20757 Moreover, the exact sequence of linker options may vary from platform
20759 The above @option{-largs} section is for Windows platforms. By contrast,
20760 under Unix there is no need for the @option{-largs} section.
20761 Differences across platforms are due to details of linker implementation.
20763 @node Tracebacks From Anywhere in a Program (symbolic)
20764 @subsubsection Tracebacks From Anywhere in a Program
20767 It is possible to get a symbolic stack traceback
20768 from anywhere in a program, just as for non-symbolic tracebacks.
20769 The first step is to obtain a non-symbolic
20770 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20771 information. Here is an example:
20773 @smallexample @c ada
20775 with GNAT.Traceback;
20776 with GNAT.Traceback.Symbolic;
20781 use GNAT.Traceback;
20782 use GNAT.Traceback.Symbolic;
20785 TB : Tracebacks_Array (1 .. 10);
20786 -- We are asking for a maximum of 10 stack frames.
20788 -- Len will receive the actual number of stack frames returned.
20790 Call_Chain (TB, Len);
20791 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20804 @c ******************************
20806 @node Compatibility with HP Ada
20807 @chapter Compatibility with HP Ada
20808 @cindex Compatibility
20813 @cindex Compatibility between GNAT and HP Ada
20814 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20815 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20816 GNAT is highly compatible
20817 with HP Ada, and it should generally be straightforward to port code
20818 from the HP Ada environment to GNAT. However, there are a few language
20819 and implementation differences of which the user must be aware. These
20820 differences are discussed in this chapter. In
20821 addition, the operating environment and command structure for the
20822 compiler are different, and these differences are also discussed.
20824 For further details on these and other compatibility issues,
20825 see Appendix E of the HP publication
20826 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20828 Except where otherwise indicated, the description of GNAT for OpenVMS
20829 applies to both the Alpha and I64 platforms.
20831 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20832 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20834 The discussion in this chapter addresses specifically the implementation
20835 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20836 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20837 GNAT always follows the Alpha implementation.
20839 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20840 attributes are recognized, although only a subset of them can sensibly
20841 be implemented. The description of pragmas in
20842 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20843 indicates whether or not they are applicable to non-VMS systems.
20846 * Ada Language Compatibility::
20847 * Differences in the Definition of Package System::
20848 * Language-Related Features::
20849 * The Package STANDARD::
20850 * The Package SYSTEM::
20851 * Tasking and Task-Related Features::
20852 * Pragmas and Pragma-Related Features::
20853 * Library of Predefined Units::
20855 * Main Program Definition::
20856 * Implementation-Defined Attributes::
20857 * Compiler and Run-Time Interfacing::
20858 * Program Compilation and Library Management::
20860 * Implementation Limits::
20861 * Tools and Utilities::
20864 @node Ada Language Compatibility
20865 @section Ada Language Compatibility
20868 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20869 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20870 with Ada 83, and therefore Ada 83 programs will compile
20871 and run under GNAT with
20872 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20873 provides details on specific incompatibilities.
20875 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20876 as well as the pragma @code{ADA_83}, to force the compiler to
20877 operate in Ada 83 mode. This mode does not guarantee complete
20878 conformance to Ada 83, but in practice is sufficient to
20879 eliminate most sources of incompatibilities.
20880 In particular, it eliminates the recognition of the
20881 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20882 in Ada 83 programs is legal, and handles the cases of packages
20883 with optional bodies, and generics that instantiate unconstrained
20884 types without the use of @code{(<>)}.
20886 @node Differences in the Definition of Package System
20887 @section Differences in the Definition of Package @code{System}
20890 An Ada compiler is allowed to add
20891 implementation-dependent declarations to package @code{System}.
20893 GNAT does not take advantage of this permission, and the version of
20894 @code{System} provided by GNAT exactly matches that defined in the Ada
20897 However, HP Ada adds an extensive set of declarations to package
20899 as fully documented in the HP Ada manuals. To minimize changes required
20900 for programs that make use of these extensions, GNAT provides the pragma
20901 @code{Extend_System} for extending the definition of package System. By using:
20902 @cindex pragma @code{Extend_System}
20903 @cindex @code{Extend_System} pragma
20905 @smallexample @c ada
20908 pragma Extend_System (Aux_DEC);
20914 the set of definitions in @code{System} is extended to include those in
20915 package @code{System.Aux_DEC}.
20916 @cindex @code{System.Aux_DEC} package
20917 @cindex @code{Aux_DEC} package (child of @code{System})
20918 These definitions are incorporated directly into package @code{System},
20919 as though they had been declared there. For a
20920 list of the declarations added, see the spec of this package,
20921 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20922 @cindex @file{s-auxdec.ads} file
20923 The pragma @code{Extend_System} is a configuration pragma, which means that
20924 it can be placed in the file @file{gnat.adc}, so that it will automatically
20925 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20926 for further details.
20928 An alternative approach that avoids the use of the non-standard
20929 @code{Extend_System} pragma is to add a context clause to the unit that
20930 references these facilities:
20932 @smallexample @c ada
20934 with System.Aux_DEC;
20935 use System.Aux_DEC;
20940 The effect is not quite semantically identical to incorporating
20941 the declarations directly into package @code{System},
20942 but most programs will not notice a difference
20943 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20944 to reference the entities directly in package @code{System}.
20945 For units containing such references,
20946 the prefixes must either be removed, or the pragma @code{Extend_System}
20949 @node Language-Related Features
20950 @section Language-Related Features
20953 The following sections highlight differences in types,
20954 representations of types, operations, alignment, and
20958 * Integer Types and Representations::
20959 * Floating-Point Types and Representations::
20960 * Pragmas Float_Representation and Long_Float::
20961 * Fixed-Point Types and Representations::
20962 * Record and Array Component Alignment::
20963 * Address Clauses::
20964 * Other Representation Clauses::
20967 @node Integer Types and Representations
20968 @subsection Integer Types and Representations
20971 The set of predefined integer types is identical in HP Ada and GNAT.
20972 Furthermore the representation of these integer types is also identical,
20973 including the capability of size clauses forcing biased representation.
20976 HP Ada for OpenVMS Alpha systems has defined the
20977 following additional integer types in package @code{System}:
20994 @code{LARGEST_INTEGER}
20998 In GNAT, the first four of these types may be obtained from the
20999 standard Ada package @code{Interfaces}.
21000 Alternatively, by use of the pragma @code{Extend_System}, identical
21001 declarations can be referenced directly in package @code{System}.
21002 On both GNAT and HP Ada, the maximum integer size is 64 bits.
21004 @node Floating-Point Types and Representations
21005 @subsection Floating-Point Types and Representations
21006 @cindex Floating-Point types
21009 The set of predefined floating-point types is identical in HP Ada and GNAT.
21010 Furthermore the representation of these floating-point
21011 types is also identical. One important difference is that the default
21012 representation for HP Ada is @code{VAX_Float}, but the default representation
21015 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
21016 pragma @code{Float_Representation} as described in the HP Ada
21018 For example, the declarations:
21020 @smallexample @c ada
21022 type F_Float is digits 6;
21023 pragma Float_Representation (VAX_Float, F_Float);
21028 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21030 This set of declarations actually appears in @code{System.Aux_DEC},
21032 the full set of additional floating-point declarations provided in
21033 the HP Ada version of package @code{System}.
21034 This and similar declarations may be accessed in a user program
21035 by using pragma @code{Extend_System}. The use of this
21036 pragma, and the related pragma @code{Long_Float} is described in further
21037 detail in the following section.
21039 @node Pragmas Float_Representation and Long_Float
21040 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
21043 HP Ada provides the pragma @code{Float_Representation}, which
21044 acts as a program library switch to allow control over
21045 the internal representation chosen for the predefined
21046 floating-point types declared in the package @code{Standard}.
21047 The format of this pragma is as follows:
21049 @smallexample @c ada
21051 pragma Float_Representation(VAX_Float | IEEE_Float);
21056 This pragma controls the representation of floating-point
21061 @code{VAX_Float} specifies that floating-point
21062 types are represented by default with the VAX system hardware types
21063 @code{F-floating}, @code{D-floating}, @code{G-floating}.
21064 Note that the @code{H-floating}
21065 type was available only on VAX systems, and is not available
21066 in either HP Ada or GNAT.
21069 @code{IEEE_Float} specifies that floating-point
21070 types are represented by default with the IEEE single and
21071 double floating-point types.
21075 GNAT provides an identical implementation of the pragma
21076 @code{Float_Representation}, except that it functions as a
21077 configuration pragma. Note that the
21078 notion of configuration pragma corresponds closely to the
21079 HP Ada notion of a program library switch.
21081 When no pragma is used in GNAT, the default is @code{IEEE_Float},
21083 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
21084 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
21085 advisable to change the format of numbers passed to standard library
21086 routines, and if necessary explicit type conversions may be needed.
21088 The use of @code{IEEE_Float} is recommended in GNAT since it is more
21089 efficient, and (given that it conforms to an international standard)
21090 potentially more portable.
21091 The situation in which @code{VAX_Float} may be useful is in interfacing
21092 to existing code and data that expect the use of @code{VAX_Float}.
21093 In such a situation use the predefined @code{VAX_Float}
21094 types in package @code{System}, as extended by
21095 @code{Extend_System}. For example, use @code{System.F_Float}
21096 to specify the 32-bit @code{F-Float} format.
21099 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
21100 to allow control over the internal representation chosen
21101 for the predefined type @code{Long_Float} and for floating-point
21102 type declarations with digits specified in the range 7 .. 15.
21103 The format of this pragma is as follows:
21105 @smallexample @c ada
21107 pragma Long_Float (D_FLOAT | G_FLOAT);
21111 @node Fixed-Point Types and Representations
21112 @subsection Fixed-Point Types and Representations
21115 On HP Ada for OpenVMS Alpha systems, rounding is
21116 away from zero for both positive and negative numbers.
21117 Therefore, @code{+0.5} rounds to @code{1},
21118 and @code{-0.5} rounds to @code{-1}.
21120 On GNAT the results of operations
21121 on fixed-point types are in accordance with the Ada
21122 rules. In particular, results of operations on decimal
21123 fixed-point types are truncated.
21125 @node Record and Array Component Alignment
21126 @subsection Record and Array Component Alignment
21129 On HP Ada for OpenVMS Alpha, all non-composite components
21130 are aligned on natural boundaries. For example, 1-byte
21131 components are aligned on byte boundaries, 2-byte
21132 components on 2-byte boundaries, 4-byte components on 4-byte
21133 byte boundaries, and so on. The OpenVMS Alpha hardware
21134 runs more efficiently with naturally aligned data.
21136 On GNAT, alignment rules are compatible
21137 with HP Ada for OpenVMS Alpha.
21139 @node Address Clauses
21140 @subsection Address Clauses
21143 In HP Ada and GNAT, address clauses are supported for
21144 objects and imported subprograms.
21145 The predefined type @code{System.Address} is a private type
21146 in both compilers on Alpha OpenVMS, with the same representation
21147 (it is simply a machine pointer). Addition, subtraction, and comparison
21148 operations are available in the standard Ada package
21149 @code{System.Storage_Elements}, or in package @code{System}
21150 if it is extended to include @code{System.Aux_DEC} using a
21151 pragma @code{Extend_System} as previously described.
21153 Note that code that @code{with}'s both this extended package @code{System}
21154 and the package @code{System.Storage_Elements} should not @code{use}
21155 both packages, or ambiguities will result. In general it is better
21156 not to mix these two sets of facilities. The Ada package was
21157 designed specifically to provide the kind of features that HP Ada
21158 adds directly to package @code{System}.
21160 The type @code{System.Address} is a 64-bit integer type in GNAT for
21161 I64 OpenVMS. For more information,
21162 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21164 GNAT is compatible with HP Ada in its handling of address
21165 clauses, except for some limitations in
21166 the form of address clauses for composite objects with
21167 initialization. Such address clauses are easily replaced
21168 by the use of an explicitly-defined constant as described
21169 in the Ada Reference Manual (13.1(22)). For example, the sequence
21172 @smallexample @c ada
21174 X, Y : Integer := Init_Func;
21175 Q : String (X .. Y) := "abc";
21177 for Q'Address use Compute_Address;
21182 will be rejected by GNAT, since the address cannot be computed at the time
21183 that @code{Q} is declared. To achieve the intended effect, write instead:
21185 @smallexample @c ada
21188 X, Y : Integer := Init_Func;
21189 Q_Address : constant Address := Compute_Address;
21190 Q : String (X .. Y) := "abc";
21192 for Q'Address use Q_Address;
21198 which will be accepted by GNAT (and other Ada compilers), and is also
21199 compatible with Ada 83. A fuller description of the restrictions
21200 on address specifications is found in @ref{Top, GNAT Reference Manual,
21201 About This Guide, gnat_rm, GNAT Reference Manual}.
21203 @node Other Representation Clauses
21204 @subsection Other Representation Clauses
21207 GNAT implements in a compatible manner all the representation
21208 clauses supported by HP Ada. In addition, GNAT
21209 implements the representation clause forms that were introduced in Ada 95,
21210 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
21212 @node The Package STANDARD
21213 @section The Package @code{STANDARD}
21216 The package @code{STANDARD}, as implemented by HP Ada, is fully
21217 described in the @cite{Ada Reference Manual} and in the
21218 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
21219 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
21221 In addition, HP Ada supports the Latin-1 character set in
21222 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
21223 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
21224 the type @code{WIDE_CHARACTER}.
21226 The floating-point types supported by GNAT are those
21227 supported by HP Ada, but the defaults are different, and are controlled by
21228 pragmas. See @ref{Floating-Point Types and Representations}, for details.
21230 @node The Package SYSTEM
21231 @section The Package @code{SYSTEM}
21234 HP Ada provides a specific version of the package
21235 @code{SYSTEM} for each platform on which the language is implemented.
21236 For the complete spec of the package @code{SYSTEM}, see
21237 Appendix F of the @cite{HP Ada Language Reference Manual}.
21239 On HP Ada, the package @code{SYSTEM} includes the following conversion
21242 @item @code{TO_ADDRESS(INTEGER)}
21244 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
21246 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
21248 @item @code{TO_INTEGER(ADDRESS)}
21250 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
21252 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
21253 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
21257 By default, GNAT supplies a version of @code{SYSTEM} that matches
21258 the definition given in the @cite{Ada Reference Manual}.
21260 is a subset of the HP system definitions, which is as
21261 close as possible to the original definitions. The only difference
21262 is that the definition of @code{SYSTEM_NAME} is different:
21264 @smallexample @c ada
21266 type Name is (SYSTEM_NAME_GNAT);
21267 System_Name : constant Name := SYSTEM_NAME_GNAT;
21272 Also, GNAT adds the Ada declarations for
21273 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
21275 However, the use of the following pragma causes GNAT
21276 to extend the definition of package @code{SYSTEM} so that it
21277 encompasses the full set of HP-specific extensions,
21278 including the functions listed above:
21280 @smallexample @c ada
21282 pragma Extend_System (Aux_DEC);
21287 The pragma @code{Extend_System} is a configuration pragma that
21288 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
21289 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
21291 HP Ada does not allow the recompilation of the package
21292 @code{SYSTEM}. Instead HP Ada provides several pragmas
21293 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
21294 to modify values in the package @code{SYSTEM}.
21295 On OpenVMS Alpha systems, the pragma
21296 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
21297 its single argument.
21299 GNAT does permit the recompilation of package @code{SYSTEM} using
21300 the special switch @option{-gnatg}, and this switch can be used if
21301 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
21302 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
21303 or @code{MEMORY_SIZE} by any other means.
21305 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
21306 enumeration literal @code{SYSTEM_NAME_GNAT}.
21308 The definitions provided by the use of
21310 @smallexample @c ada
21311 pragma Extend_System (AUX_Dec);
21315 are virtually identical to those provided by the HP Ada 83 package
21316 @code{SYSTEM}. One important difference is that the name of the
21318 function for type @code{UNSIGNED_LONGWORD} is changed to
21319 @code{TO_ADDRESS_LONG}.
21320 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
21321 discussion of why this change was necessary.
21324 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
21326 an extension to Ada 83 not strictly compatible with the reference manual.
21327 GNAT, in order to be exactly compatible with the standard,
21328 does not provide this capability. In HP Ada 83, the
21329 point of this definition is to deal with a call like:
21331 @smallexample @c ada
21332 TO_ADDRESS (16#12777#);
21336 Normally, according to Ada 83 semantics, one would expect this to be
21337 ambiguous, since it matches both the @code{INTEGER} and
21338 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
21339 However, in HP Ada 83, there is no ambiguity, since the
21340 definition using @i{universal_integer} takes precedence.
21342 In GNAT, since the version with @i{universal_integer} cannot be supplied,
21344 not possible to be 100% compatible. Since there are many programs using
21345 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
21347 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
21348 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
21350 @smallexample @c ada
21351 function To_Address (X : Integer) return Address;
21352 pragma Pure_Function (To_Address);
21354 function To_Address_Long (X : Unsigned_Longword) return Address;
21355 pragma Pure_Function (To_Address_Long);
21359 This means that programs using @code{TO_ADDRESS} for
21360 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
21362 @node Tasking and Task-Related Features
21363 @section Tasking and Task-Related Features
21366 This section compares the treatment of tasking in GNAT
21367 and in HP Ada for OpenVMS Alpha.
21368 The GNAT description applies to both Alpha and I64 OpenVMS.
21369 For detailed information on tasking in
21370 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
21371 relevant run-time reference manual.
21374 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
21375 * Assigning Task IDs::
21376 * Task IDs and Delays::
21377 * Task-Related Pragmas::
21378 * Scheduling and Task Priority::
21380 * External Interrupts::
21383 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21384 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21387 On OpenVMS Alpha systems, each Ada task (except a passive
21388 task) is implemented as a single stream of execution
21389 that is created and managed by the kernel. On these
21390 systems, HP Ada tasking support is based on DECthreads,
21391 an implementation of the POSIX standard for threads.
21393 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
21394 code that calls DECthreads routines can be used together.
21395 The interaction between Ada tasks and DECthreads routines
21396 can have some benefits. For example when on OpenVMS Alpha,
21397 HP Ada can call C code that is already threaded.
21399 GNAT uses the facilities of DECthreads,
21400 and Ada tasks are mapped to threads.
21402 @node Assigning Task IDs
21403 @subsection Assigning Task IDs
21406 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
21407 the environment task that executes the main program. On
21408 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21409 that have been created but are not yet activated.
21411 On OpenVMS Alpha systems, task IDs are assigned at
21412 activation. On GNAT systems, task IDs are also assigned at
21413 task creation but do not have the same form or values as
21414 task ID values in HP Ada. There is no null task, and the
21415 environment task does not have a specific task ID value.
21417 @node Task IDs and Delays
21418 @subsection Task IDs and Delays
21421 On OpenVMS Alpha systems, tasking delays are implemented
21422 using Timer System Services. The Task ID is used for the
21423 identification of the timer request (the @code{REQIDT} parameter).
21424 If Timers are used in the application take care not to use
21425 @code{0} for the identification, because cancelling such a timer
21426 will cancel all timers and may lead to unpredictable results.
21428 @node Task-Related Pragmas
21429 @subsection Task-Related Pragmas
21432 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21433 specification of the size of the guard area for a task
21434 stack. (The guard area forms an area of memory that has no
21435 read or write access and thus helps in the detection of
21436 stack overflow.) On OpenVMS Alpha systems, if the pragma
21437 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21438 area is created. In the absence of a pragma @code{TASK_STORAGE},
21439 a default guard area is created.
21441 GNAT supplies the following task-related pragmas:
21444 @item @code{TASK_INFO}
21446 This pragma appears within a task definition and
21447 applies to the task in which it appears. The argument
21448 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21450 @item @code{TASK_STORAGE}
21452 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
21453 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21454 @code{SUPPRESS}, and @code{VOLATILE}.
21456 @node Scheduling and Task Priority
21457 @subsection Scheduling and Task Priority
21460 HP Ada implements the Ada language requirement that
21461 when two tasks are eligible for execution and they have
21462 different priorities, the lower priority task does not
21463 execute while the higher priority task is waiting. The HP
21464 Ada Run-Time Library keeps a task running until either the
21465 task is suspended or a higher priority task becomes ready.
21467 On OpenVMS Alpha systems, the default strategy is round-
21468 robin with preemption. Tasks of equal priority take turns
21469 at the processor. A task is run for a certain period of
21470 time and then placed at the tail of the ready queue for
21471 its priority level.
21473 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21474 which can be used to enable or disable round-robin
21475 scheduling of tasks with the same priority.
21476 See the relevant HP Ada run-time reference manual for
21477 information on using the pragmas to control HP Ada task
21480 GNAT follows the scheduling rules of Annex D (Real-Time
21481 Annex) of the @cite{Ada Reference Manual}. In general, this
21482 scheduling strategy is fully compatible with HP Ada
21483 although it provides some additional constraints (as
21484 fully documented in Annex D).
21485 GNAT implements time slicing control in a manner compatible with
21486 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21487 are identical to the HP Ada 83 pragma of the same name.
21488 Note that it is not possible to mix GNAT tasking and
21489 HP Ada 83 tasking in the same program, since the two run-time
21490 libraries are not compatible.
21492 @node The Task Stack
21493 @subsection The Task Stack
21496 In HP Ada, a task stack is allocated each time a
21497 non-passive task is activated. As soon as the task is
21498 terminated, the storage for the task stack is deallocated.
21499 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21500 a default stack size is used. Also, regardless of the size
21501 specified, some additional space is allocated for task
21502 management purposes. On OpenVMS Alpha systems, at least
21503 one page is allocated.
21505 GNAT handles task stacks in a similar manner. In accordance with
21506 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
21507 an alternative method for controlling the task stack size.
21508 The specification of the attribute @code{T'STORAGE_SIZE} is also
21509 supported in a manner compatible with HP Ada.
21511 @node External Interrupts
21512 @subsection External Interrupts
21515 On HP Ada, external interrupts can be associated with task entries.
21516 GNAT is compatible with HP Ada in its handling of external interrupts.
21518 @node Pragmas and Pragma-Related Features
21519 @section Pragmas and Pragma-Related Features
21522 Both HP Ada and GNAT supply all language-defined pragmas
21523 as specified by the Ada 83 standard. GNAT also supplies all
21524 language-defined pragmas introduced by Ada 95 and Ada 2005.
21525 In addition, GNAT implements the implementation-defined pragmas
21529 @item @code{AST_ENTRY}
21531 @item @code{COMMON_OBJECT}
21533 @item @code{COMPONENT_ALIGNMENT}
21535 @item @code{EXPORT_EXCEPTION}
21537 @item @code{EXPORT_FUNCTION}
21539 @item @code{EXPORT_OBJECT}
21541 @item @code{EXPORT_PROCEDURE}
21543 @item @code{EXPORT_VALUED_PROCEDURE}
21545 @item @code{FLOAT_REPRESENTATION}
21549 @item @code{IMPORT_EXCEPTION}
21551 @item @code{IMPORT_FUNCTION}
21553 @item @code{IMPORT_OBJECT}
21555 @item @code{IMPORT_PROCEDURE}
21557 @item @code{IMPORT_VALUED_PROCEDURE}
21559 @item @code{INLINE_GENERIC}
21561 @item @code{INTERFACE_NAME}
21563 @item @code{LONG_FLOAT}
21565 @item @code{MAIN_STORAGE}
21567 @item @code{PASSIVE}
21569 @item @code{PSECT_OBJECT}
21571 @item @code{SHARE_GENERIC}
21573 @item @code{SUPPRESS_ALL}
21575 @item @code{TASK_STORAGE}
21577 @item @code{TIME_SLICE}
21583 These pragmas are all fully implemented, with the exception of @code{TITLE},
21584 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21585 recognized, but which have no
21586 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21587 use of Ada protected objects. In GNAT, all generics are inlined.
21589 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21590 a separate subprogram specification which must appear before the
21593 GNAT also supplies a number of implementation-defined pragmas including the
21597 @item @code{ABORT_DEFER}
21599 @item @code{ADA_83}
21601 @item @code{ADA_95}
21603 @item @code{ADA_05}
21605 @item @code{Ada_2005}
21607 @item @code{Ada_12}
21609 @item @code{Ada_2012}
21611 @item @code{ANNOTATE}
21613 @item @code{ASSERT}
21615 @item @code{C_PASS_BY_COPY}
21617 @item @code{CPP_CLASS}
21619 @item @code{CPP_CONSTRUCTOR}
21621 @item @code{CPP_DESTRUCTOR}
21625 @item @code{EXTEND_SYSTEM}
21627 @item @code{LINKER_ALIAS}
21629 @item @code{LINKER_SECTION}
21631 @item @code{MACHINE_ATTRIBUTE}
21633 @item @code{NO_RETURN}
21635 @item @code{PURE_FUNCTION}
21637 @item @code{SOURCE_FILE_NAME}
21639 @item @code{SOURCE_REFERENCE}
21641 @item @code{TASK_INFO}
21643 @item @code{UNCHECKED_UNION}
21645 @item @code{UNIMPLEMENTED_UNIT}
21647 @item @code{UNIVERSAL_DATA}
21649 @item @code{UNSUPPRESS}
21651 @item @code{WARNINGS}
21653 @item @code{WEAK_EXTERNAL}
21657 For full details on these and other GNAT implementation-defined pragmas,
21658 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21662 * Restrictions on the Pragma INLINE::
21663 * Restrictions on the Pragma INTERFACE::
21664 * Restrictions on the Pragma SYSTEM_NAME::
21667 @node Restrictions on the Pragma INLINE
21668 @subsection Restrictions on Pragma @code{INLINE}
21671 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21673 @item Parameters cannot have a task type.
21675 @item Function results cannot be task types, unconstrained
21676 array types, or unconstrained types with discriminants.
21678 @item Bodies cannot declare the following:
21680 @item Subprogram body or stub (imported subprogram is allowed)
21684 @item Generic declarations
21686 @item Instantiations
21690 @item Access types (types derived from access types allowed)
21692 @item Array or record types
21694 @item Dependent tasks
21696 @item Direct recursive calls of subprogram or containing
21697 subprogram, directly or via a renaming
21703 In GNAT, the only restriction on pragma @code{INLINE} is that the
21704 body must occur before the call if both are in the same
21705 unit, and the size must be appropriately small. There are
21706 no other specific restrictions which cause subprograms to
21707 be incapable of being inlined.
21709 @node Restrictions on the Pragma INTERFACE
21710 @subsection Restrictions on Pragma @code{INTERFACE}
21713 The following restrictions on pragma @code{INTERFACE}
21714 are enforced by both HP Ada and GNAT:
21716 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
21717 Default is the default on OpenVMS Alpha systems.
21719 @item Parameter passing: Language specifies default
21720 mechanisms but can be overridden with an @code{EXPORT} pragma.
21723 @item Ada: Use internal Ada rules.
21725 @item Bliss, C: Parameters must be mode @code{in}; cannot be
21726 record or task type. Result cannot be a string, an
21727 array, or a record.
21729 @item Fortran: Parameters cannot have a task type. Result cannot
21730 be a string, an array, or a record.
21735 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21736 record parameters for all languages.
21738 @node Restrictions on the Pragma SYSTEM_NAME
21739 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
21742 For HP Ada for OpenVMS Alpha, the enumeration literal
21743 for the type @code{NAME} is @code{OPENVMS_AXP}.
21744 In GNAT, the enumeration
21745 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21747 @node Library of Predefined Units
21748 @section Library of Predefined Units
21751 A library of predefined units is provided as part of the
21752 HP Ada and GNAT implementations. HP Ada does not provide
21753 the package @code{MACHINE_CODE} but instead recommends importing
21756 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21757 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21759 The HP Ada Predefined Library units are modified to remove post-Ada 83
21760 incompatibilities and to make them interoperable with GNAT
21761 (@pxref{Changes to DECLIB}, for details).
21762 The units are located in the @file{DECLIB} directory.
21764 The GNAT RTL is contained in
21765 the @file{ADALIB} directory, and
21766 the default search path is set up to find @code{DECLIB} units in preference
21767 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21768 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21771 * Changes to DECLIB::
21774 @node Changes to DECLIB
21775 @subsection Changes to @code{DECLIB}
21778 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21779 compatibility are minor and include the following:
21782 @item Adjusting the location of pragmas and record representation
21783 clauses to obey Ada 95 (and thus Ada 2005) rules
21785 @item Adding the proper notation to generic formal parameters
21786 that take unconstrained types in instantiation
21788 @item Adding pragma @code{ELABORATE_BODY} to package specs
21789 that have package bodies not otherwise allowed
21791 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21792 ``@code{PROTECTD}''.
21793 Currently these are found only in the @code{STARLET} package spec.
21795 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21796 where the address size is constrained to 32 bits.
21800 None of the above changes is visible to users.
21806 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21809 @item Command Language Interpreter (CLI interface)
21811 @item DECtalk Run-Time Library (DTK interface)
21813 @item Librarian utility routines (LBR interface)
21815 @item General Purpose Run-Time Library (LIB interface)
21817 @item Math Run-Time Library (MTH interface)
21819 @item National Character Set Run-Time Library (NCS interface)
21821 @item Compiled Code Support Run-Time Library (OTS interface)
21823 @item Parallel Processing Run-Time Library (PPL interface)
21825 @item Screen Management Run-Time Library (SMG interface)
21827 @item Sort Run-Time Library (SOR interface)
21829 @item String Run-Time Library (STR interface)
21831 @item STARLET System Library
21834 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
21836 @item X Windows Toolkit (XT interface)
21838 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
21842 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21843 directory, on both the Alpha and I64 OpenVMS platforms.
21845 The X components of DECLIB compatibility package are located in a separate
21846 library, called XDECGNAT, which is not linked with by default; this library
21847 must be explicitly linked with any application that makes use of any X facilities,
21848 with a command similar to
21850 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21852 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21854 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21855 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21856 @code{Xt}, and @code{X_Lib}
21857 causing the default X/Motif sharable image libraries to be linked in. This
21858 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21859 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21861 It may be necessary to edit these options files to update or correct the
21862 library names if, for example, the newer X/Motif bindings from
21863 @file{ADA$EXAMPLES}
21864 had been (previous to installing GNAT) copied and renamed to supersede the
21865 default @file{ADA$PREDEFINED} versions.
21868 * Shared Libraries and Options Files::
21869 * Interfaces to C::
21872 @node Shared Libraries and Options Files
21873 @subsection Shared Libraries and Options Files
21876 When using the HP Ada
21877 predefined X and Motif bindings, the linking with their sharable images is
21878 done automatically by @command{GNAT LINK}.
21879 When using other X and Motif bindings, you need
21880 to add the corresponding sharable images to the command line for
21881 @code{GNAT LINK}. When linking with shared libraries, or with
21882 @file{.OPT} files, you must
21883 also add them to the command line for @command{GNAT LINK}.
21885 A shared library to be used with GNAT is built in the same way as other
21886 libraries under VMS. The VMS Link command can be used in standard fashion.
21888 @node Interfaces to C
21889 @subsection Interfaces to C
21893 provides the following Ada types and operations:
21896 @item C types package (@code{C_TYPES})
21898 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21900 @item Other_types (@code{SHORT_INT})
21904 Interfacing to C with GNAT, you can use the above approach
21905 described for HP Ada or the facilities of Annex B of
21906 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21907 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21908 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21910 The @option{-gnatF} qualifier forces default and explicit
21911 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21912 to be uppercased for compatibility with the default behavior
21913 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21915 @node Main Program Definition
21916 @section Main Program Definition
21919 The following section discusses differences in the
21920 definition of main programs on HP Ada and GNAT.
21921 On HP Ada, main programs are defined to meet the
21922 following conditions:
21924 @item Procedure with no formal parameters (returns @code{0} upon
21927 @item Procedure with no formal parameters (returns @code{42} when
21928 an unhandled exception is raised)
21930 @item Function with no formal parameters whose returned value
21931 is of a discrete type
21933 @item Procedure with one @code{out} formal of a discrete type for
21934 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21939 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21940 a main function or main procedure returns a discrete
21941 value whose size is less than 64 bits (32 on VAX systems),
21942 the value is zero- or sign-extended as appropriate.
21943 On GNAT, main programs are defined as follows:
21945 @item Must be a non-generic, parameterless subprogram that
21946 is either a procedure or function returning an Ada
21947 @code{STANDARD.INTEGER} (the predefined type)
21949 @item Cannot be a generic subprogram or an instantiation of a
21953 @node Implementation-Defined Attributes
21954 @section Implementation-Defined Attributes
21957 GNAT provides all HP Ada implementation-defined
21960 @node Compiler and Run-Time Interfacing
21961 @section Compiler and Run-Time Interfacing
21964 HP Ada provides the following qualifiers to pass options to the linker
21967 @item @option{/WAIT} and @option{/SUBMIT}
21969 @item @option{/COMMAND}
21971 @item @option{/@r{[}NO@r{]}MAP}
21973 @item @option{/OUTPUT=@var{file-spec}}
21975 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21979 To pass options to the linker, GNAT provides the following
21983 @item @option{/EXECUTABLE=@var{exec-name}}
21985 @item @option{/VERBOSE}
21987 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21991 For more information on these switches, see
21992 @ref{Switches for gnatlink}.
21993 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21994 to control optimization. HP Ada also supplies the
21997 @item @code{OPTIMIZE}
21999 @item @code{INLINE}
22001 @item @code{INLINE_GENERIC}
22003 @item @code{SUPPRESS_ALL}
22005 @item @code{PASSIVE}
22009 In GNAT, optimization is controlled strictly by command
22010 line parameters, as described in the corresponding section of this guide.
22011 The HP pragmas for control of optimization are
22012 recognized but ignored.
22014 Note that in GNAT, the default is optimization off, whereas in HP Ada
22015 the default is that optimization is turned on.
22017 @node Program Compilation and Library Management
22018 @section Program Compilation and Library Management
22021 HP Ada and GNAT provide a comparable set of commands to
22022 build programs. HP Ada also provides a program library,
22023 which is a concept that does not exist on GNAT. Instead,
22024 GNAT provides directories of sources that are compiled as
22027 The following table summarizes
22028 the HP Ada commands and provides
22029 equivalent GNAT commands. In this table, some GNAT
22030 equivalents reflect the fact that GNAT does not use the
22031 concept of a program library. Instead, it uses a model
22032 in which collections of source and object files are used
22033 in a manner consistent with other languages like C and
22034 Fortran. Therefore, standard system file commands are used
22035 to manipulate these elements. Those GNAT commands are marked with
22037 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
22040 @multitable @columnfractions .35 .65
22042 @item @emph{HP Ada Command}
22043 @tab @emph{GNAT Equivalent / Description}
22045 @item @command{ADA}
22046 @tab @command{GNAT COMPILE}@*
22047 Invokes the compiler to compile one or more Ada source files.
22049 @item @command{ACS ATTACH}@*
22050 @tab [No equivalent]@*
22051 Switches control of terminal from current process running the program
22054 @item @command{ACS CHECK}
22055 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
22056 Forms the execution closure of one
22057 or more compiled units and checks completeness and currency.
22059 @item @command{ACS COMPILE}
22060 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22061 Forms the execution closure of one or
22062 more specified units, checks completeness and currency,
22063 identifies units that have revised source files, compiles same,
22064 and recompiles units that are or will become obsolete.
22065 Also completes incomplete generic instantiations.
22067 @item @command{ACS COPY FOREIGN}
22069 Copies a foreign object file into the program library as a
22072 @item @command{ACS COPY UNIT}
22074 Copies a compiled unit from one program library to another.
22076 @item @command{ACS CREATE LIBRARY}
22077 @tab Create /directory (*)@*
22078 Creates a program library.
22080 @item @command{ACS CREATE SUBLIBRARY}
22081 @tab Create /directory (*)@*
22082 Creates a program sublibrary.
22084 @item @command{ACS DELETE LIBRARY}
22086 Deletes a program library and its contents.
22088 @item @command{ACS DELETE SUBLIBRARY}
22090 Deletes a program sublibrary and its contents.
22092 @item @command{ACS DELETE UNIT}
22093 @tab Delete file (*)@*
22094 On OpenVMS systems, deletes one or more compiled units from
22095 the current program library.
22097 @item @command{ACS DIRECTORY}
22098 @tab Directory (*)@*
22099 On OpenVMS systems, lists units contained in the current
22102 @item @command{ACS ENTER FOREIGN}
22104 Allows the import of a foreign body as an Ada library
22105 spec and enters a reference to a pointer.
22107 @item @command{ACS ENTER UNIT}
22109 Enters a reference (pointer) from the current program library to
22110 a unit compiled into another program library.
22112 @item @command{ACS EXIT}
22113 @tab [No equivalent]@*
22114 Exits from the program library manager.
22116 @item @command{ACS EXPORT}
22118 Creates an object file that contains system-specific object code
22119 for one or more units. With GNAT, object files can simply be copied
22120 into the desired directory.
22122 @item @command{ACS EXTRACT SOURCE}
22124 Allows access to the copied source file for each Ada compilation unit
22126 @item @command{ACS HELP}
22127 @tab @command{HELP GNAT}@*
22128 Provides online help.
22130 @item @command{ACS LINK}
22131 @tab @command{GNAT LINK}@*
22132 Links an object file containing Ada units into an executable file.
22134 @item @command{ACS LOAD}
22136 Loads (partially compiles) Ada units into the program library.
22137 Allows loading a program from a collection of files into a library
22138 without knowing the relationship among units.
22140 @item @command{ACS MERGE}
22142 Merges into the current program library, one or more units from
22143 another library where they were modified.
22145 @item @command{ACS RECOMPILE}
22146 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22147 Recompiles from external or copied source files any obsolete
22148 unit in the closure. Also, completes any incomplete generic
22151 @item @command{ACS REENTER}
22152 @tab @command{GNAT MAKE}@*
22153 Reenters current references to units compiled after last entered
22154 with the @command{ACS ENTER UNIT} command.
22156 @item @command{ACS SET LIBRARY}
22157 @tab Set default (*)@*
22158 Defines a program library to be the compilation context as well
22159 as the target library for compiler output and commands in general.
22161 @item @command{ACS SET PRAGMA}
22162 @tab Edit @file{gnat.adc} (*)@*
22163 Redefines specified values of the library characteristics
22164 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
22165 and @code{Float_Representation}.
22167 @item @command{ACS SET SOURCE}
22168 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
22169 Defines the source file search list for the @command{ACS COMPILE} command.
22171 @item @command{ACS SHOW LIBRARY}
22172 @tab Directory (*)@*
22173 Lists information about one or more program libraries.
22175 @item @command{ACS SHOW PROGRAM}
22176 @tab [No equivalent]@*
22177 Lists information about the execution closure of one or
22178 more units in the program library.
22180 @item @command{ACS SHOW SOURCE}
22181 @tab Show logical @code{ADA_INCLUDE_PATH}@*
22182 Shows the source file search used when compiling units.
22184 @item @command{ACS SHOW VERSION}
22185 @tab Compile with @option{VERBOSE} option
22186 Displays the version number of the compiler and program library
22189 @item @command{ACS SPAWN}
22190 @tab [No equivalent]@*
22191 Creates a subprocess of the current process (same as @command{DCL SPAWN}
22194 @item @command{ACS VERIFY}
22195 @tab [No equivalent]@*
22196 Performs a series of consistency checks on a program library to
22197 determine whether the library structure and library files are in
22204 @section Input-Output
22207 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22208 Management Services (RMS) to perform operations on
22212 HP Ada and GNAT predefine an identical set of input-
22213 output packages. To make the use of the
22214 generic @code{TEXT_IO} operations more convenient, HP Ada
22215 provides predefined library packages that instantiate the
22216 integer and floating-point operations for the predefined
22217 integer and floating-point types as shown in the following table.
22219 @multitable @columnfractions .45 .55
22220 @item @emph{Package Name} @tab Instantiation
22222 @item @code{INTEGER_TEXT_IO}
22223 @tab @code{INTEGER_IO(INTEGER)}
22225 @item @code{SHORT_INTEGER_TEXT_IO}
22226 @tab @code{INTEGER_IO(SHORT_INTEGER)}
22228 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
22229 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
22231 @item @code{FLOAT_TEXT_IO}
22232 @tab @code{FLOAT_IO(FLOAT)}
22234 @item @code{LONG_FLOAT_TEXT_IO}
22235 @tab @code{FLOAT_IO(LONG_FLOAT)}
22239 The HP Ada predefined packages and their operations
22240 are implemented using OpenVMS Alpha files and input-output
22241 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
22242 Familiarity with the following is recommended:
22244 @item RMS file organizations and access methods
22246 @item OpenVMS file specifications and directories
22248 @item OpenVMS File Definition Language (FDL)
22252 GNAT provides I/O facilities that are completely
22253 compatible with HP Ada. The distribution includes the
22254 standard HP Ada versions of all I/O packages, operating
22255 in a manner compatible with HP Ada. In particular, the
22256 following packages are by default the HP Ada (Ada 83)
22257 versions of these packages rather than the renamings
22258 suggested in Annex J of the Ada Reference Manual:
22260 @item @code{TEXT_IO}
22262 @item @code{SEQUENTIAL_IO}
22264 @item @code{DIRECT_IO}
22268 The use of the standard child package syntax (for
22269 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
22271 GNAT provides HP-compatible predefined instantiations
22272 of the @code{TEXT_IO} packages, and also
22273 provides the standard predefined instantiations required
22274 by the @cite{Ada Reference Manual}.
22276 For further information on how GNAT interfaces to the file
22277 system or how I/O is implemented in programs written in
22278 mixed languages, see @ref{Implementation of the Standard I/O,,,
22279 gnat_rm, GNAT Reference Manual}.
22280 This chapter covers the following:
22282 @item Standard I/O packages
22284 @item @code{FORM} strings
22286 @item @code{ADA.DIRECT_IO}
22288 @item @code{ADA.SEQUENTIAL_IO}
22290 @item @code{ADA.TEXT_IO}
22292 @item Stream pointer positioning
22294 @item Reading and writing non-regular files
22296 @item @code{GET_IMMEDIATE}
22298 @item Treating @code{TEXT_IO} files as streams
22305 @node Implementation Limits
22306 @section Implementation Limits
22309 The following table lists implementation limits for HP Ada
22311 @multitable @columnfractions .60 .20 .20
22313 @item @emph{Compilation Parameter}
22318 @item In a subprogram or entry declaration, maximum number of
22319 formal parameters that are of an unconstrained record type
22324 @item Maximum identifier length (number of characters)
22329 @item Maximum number of characters in a source line
22334 @item Maximum collection size (number of bytes)
22339 @item Maximum number of discriminants for a record type
22344 @item Maximum number of formal parameters in an entry or
22345 subprogram declaration
22350 @item Maximum number of dimensions in an array type
22355 @item Maximum number of library units and subunits in a compilation.
22360 @item Maximum number of library units and subunits in an execution.
22365 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22366 or @code{PSECT_OBJECT}
22371 @item Maximum number of enumeration literals in an enumeration type
22377 @item Maximum number of lines in a source file
22382 @item Maximum number of bits in any object
22387 @item Maximum size of the static portion of a stack frame (approximate)
22392 @node Tools and Utilities
22393 @section Tools and Utilities
22396 The following table lists some of the OpenVMS development tools
22397 available for HP Ada, and the corresponding tools for
22398 use with @value{EDITION} on Alpha and I64 platforms.
22399 Aside from the debugger, all the OpenVMS tools identified are part
22400 of the DECset package.
22403 @c Specify table in TeX since Texinfo does a poor job
22407 \settabs\+Language-Sensitive Editor\quad
22408 &Product with HP Ada\quad
22411 &\it Product with HP Ada
22412 & \it Product with @value{EDITION}\cr
22414 \+Code Management System
22418 \+Language-Sensitive Editor
22420 & emacs or HP LSE (Alpha)\cr
22430 & OpenVMS Debug (I64)\cr
22432 \+Source Code Analyzer /
22449 \+Coverage Analyzer
22453 \+Module Management
22455 & Not applicable\cr
22465 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
22466 @c the TeX version above for the printed version
22468 @c @multitable @columnfractions .3 .4 .4
22469 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22471 @tab @i{Tool with HP Ada}
22472 @tab @i{Tool with @value{EDITION}}
22473 @item Code Management@*System
22476 @item Language-Sensitive@*Editor
22478 @tab emacs or HP LSE (Alpha)
22487 @tab OpenVMS Debug (I64)
22488 @item Source Code Analyzer /@*Cross Referencer
22492 @tab HP Digital Test@*Manager (DTM)
22494 @item Performance and@*Coverage Analyzer
22497 @item Module Management@*System
22499 @tab Not applicable
22506 @c **************************************
22507 @node Platform-Specific Information for the Run-Time Libraries
22508 @appendix Platform-Specific Information for the Run-Time Libraries
22509 @cindex Tasking and threads libraries
22510 @cindex Threads libraries and tasking
22511 @cindex Run-time libraries (platform-specific information)
22514 The GNAT run-time implementation may vary with respect to both the
22515 underlying threads library and the exception handling scheme.
22516 For threads support, one or more of the following are supplied:
22518 @item @b{native threads library}, a binding to the thread package from
22519 the underlying operating system
22521 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22522 POSIX thread package
22526 For exception handling, either or both of two models are supplied:
22528 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22529 Most programs should experience a substantial speed improvement by
22530 being compiled with a ZCX run-time.
22531 This is especially true for
22532 tasking applications or applications with many exception handlers.}
22533 @cindex Zero-Cost Exceptions
22534 @cindex ZCX (Zero-Cost Exceptions)
22535 which uses binder-generated tables that
22536 are interrogated at run time to locate a handler
22538 @item @b{setjmp / longjmp} (``SJLJ''),
22539 @cindex setjmp/longjmp Exception Model
22540 @cindex SJLJ (setjmp/longjmp Exception Model)
22541 which uses dynamically-set data to establish
22542 the set of handlers
22546 This appendix summarizes which combinations of threads and exception support
22547 are supplied on various GNAT platforms.
22548 It then shows how to select a particular library either
22549 permanently or temporarily,
22550 explains the properties of (and tradeoffs among) the various threads
22551 libraries, and provides some additional
22552 information about several specific platforms.
22555 * Summary of Run-Time Configurations::
22556 * Specifying a Run-Time Library::
22557 * Choosing the Scheduling Policy::
22558 * Solaris-Specific Considerations::
22559 * Linux-Specific Considerations::
22560 * AIX-Specific Considerations::
22561 * RTX-Specific Considerations::
22562 * HP-UX-Specific Considerations::
22565 @node Summary of Run-Time Configurations
22566 @section Summary of Run-Time Configurations
22568 @multitable @columnfractions .30 .70
22569 @item @b{alpha-openvms}
22570 @item @code{@ @ }@i{rts-native (default)}
22571 @item @code{@ @ @ @ }Tasking @tab native VMS threads
22572 @item @code{@ @ @ @ }Exceptions @tab ZCX
22574 @item @code{@ @ }@i{rts-sjlj}
22575 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
22576 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22578 @item @b{ia64-hp_linux}
22579 @item @code{@ @ }@i{rts-native (default)}
22580 @item @code{@ @ @ @ }Tasking @tab pthread library
22581 @item @code{@ @ @ @ }Exceptions @tab ZCX
22583 @item @b{ia64-hpux}
22584 @item @code{@ @ }@i{rts-native (default)}
22585 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22586 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22588 @item @b{ia64-openvms}
22589 @item @code{@ @ }@i{rts-native (default)}
22590 @item @code{@ @ @ @ }Tasking @tab native VMS threads
22591 @item @code{@ @ @ @ }Exceptions @tab ZCX
22593 @item @b{ia64-sgi_linux}
22594 @item @code{@ @ }@i{rts-native (default)}
22595 @item @code{@ @ @ @ }Tasking @tab pthread library
22596 @item @code{@ @ @ @ }Exceptions @tab ZCX
22599 @item @code{@ @ }@i{rts-native (default)}
22600 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22601 @item @code{@ @ @ @ }Exceptions @tab ZCX
22603 @item @code{@ @ }@i{rts-sjlj}
22604 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22605 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22608 @item @code{@ @ }@i{rts-native (default)}
22609 @item @code{@ @ @ @ }Tasking @tab native AIX threads
22610 @item @code{@ @ @ @ }Exceptions @tab ZCX
22612 @item @code{@ @ }@i{rts-sjlj}
22613 @item @code{@ @ @ @ }Tasking @tab native AIX threads
22614 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22616 @item @b{ppc-darwin}
22617 @item @code{@ @ }@i{rts-native (default)}
22618 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
22619 @item @code{@ @ @ @ }Exceptions @tab ZCX
22621 @item @b{sparc-solaris} @tab
22622 @item @code{@ @ }@i{rts-native (default)}
22623 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22624 @item @code{@ @ @ @ }Exceptions @tab ZCX
22626 @item @code{@ @ }@i{rts-pthread}
22627 @item @code{@ @ @ @ }Tasking @tab pthread library
22628 @item @code{@ @ @ @ }Exceptions @tab ZCX
22630 @item @code{@ @ }@i{rts-sjlj}
22631 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22632 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22634 @item @b{sparc64-solaris} @tab
22635 @item @code{@ @ }@i{rts-native (default)}
22636 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22637 @item @code{@ @ @ @ }Exceptions @tab ZCX
22639 @item @b{x86-linux}
22640 @item @code{@ @ }@i{rts-native (default)}
22641 @item @code{@ @ @ @ }Tasking @tab pthread library
22642 @item @code{@ @ @ @ }Exceptions @tab ZCX
22644 @item @code{@ @ }@i{rts-sjlj}
22645 @item @code{@ @ @ @ }Tasking @tab pthread library
22646 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22649 @item @code{@ @ }@i{rts-native (default)}
22650 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
22651 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22653 @item @b{x86-solaris}
22654 @item @code{@ @ }@i{rts-native (default)}
22655 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
22656 @item @code{@ @ @ @ }Exceptions @tab ZCX
22658 @item @code{@ @ }@i{rts-sjlj}
22659 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22660 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22662 @item @b{x86-windows}
22663 @item @code{@ @ }@i{rts-native (default)}
22664 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
22665 @item @code{@ @ @ @ }Exceptions @tab ZCX
22667 @item @code{@ @ }@i{rts-sjlj}
22668 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
22669 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22671 @item @b{x86-windows-rtx}
22672 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22673 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
22674 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22676 @item @code{@ @ }@i{rts-rtx-w32}
22677 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
22678 @item @code{@ @ @ @ }Exceptions @tab ZCX
22680 @item @b{x86_64-linux}
22681 @item @code{@ @ }@i{rts-native (default)}
22682 @item @code{@ @ @ @ }Tasking @tab pthread library
22683 @item @code{@ @ @ @ }Exceptions @tab ZCX
22685 @item @code{@ @ }@i{rts-sjlj}
22686 @item @code{@ @ @ @ }Tasking @tab pthread library
22687 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22691 @node Specifying a Run-Time Library
22692 @section Specifying a Run-Time Library
22695 The @file{adainclude} subdirectory containing the sources of the GNAT
22696 run-time library, and the @file{adalib} subdirectory containing the
22697 @file{ALI} files and the static and/or shared GNAT library, are located
22698 in the gcc target-dependent area:
22701 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22705 As indicated above, on some platforms several run-time libraries are supplied.
22706 These libraries are installed in the target dependent area and
22707 contain a complete source and binary subdirectory. The detailed description
22708 below explains the differences between the different libraries in terms of
22709 their thread support.
22711 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22712 This default run time is selected by the means of soft links.
22713 For example on x86-linux:
22719 +--- adainclude----------+
22721 +--- adalib-----------+ |
22723 +--- rts-native | |
22725 | +--- adainclude <---+
22727 | +--- adalib <----+
22738 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22739 these soft links can be modified with the following commands:
22743 $ rm -f adainclude adalib
22744 $ ln -s rts-sjlj/adainclude adainclude
22745 $ ln -s rts-sjlj/adalib adalib
22749 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22750 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22751 @file{$target/ada_object_path}.
22753 Selecting another run-time library temporarily can be
22754 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22755 @cindex @option{--RTS} option
22757 @node Choosing the Scheduling Policy
22758 @section Choosing the Scheduling Policy
22761 When using a POSIX threads implementation, you have a choice of several
22762 scheduling policies: @code{SCHED_FIFO},
22763 @cindex @code{SCHED_FIFO} scheduling policy
22765 @cindex @code{SCHED_RR} scheduling policy
22766 and @code{SCHED_OTHER}.
22767 @cindex @code{SCHED_OTHER} scheduling policy
22768 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22769 or @code{SCHED_RR} requires special (e.g., root) privileges.
22771 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22773 @cindex @code{SCHED_FIFO} scheduling policy
22774 you can use one of the following:
22778 @code{pragma Time_Slice (0.0)}
22779 @cindex pragma Time_Slice
22781 the corresponding binder option @option{-T0}
22782 @cindex @option{-T0} option
22784 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22785 @cindex pragma Task_Dispatching_Policy
22789 To specify @code{SCHED_RR},
22790 @cindex @code{SCHED_RR} scheduling policy
22791 you should use @code{pragma Time_Slice} with a
22792 value greater than @code{0.0}, or else use the corresponding @option{-T}
22795 @node Solaris-Specific Considerations
22796 @section Solaris-Specific Considerations
22797 @cindex Solaris Sparc threads libraries
22800 This section addresses some topics related to the various threads libraries
22804 * Solaris Threads Issues::
22807 @node Solaris Threads Issues
22808 @subsection Solaris Threads Issues
22811 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22812 library based on POSIX threads --- @emph{rts-pthread}.
22813 @cindex rts-pthread threads library
22814 This run-time library has the advantage of being mostly shared across all
22815 POSIX-compliant thread implementations, and it also provides under
22816 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22817 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22818 and @code{PTHREAD_PRIO_PROTECT}
22819 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22820 semantics that can be selected using the predefined pragma
22821 @code{Locking_Policy}
22822 @cindex pragma Locking_Policy (under rts-pthread)
22824 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22825 @cindex @code{Inheritance_Locking} (under rts-pthread)
22826 @cindex @code{Ceiling_Locking} (under rts-pthread)
22828 As explained above, the native run-time library is based on the Solaris thread
22829 library (@code{libthread}) and is the default library.
22831 When the Solaris threads library is used (this is the default), programs
22832 compiled with GNAT can automatically take advantage of
22833 and can thus execute on multiple processors.
22834 The user can alternatively specify a processor on which the program should run
22835 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22837 setting the environment variable @env{GNAT_PROCESSOR}
22838 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22839 to one of the following:
22843 Use the default configuration (run the program on all
22844 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22848 Let the run-time implementation choose one processor and run the program on
22851 @item 0 .. Last_Proc
22852 Run the program on the specified processor.
22853 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22854 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22857 @node Linux-Specific Considerations
22858 @section Linux-Specific Considerations
22859 @cindex Linux threads libraries
22862 On GNU/Linux without NPTL support (usually system with GNU C Library
22863 older than 2.3), the signal model is not POSIX compliant, which means
22864 that to send a signal to the process, you need to send the signal to all
22865 threads, e.g.@: by using @code{killpg()}.
22867 @node AIX-Specific Considerations
22868 @section AIX-Specific Considerations
22869 @cindex AIX resolver library
22872 On AIX, the resolver library initializes some internal structure on
22873 the first call to @code{get*by*} functions, which are used to implement
22874 @code{GNAT.Sockets.Get_Host_By_Name} and
22875 @code{GNAT.Sockets.Get_Host_By_Address}.
22876 If such initialization occurs within an Ada task, and the stack size for
22877 the task is the default size, a stack overflow may occur.
22879 To avoid this overflow, the user should either ensure that the first call
22880 to @code{GNAT.Sockets.Get_Host_By_Name} or
22881 @code{GNAT.Sockets.Get_Host_By_Addrss}
22882 occurs in the environment task, or use @code{pragma Storage_Size} to
22883 specify a sufficiently large size for the stack of the task that contains
22886 @node RTX-Specific Considerations
22887 @section RTX-Specific Considerations
22888 @cindex RTX libraries
22891 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22892 API. Applications can be built to work in two different modes:
22896 Windows executables that run in Ring 3 to utilize memory protection
22897 (@emph{rts-rtx-w32}).
22900 Real-time subsystem (RTSS) executables that run in Ring 0, where
22901 performance can be optimized with RTSS applications taking precedent
22902 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22903 the Microsoft linker to handle RTSS libraries.
22907 @node HP-UX-Specific Considerations
22908 @section HP-UX-Specific Considerations
22909 @cindex HP-UX Scheduling
22912 On HP-UX, appropriate privileges are required to change the scheduling
22913 parameters of a task. The calling process must have appropriate
22914 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22915 successfully change the scheduling parameters.
22917 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22918 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22919 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22921 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22922 one of the following:
22926 @code{pragma Time_Slice (0.0)}
22927 @cindex pragma Time_Slice
22929 the corresponding binder option @option{-T0}
22930 @cindex @option{-T0} option
22932 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22933 @cindex pragma Task_Dispatching_Policy
22937 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22938 you should use @code{pragma Time_Slice} with a
22939 value greater than @code{0.0}, or use the corresponding @option{-T}
22940 binder option, or set the @code{pragma Task_Dispatching_Policy
22941 (Round_Robin_Within_Priorities)}.
22943 @c *******************************
22944 @node Example of Binder Output File
22945 @appendix Example of Binder Output File
22948 This Appendix displays the source code for @command{gnatbind}'s output
22949 file generated for a simple ``Hello World'' program.
22950 Comments have been added for clarification purposes.
22952 @smallexample @c adanocomment
22956 -- The package is called Ada_Main unless this name is actually used
22957 -- as a unit name in the partition, in which case some other unique
22961 package ada_main is
22963 Elab_Final_Code : Integer;
22964 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22966 -- The main program saves the parameters (argument count,
22967 -- argument values, environment pointer) in global variables
22968 -- for later access by other units including
22969 -- Ada.Command_Line.
22971 gnat_argc : Integer;
22972 gnat_argv : System.Address;
22973 gnat_envp : System.Address;
22975 -- The actual variables are stored in a library routine. This
22976 -- is useful for some shared library situations, where there
22977 -- are problems if variables are not in the library.
22979 pragma Import (C, gnat_argc);
22980 pragma Import (C, gnat_argv);
22981 pragma Import (C, gnat_envp);
22983 -- The exit status is similarly an external location
22985 gnat_exit_status : Integer;
22986 pragma Import (C, gnat_exit_status);
22988 GNAT_Version : constant String :=
22989 "GNAT Version: 6.0.0w (20061115)";
22990 pragma Export (C, GNAT_Version, "__gnat_version");
22992 -- This is the generated adafinal routine that performs
22993 -- finalization at the end of execution. In the case where
22994 -- Ada is the main program, this main program makes a call
22995 -- to adafinal at program termination.
22997 procedure adafinal;
22998 pragma Export (C, adafinal, "adafinal");
23000 -- This is the generated adainit routine that performs
23001 -- initialization at the start of execution. In the case
23002 -- where Ada is the main program, this main program makes
23003 -- a call to adainit at program startup.
23006 pragma Export (C, adainit, "adainit");
23008 -- This routine is called at the start of execution. It is
23009 -- a dummy routine that is used by the debugger to breakpoint
23010 -- at the start of execution.
23012 procedure Break_Start;
23013 pragma Import (C, Break_Start, "__gnat_break_start");
23015 -- This is the actual generated main program (it would be
23016 -- suppressed if the no main program switch were used). As
23017 -- required by standard system conventions, this program has
23018 -- the external name main.
23022 argv : System.Address;
23023 envp : System.Address)
23025 pragma Export (C, main, "main");
23027 -- The following set of constants give the version
23028 -- identification values for every unit in the bound
23029 -- partition. This identification is computed from all
23030 -- dependent semantic units, and corresponds to the
23031 -- string that would be returned by use of the
23032 -- Body_Version or Version attributes.
23034 type Version_32 is mod 2 ** 32;
23035 u00001 : constant Version_32 := 16#7880BEB3#;
23036 u00002 : constant Version_32 := 16#0D24CBD0#;
23037 u00003 : constant Version_32 := 16#3283DBEB#;
23038 u00004 : constant Version_32 := 16#2359F9ED#;
23039 u00005 : constant Version_32 := 16#664FB847#;
23040 u00006 : constant Version_32 := 16#68E803DF#;
23041 u00007 : constant Version_32 := 16#5572E604#;
23042 u00008 : constant Version_32 := 16#46B173D8#;
23043 u00009 : constant Version_32 := 16#156A40CF#;
23044 u00010 : constant Version_32 := 16#033DABE0#;
23045 u00011 : constant Version_32 := 16#6AB38FEA#;
23046 u00012 : constant Version_32 := 16#22B6217D#;
23047 u00013 : constant Version_32 := 16#68A22947#;
23048 u00014 : constant Version_32 := 16#18CC4A56#;
23049 u00015 : constant Version_32 := 16#08258E1B#;
23050 u00016 : constant Version_32 := 16#367D5222#;
23051 u00017 : constant Version_32 := 16#20C9ECA4#;
23052 u00018 : constant Version_32 := 16#50D32CB6#;
23053 u00019 : constant Version_32 := 16#39A8BB77#;
23054 u00020 : constant Version_32 := 16#5CF8FA2B#;
23055 u00021 : constant Version_32 := 16#2F1EB794#;
23056 u00022 : constant Version_32 := 16#31AB6444#;
23057 u00023 : constant Version_32 := 16#1574B6E9#;
23058 u00024 : constant Version_32 := 16#5109C189#;
23059 u00025 : constant Version_32 := 16#56D770CD#;
23060 u00026 : constant Version_32 := 16#02F9DE3D#;
23061 u00027 : constant Version_32 := 16#08AB6B2C#;
23062 u00028 : constant Version_32 := 16#3FA37670#;
23063 u00029 : constant Version_32 := 16#476457A0#;
23064 u00030 : constant Version_32 := 16#731E1B6E#;
23065 u00031 : constant Version_32 := 16#23C2E789#;
23066 u00032 : constant Version_32 := 16#0F1BD6A1#;
23067 u00033 : constant Version_32 := 16#7C25DE96#;
23068 u00034 : constant Version_32 := 16#39ADFFA2#;
23069 u00035 : constant Version_32 := 16#571DE3E7#;
23070 u00036 : constant Version_32 := 16#5EB646AB#;
23071 u00037 : constant Version_32 := 16#4249379B#;
23072 u00038 : constant Version_32 := 16#0357E00A#;
23073 u00039 : constant Version_32 := 16#3784FB72#;
23074 u00040 : constant Version_32 := 16#2E723019#;
23075 u00041 : constant Version_32 := 16#623358EA#;
23076 u00042 : constant Version_32 := 16#107F9465#;
23077 u00043 : constant Version_32 := 16#6843F68A#;
23078 u00044 : constant Version_32 := 16#63305874#;
23079 u00045 : constant Version_32 := 16#31E56CE1#;
23080 u00046 : constant Version_32 := 16#02917970#;
23081 u00047 : constant Version_32 := 16#6CCBA70E#;
23082 u00048 : constant Version_32 := 16#41CD4204#;
23083 u00049 : constant Version_32 := 16#572E3F58#;
23084 u00050 : constant Version_32 := 16#20729FF5#;
23085 u00051 : constant Version_32 := 16#1D4F93E8#;
23086 u00052 : constant Version_32 := 16#30B2EC3D#;
23087 u00053 : constant Version_32 := 16#34054F96#;
23088 u00054 : constant Version_32 := 16#5A199860#;
23089 u00055 : constant Version_32 := 16#0E7F912B#;
23090 u00056 : constant Version_32 := 16#5760634A#;
23091 u00057 : constant Version_32 := 16#5D851835#;
23093 -- The following Export pragmas export the version numbers
23094 -- with symbolic names ending in B (for body) or S
23095 -- (for spec) so that they can be located in a link. The
23096 -- information provided here is sufficient to track down
23097 -- the exact versions of units used in a given build.
23099 pragma Export (C, u00001, "helloB");
23100 pragma Export (C, u00002, "system__standard_libraryB");
23101 pragma Export (C, u00003, "system__standard_libraryS");
23102 pragma Export (C, u00004, "adaS");
23103 pragma Export (C, u00005, "ada__text_ioB");
23104 pragma Export (C, u00006, "ada__text_ioS");
23105 pragma Export (C, u00007, "ada__exceptionsB");
23106 pragma Export (C, u00008, "ada__exceptionsS");
23107 pragma Export (C, u00009, "gnatS");
23108 pragma Export (C, u00010, "gnat__heap_sort_aB");
23109 pragma Export (C, u00011, "gnat__heap_sort_aS");
23110 pragma Export (C, u00012, "systemS");
23111 pragma Export (C, u00013, "system__exception_tableB");
23112 pragma Export (C, u00014, "system__exception_tableS");
23113 pragma Export (C, u00015, "gnat__htableB");
23114 pragma Export (C, u00016, "gnat__htableS");
23115 pragma Export (C, u00017, "system__exceptionsS");
23116 pragma Export (C, u00018, "system__machine_state_operationsB");
23117 pragma Export (C, u00019, "system__machine_state_operationsS");
23118 pragma Export (C, u00020, "system__machine_codeS");
23119 pragma Export (C, u00021, "system__storage_elementsB");
23120 pragma Export (C, u00022, "system__storage_elementsS");
23121 pragma Export (C, u00023, "system__secondary_stackB");
23122 pragma Export (C, u00024, "system__secondary_stackS");
23123 pragma Export (C, u00025, "system__parametersB");
23124 pragma Export (C, u00026, "system__parametersS");
23125 pragma Export (C, u00027, "system__soft_linksB");
23126 pragma Export (C, u00028, "system__soft_linksS");
23127 pragma Export (C, u00029, "system__stack_checkingB");
23128 pragma Export (C, u00030, "system__stack_checkingS");
23129 pragma Export (C, u00031, "system__tracebackB");
23130 pragma Export (C, u00032, "system__tracebackS");
23131 pragma Export (C, u00033, "ada__streamsS");
23132 pragma Export (C, u00034, "ada__tagsB");
23133 pragma Export (C, u00035, "ada__tagsS");
23134 pragma Export (C, u00036, "system__string_opsB");
23135 pragma Export (C, u00037, "system__string_opsS");
23136 pragma Export (C, u00038, "interfacesS");
23137 pragma Export (C, u00039, "interfaces__c_streamsB");
23138 pragma Export (C, u00040, "interfaces__c_streamsS");
23139 pragma Export (C, u00041, "system__file_ioB");
23140 pragma Export (C, u00042, "system__file_ioS");
23141 pragma Export (C, u00043, "ada__finalizationB");
23142 pragma Export (C, u00044, "ada__finalizationS");
23143 pragma Export (C, u00045, "system__finalization_rootB");
23144 pragma Export (C, u00046, "system__finalization_rootS");
23145 pragma Export (C, u00047, "system__finalization_implementationB");
23146 pragma Export (C, u00048, "system__finalization_implementationS");
23147 pragma Export (C, u00049, "system__string_ops_concat_3B");
23148 pragma Export (C, u00050, "system__string_ops_concat_3S");
23149 pragma Export (C, u00051, "system__stream_attributesB");
23150 pragma Export (C, u00052, "system__stream_attributesS");
23151 pragma Export (C, u00053, "ada__io_exceptionsS");
23152 pragma Export (C, u00054, "system__unsigned_typesS");
23153 pragma Export (C, u00055, "system__file_control_blockS");
23154 pragma Export (C, u00056, "ada__finalization__list_controllerB");
23155 pragma Export (C, u00057, "ada__finalization__list_controllerS");
23157 -- BEGIN ELABORATION ORDER
23160 -- gnat.heap_sort_a (spec)
23161 -- gnat.heap_sort_a (body)
23162 -- gnat.htable (spec)
23163 -- gnat.htable (body)
23164 -- interfaces (spec)
23166 -- system.machine_code (spec)
23167 -- system.parameters (spec)
23168 -- system.parameters (body)
23169 -- interfaces.c_streams (spec)
23170 -- interfaces.c_streams (body)
23171 -- system.standard_library (spec)
23172 -- ada.exceptions (spec)
23173 -- system.exception_table (spec)
23174 -- system.exception_table (body)
23175 -- ada.io_exceptions (spec)
23176 -- system.exceptions (spec)
23177 -- system.storage_elements (spec)
23178 -- system.storage_elements (body)
23179 -- system.machine_state_operations (spec)
23180 -- system.machine_state_operations (body)
23181 -- system.secondary_stack (spec)
23182 -- system.stack_checking (spec)
23183 -- system.soft_links (spec)
23184 -- system.soft_links (body)
23185 -- system.stack_checking (body)
23186 -- system.secondary_stack (body)
23187 -- system.standard_library (body)
23188 -- system.string_ops (spec)
23189 -- system.string_ops (body)
23192 -- ada.streams (spec)
23193 -- system.finalization_root (spec)
23194 -- system.finalization_root (body)
23195 -- system.string_ops_concat_3 (spec)
23196 -- system.string_ops_concat_3 (body)
23197 -- system.traceback (spec)
23198 -- system.traceback (body)
23199 -- ada.exceptions (body)
23200 -- system.unsigned_types (spec)
23201 -- system.stream_attributes (spec)
23202 -- system.stream_attributes (body)
23203 -- system.finalization_implementation (spec)
23204 -- system.finalization_implementation (body)
23205 -- ada.finalization (spec)
23206 -- ada.finalization (body)
23207 -- ada.finalization.list_controller (spec)
23208 -- ada.finalization.list_controller (body)
23209 -- system.file_control_block (spec)
23210 -- system.file_io (spec)
23211 -- system.file_io (body)
23212 -- ada.text_io (spec)
23213 -- ada.text_io (body)
23215 -- END ELABORATION ORDER
23219 -- The following source file name pragmas allow the generated file
23220 -- names to be unique for different main programs. They are needed
23221 -- since the package name will always be Ada_Main.
23223 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
23224 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
23226 -- Generated package body for Ada_Main starts here
23228 package body ada_main is
23230 -- The actual finalization is performed by calling the
23231 -- library routine in System.Standard_Library.Adafinal
23233 procedure Do_Finalize;
23234 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
23241 procedure adainit is
23243 -- These booleans are set to True once the associated unit has
23244 -- been elaborated. It is also used to avoid elaborating the
23245 -- same unit twice.
23248 pragma Import (Ada, E040, "interfaces__c_streams_E");
23251 pragma Import (Ada, E008, "ada__exceptions_E");
23254 pragma Import (Ada, E014, "system__exception_table_E");
23257 pragma Import (Ada, E053, "ada__io_exceptions_E");
23260 pragma Import (Ada, E017, "system__exceptions_E");
23263 pragma Import (Ada, E024, "system__secondary_stack_E");
23266 pragma Import (Ada, E030, "system__stack_checking_E");
23269 pragma Import (Ada, E028, "system__soft_links_E");
23272 pragma Import (Ada, E035, "ada__tags_E");
23275 pragma Import (Ada, E033, "ada__streams_E");
23278 pragma Import (Ada, E046, "system__finalization_root_E");
23281 pragma Import (Ada, E048, "system__finalization_implementation_E");
23284 pragma Import (Ada, E044, "ada__finalization_E");
23287 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23290 pragma Import (Ada, E055, "system__file_control_block_E");
23293 pragma Import (Ada, E042, "system__file_io_E");
23296 pragma Import (Ada, E006, "ada__text_io_E");
23298 -- Set_Globals is a library routine that stores away the
23299 -- value of the indicated set of global values in global
23300 -- variables within the library.
23302 procedure Set_Globals
23303 (Main_Priority : Integer;
23304 Time_Slice_Value : Integer;
23305 WC_Encoding : Character;
23306 Locking_Policy : Character;
23307 Queuing_Policy : Character;
23308 Task_Dispatching_Policy : Character;
23309 Adafinal : System.Address;
23310 Unreserve_All_Interrupts : Integer;
23311 Exception_Tracebacks : Integer);
23312 @findex __gnat_set_globals
23313 pragma Import (C, Set_Globals, "__gnat_set_globals");
23315 -- SDP_Table_Build is a library routine used to build the
23316 -- exception tables. See unit Ada.Exceptions in files
23317 -- a-except.ads/adb for full details of how zero cost
23318 -- exception handling works. This procedure, the call to
23319 -- it, and the two following tables are all omitted if the
23320 -- build is in longjmp/setjmp exception mode.
23322 @findex SDP_Table_Build
23323 @findex Zero Cost Exceptions
23324 procedure SDP_Table_Build
23325 (SDP_Addresses : System.Address;
23326 SDP_Count : Natural;
23327 Elab_Addresses : System.Address;
23328 Elab_Addr_Count : Natural);
23329 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
23331 -- Table of Unit_Exception_Table addresses. Used for zero
23332 -- cost exception handling to build the top level table.
23334 ST : aliased constant array (1 .. 23) of System.Address := (
23336 Ada.Text_Io'UET_Address,
23337 Ada.Exceptions'UET_Address,
23338 Gnat.Heap_Sort_A'UET_Address,
23339 System.Exception_Table'UET_Address,
23340 System.Machine_State_Operations'UET_Address,
23341 System.Secondary_Stack'UET_Address,
23342 System.Parameters'UET_Address,
23343 System.Soft_Links'UET_Address,
23344 System.Stack_Checking'UET_Address,
23345 System.Traceback'UET_Address,
23346 Ada.Streams'UET_Address,
23347 Ada.Tags'UET_Address,
23348 System.String_Ops'UET_Address,
23349 Interfaces.C_Streams'UET_Address,
23350 System.File_Io'UET_Address,
23351 Ada.Finalization'UET_Address,
23352 System.Finalization_Root'UET_Address,
23353 System.Finalization_Implementation'UET_Address,
23354 System.String_Ops_Concat_3'UET_Address,
23355 System.Stream_Attributes'UET_Address,
23356 System.File_Control_Block'UET_Address,
23357 Ada.Finalization.List_Controller'UET_Address);
23359 -- Table of addresses of elaboration routines. Used for
23360 -- zero cost exception handling to make sure these
23361 -- addresses are included in the top level procedure
23364 EA : aliased constant array (1 .. 23) of System.Address := (
23365 adainit'Code_Address,
23366 Do_Finalize'Code_Address,
23367 Ada.Exceptions'Elab_Spec'Address,
23368 System.Exceptions'Elab_Spec'Address,
23369 Interfaces.C_Streams'Elab_Spec'Address,
23370 System.Exception_Table'Elab_Body'Address,
23371 Ada.Io_Exceptions'Elab_Spec'Address,
23372 System.Stack_Checking'Elab_Spec'Address,
23373 System.Soft_Links'Elab_Body'Address,
23374 System.Secondary_Stack'Elab_Body'Address,
23375 Ada.Tags'Elab_Spec'Address,
23376 Ada.Tags'Elab_Body'Address,
23377 Ada.Streams'Elab_Spec'Address,
23378 System.Finalization_Root'Elab_Spec'Address,
23379 Ada.Exceptions'Elab_Body'Address,
23380 System.Finalization_Implementation'Elab_Spec'Address,
23381 System.Finalization_Implementation'Elab_Body'Address,
23382 Ada.Finalization'Elab_Spec'Address,
23383 Ada.Finalization.List_Controller'Elab_Spec'Address,
23384 System.File_Control_Block'Elab_Spec'Address,
23385 System.File_Io'Elab_Body'Address,
23386 Ada.Text_Io'Elab_Spec'Address,
23387 Ada.Text_Io'Elab_Body'Address);
23389 -- Start of processing for adainit
23393 -- Call SDP_Table_Build to build the top level procedure
23394 -- table for zero cost exception handling (omitted in
23395 -- longjmp/setjmp mode).
23397 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23399 -- Call Set_Globals to record various information for
23400 -- this partition. The values are derived by the binder
23401 -- from information stored in the ali files by the compiler.
23403 @findex __gnat_set_globals
23405 (Main_Priority => -1,
23406 -- Priority of main program, -1 if no pragma Priority used
23408 Time_Slice_Value => -1,
23409 -- Time slice from Time_Slice pragma, -1 if none used
23411 WC_Encoding => 'b',
23412 -- Wide_Character encoding used, default is brackets
23414 Locking_Policy => ' ',
23415 -- Locking_Policy used, default of space means not
23416 -- specified, otherwise it is the first character of
23417 -- the policy name.
23419 Queuing_Policy => ' ',
23420 -- Queuing_Policy used, default of space means not
23421 -- specified, otherwise it is the first character of
23422 -- the policy name.
23424 Task_Dispatching_Policy => ' ',
23425 -- Task_Dispatching_Policy used, default of space means
23426 -- not specified, otherwise first character of the
23429 Adafinal => System.Null_Address,
23430 -- Address of Adafinal routine, not used anymore
23432 Unreserve_All_Interrupts => 0,
23433 -- Set true if pragma Unreserve_All_Interrupts was used
23435 Exception_Tracebacks => 0);
23436 -- Indicates if exception tracebacks are enabled
23438 Elab_Final_Code := 1;
23440 -- Now we have the elaboration calls for all units in the partition.
23441 -- The Elab_Spec and Elab_Body attributes generate references to the
23442 -- implicit elaboration procedures generated by the compiler for
23443 -- each unit that requires elaboration.
23446 Interfaces.C_Streams'Elab_Spec;
23450 Ada.Exceptions'Elab_Spec;
23453 System.Exception_Table'Elab_Body;
23457 Ada.Io_Exceptions'Elab_Spec;
23461 System.Exceptions'Elab_Spec;
23465 System.Stack_Checking'Elab_Spec;
23468 System.Soft_Links'Elab_Body;
23473 System.Secondary_Stack'Elab_Body;
23477 Ada.Tags'Elab_Spec;
23480 Ada.Tags'Elab_Body;
23484 Ada.Streams'Elab_Spec;
23488 System.Finalization_Root'Elab_Spec;
23492 Ada.Exceptions'Elab_Body;
23496 System.Finalization_Implementation'Elab_Spec;
23499 System.Finalization_Implementation'Elab_Body;
23503 Ada.Finalization'Elab_Spec;
23507 Ada.Finalization.List_Controller'Elab_Spec;
23511 System.File_Control_Block'Elab_Spec;
23515 System.File_Io'Elab_Body;
23519 Ada.Text_Io'Elab_Spec;
23522 Ada.Text_Io'Elab_Body;
23526 Elab_Final_Code := 0;
23534 procedure adafinal is
23543 -- main is actually a function, as in the ANSI C standard,
23544 -- defined to return the exit status. The three parameters
23545 -- are the argument count, argument values and environment
23548 @findex Main Program
23551 argv : System.Address;
23552 envp : System.Address)
23555 -- The initialize routine performs low level system
23556 -- initialization using a standard library routine which
23557 -- sets up signal handling and performs any other
23558 -- required setup. The routine can be found in file
23561 @findex __gnat_initialize
23562 procedure initialize;
23563 pragma Import (C, initialize, "__gnat_initialize");
23565 -- The finalize routine performs low level system
23566 -- finalization using a standard library routine. The
23567 -- routine is found in file a-final.c and in the standard
23568 -- distribution is a dummy routine that does nothing, so
23569 -- really this is a hook for special user finalization.
23571 @findex __gnat_finalize
23572 procedure finalize;
23573 pragma Import (C, finalize, "__gnat_finalize");
23575 -- We get to the main program of the partition by using
23576 -- pragma Import because if we try to with the unit and
23577 -- call it Ada style, then not only do we waste time
23578 -- recompiling it, but also, we don't really know the right
23579 -- switches (e.g.@: identifier character set) to be used
23582 procedure Ada_Main_Program;
23583 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23585 -- Start of processing for main
23588 -- Save global variables
23594 -- Call low level system initialization
23598 -- Call our generated Ada initialization routine
23602 -- This is the point at which we want the debugger to get
23607 -- Now we call the main program of the partition
23611 -- Perform Ada finalization
23615 -- Perform low level system finalization
23619 -- Return the proper exit status
23620 return (gnat_exit_status);
23623 -- This section is entirely comments, so it has no effect on the
23624 -- compilation of the Ada_Main package. It provides the list of
23625 -- object files and linker options, as well as some standard
23626 -- libraries needed for the link. The gnatlink utility parses
23627 -- this b~hello.adb file to read these comment lines to generate
23628 -- the appropriate command line arguments for the call to the
23629 -- system linker. The BEGIN/END lines are used for sentinels for
23630 -- this parsing operation.
23632 -- The exact file names will of course depend on the environment,
23633 -- host/target and location of files on the host system.
23635 @findex Object file list
23636 -- BEGIN Object file/option list
23639 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23640 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23641 -- END Object file/option list
23647 The Ada code in the above example is exactly what is generated by the
23648 binder. We have added comments to more clearly indicate the function
23649 of each part of the generated @code{Ada_Main} package.
23651 The code is standard Ada in all respects, and can be processed by any
23652 tools that handle Ada. In particular, it is possible to use the debugger
23653 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23654 suppose that for reasons that you do not understand, your program is crashing
23655 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23656 you can place a breakpoint on the call:
23658 @smallexample @c ada
23659 Ada.Text_Io'Elab_Body;
23663 and trace the elaboration routine for this package to find out where
23664 the problem might be (more usually of course you would be debugging
23665 elaboration code in your own application).
23667 @node Elaboration Order Handling in GNAT
23668 @appendix Elaboration Order Handling in GNAT
23669 @cindex Order of elaboration
23670 @cindex Elaboration control
23673 * Elaboration Code::
23674 * Checking the Elaboration Order::
23675 * Controlling the Elaboration Order::
23676 * Controlling Elaboration in GNAT - Internal Calls::
23677 * Controlling Elaboration in GNAT - External Calls::
23678 * Default Behavior in GNAT - Ensuring Safety::
23679 * Treatment of Pragma Elaborate::
23680 * Elaboration Issues for Library Tasks::
23681 * Mixing Elaboration Models::
23682 * What to Do If the Default Elaboration Behavior Fails::
23683 * Elaboration for Dispatching Calls::
23684 * Summary of Procedures for Elaboration Control::
23685 * Other Elaboration Order Considerations::
23689 This chapter describes the handling of elaboration code in Ada and
23690 in GNAT, and discusses how the order of elaboration of program units can
23691 be controlled in GNAT, either automatically or with explicit programming
23694 @node Elaboration Code
23695 @section Elaboration Code
23698 Ada provides rather general mechanisms for executing code at elaboration
23699 time, that is to say before the main program starts executing. Such code arises
23703 @item Initializers for variables.
23704 Variables declared at the library level, in package specs or bodies, can
23705 require initialization that is performed at elaboration time, as in:
23706 @smallexample @c ada
23708 Sqrt_Half : Float := Sqrt (0.5);
23712 @item Package initialization code
23713 Code in a @code{BEGIN-END} section at the outer level of a package body is
23714 executed as part of the package body elaboration code.
23716 @item Library level task allocators
23717 Tasks that are declared using task allocators at the library level
23718 start executing immediately and hence can execute at elaboration time.
23722 Subprogram calls are possible in any of these contexts, which means that
23723 any arbitrary part of the program may be executed as part of the elaboration
23724 code. It is even possible to write a program which does all its work at
23725 elaboration time, with a null main program, although stylistically this
23726 would usually be considered an inappropriate way to structure
23729 An important concern arises in the context of elaboration code:
23730 we have to be sure that it is executed in an appropriate order. What we
23731 have is a series of elaboration code sections, potentially one section
23732 for each unit in the program. It is important that these execute
23733 in the correct order. Correctness here means that, taking the above
23734 example of the declaration of @code{Sqrt_Half},
23735 if some other piece of
23736 elaboration code references @code{Sqrt_Half},
23737 then it must run after the
23738 section of elaboration code that contains the declaration of
23741 There would never be any order of elaboration problem if we made a rule
23742 that whenever you @code{with} a unit, you must elaborate both the spec and body
23743 of that unit before elaborating the unit doing the @code{with}'ing:
23745 @smallexample @c ada
23749 package Unit_2 is @dots{}
23755 would require that both the body and spec of @code{Unit_1} be elaborated
23756 before the spec of @code{Unit_2}. However, a rule like that would be far too
23757 restrictive. In particular, it would make it impossible to have routines
23758 in separate packages that were mutually recursive.
23760 You might think that a clever enough compiler could look at the actual
23761 elaboration code and determine an appropriate correct order of elaboration,
23762 but in the general case, this is not possible. Consider the following
23765 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23767 the variable @code{Sqrt_1}, which is declared in the elaboration code
23768 of the body of @code{Unit_1}:
23770 @smallexample @c ada
23772 Sqrt_1 : Float := Sqrt (0.1);
23777 The elaboration code of the body of @code{Unit_1} also contains:
23779 @smallexample @c ada
23782 if expression_1 = 1 then
23783 Q := Unit_2.Func_2;
23790 @code{Unit_2} is exactly parallel,
23791 it has a procedure @code{Func_2} that references
23792 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23793 the body @code{Unit_2}:
23795 @smallexample @c ada
23797 Sqrt_2 : Float := Sqrt (0.1);
23802 The elaboration code of the body of @code{Unit_2} also contains:
23804 @smallexample @c ada
23807 if expression_2 = 2 then
23808 Q := Unit_1.Func_1;
23815 Now the question is, which of the following orders of elaboration is
23840 If you carefully analyze the flow here, you will see that you cannot tell
23841 at compile time the answer to this question.
23842 If @code{expression_1} is not equal to 1,
23843 and @code{expression_2} is not equal to 2,
23844 then either order is acceptable, because neither of the function calls is
23845 executed. If both tests evaluate to true, then neither order is acceptable
23846 and in fact there is no correct order.
23848 If one of the two expressions is true, and the other is false, then one
23849 of the above orders is correct, and the other is incorrect. For example,
23850 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23851 then the call to @code{Func_1}
23852 will occur, but not the call to @code{Func_2.}
23853 This means that it is essential
23854 to elaborate the body of @code{Unit_1} before
23855 the body of @code{Unit_2}, so the first
23856 order of elaboration is correct and the second is wrong.
23858 By making @code{expression_1} and @code{expression_2}
23859 depend on input data, or perhaps
23860 the time of day, we can make it impossible for the compiler or binder
23861 to figure out which of these expressions will be true, and hence it
23862 is impossible to guarantee a safe order of elaboration at run time.
23864 @node Checking the Elaboration Order
23865 @section Checking the Elaboration Order
23868 In some languages that involve the same kind of elaboration problems,
23869 e.g.@: Java and C++, the programmer is expected to worry about these
23870 ordering problems himself, and it is common to
23871 write a program in which an incorrect elaboration order gives
23872 surprising results, because it references variables before they
23874 Ada is designed to be a safe language, and a programmer-beware approach is
23875 clearly not sufficient. Consequently, the language provides three lines
23879 @item Standard rules
23880 Some standard rules restrict the possible choice of elaboration
23881 order. In particular, if you @code{with} a unit, then its spec is always
23882 elaborated before the unit doing the @code{with}. Similarly, a parent
23883 spec is always elaborated before the child spec, and finally
23884 a spec is always elaborated before its corresponding body.
23886 @item Dynamic elaboration checks
23887 @cindex Elaboration checks
23888 @cindex Checks, elaboration
23889 Dynamic checks are made at run time, so that if some entity is accessed
23890 before it is elaborated (typically by means of a subprogram call)
23891 then the exception (@code{Program_Error}) is raised.
23893 @item Elaboration control
23894 Facilities are provided for the programmer to specify the desired order
23898 Let's look at these facilities in more detail. First, the rules for
23899 dynamic checking. One possible rule would be simply to say that the
23900 exception is raised if you access a variable which has not yet been
23901 elaborated. The trouble with this approach is that it could require
23902 expensive checks on every variable reference. Instead Ada has two
23903 rules which are a little more restrictive, but easier to check, and
23907 @item Restrictions on calls
23908 A subprogram can only be called at elaboration time if its body
23909 has been elaborated. The rules for elaboration given above guarantee
23910 that the spec of the subprogram has been elaborated before the
23911 call, but not the body. If this rule is violated, then the
23912 exception @code{Program_Error} is raised.
23914 @item Restrictions on instantiations
23915 A generic unit can only be instantiated if the body of the generic
23916 unit has been elaborated. Again, the rules for elaboration given above
23917 guarantee that the spec of the generic unit has been elaborated
23918 before the instantiation, but not the body. If this rule is
23919 violated, then the exception @code{Program_Error} is raised.
23923 The idea is that if the body has been elaborated, then any variables
23924 it references must have been elaborated; by checking for the body being
23925 elaborated we guarantee that none of its references causes any
23926 trouble. As we noted above, this is a little too restrictive, because a
23927 subprogram that has no non-local references in its body may in fact be safe
23928 to call. However, it really would be unsafe to rely on this, because
23929 it would mean that the caller was aware of details of the implementation
23930 in the body. This goes against the basic tenets of Ada.
23932 A plausible implementation can be described as follows.
23933 A Boolean variable is associated with each subprogram
23934 and each generic unit. This variable is initialized to False, and is set to
23935 True at the point body is elaborated. Every call or instantiation checks the
23936 variable, and raises @code{Program_Error} if the variable is False.
23938 Note that one might think that it would be good enough to have one Boolean
23939 variable for each package, but that would not deal with cases of trying
23940 to call a body in the same package as the call
23941 that has not been elaborated yet.
23942 Of course a compiler may be able to do enough analysis to optimize away
23943 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23944 does such optimizations, but still the easiest conceptual model is to
23945 think of there being one variable per subprogram.
23947 @node Controlling the Elaboration Order
23948 @section Controlling the Elaboration Order
23951 In the previous section we discussed the rules in Ada which ensure
23952 that @code{Program_Error} is raised if an incorrect elaboration order is
23953 chosen. This prevents erroneous executions, but we need mechanisms to
23954 specify a correct execution and avoid the exception altogether.
23955 To achieve this, Ada provides a number of features for controlling
23956 the order of elaboration. We discuss these features in this section.
23958 First, there are several ways of indicating to the compiler that a given
23959 unit has no elaboration problems:
23962 @item packages that do not require a body
23963 A library package that does not require a body does not permit
23964 a body (this rule was introduced in Ada 95).
23965 Thus if we have a such a package, as in:
23967 @smallexample @c ada
23970 package Definitions is
23972 type m is new integer;
23974 type a is array (1 .. 10) of m;
23975 type b is array (1 .. 20) of m;
23983 A package that @code{with}'s @code{Definitions} may safely instantiate
23984 @code{Definitions.Subp} because the compiler can determine that there
23985 definitely is no package body to worry about in this case
23988 @cindex pragma Pure
23990 Places sufficient restrictions on a unit to guarantee that
23991 no call to any subprogram in the unit can result in an
23992 elaboration problem. This means that the compiler does not need
23993 to worry about the point of elaboration of such units, and in
23994 particular, does not need to check any calls to any subprograms
23997 @item pragma Preelaborate
23998 @findex Preelaborate
23999 @cindex pragma Preelaborate
24000 This pragma places slightly less stringent restrictions on a unit than
24002 but these restrictions are still sufficient to ensure that there
24003 are no elaboration problems with any calls to the unit.
24005 @item pragma Elaborate_Body
24006 @findex Elaborate_Body
24007 @cindex pragma Elaborate_Body
24008 This pragma requires that the body of a unit be elaborated immediately
24009 after its spec. Suppose a unit @code{A} has such a pragma,
24010 and unit @code{B} does
24011 a @code{with} of unit @code{A}. Recall that the standard rules require
24012 the spec of unit @code{A}
24013 to be elaborated before the @code{with}'ing unit; given the pragma in
24014 @code{A}, we also know that the body of @code{A}
24015 will be elaborated before @code{B}, so
24016 that calls to @code{A} are safe and do not need a check.
24021 unlike pragma @code{Pure} and pragma @code{Preelaborate},
24023 @code{Elaborate_Body} does not guarantee that the program is
24024 free of elaboration problems, because it may not be possible
24025 to satisfy the requested elaboration order.
24026 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
24028 marks @code{Unit_1} as @code{Elaborate_Body},
24029 and not @code{Unit_2,} then the order of
24030 elaboration will be:
24042 Now that means that the call to @code{Func_1} in @code{Unit_2}
24043 need not be checked,
24044 it must be safe. But the call to @code{Func_2} in
24045 @code{Unit_1} may still fail if
24046 @code{Expression_1} is equal to 1,
24047 and the programmer must still take
24048 responsibility for this not being the case.
24050 If all units carry a pragma @code{Elaborate_Body}, then all problems are
24051 eliminated, except for calls entirely within a body, which are
24052 in any case fully under programmer control. However, using the pragma
24053 everywhere is not always possible.
24054 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
24055 we marked both of them as having pragma @code{Elaborate_Body}, then
24056 clearly there would be no possible elaboration order.
24058 The above pragmas allow a server to guarantee safe use by clients, and
24059 clearly this is the preferable approach. Consequently a good rule
24060 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
24061 and if this is not possible,
24062 mark them as @code{Elaborate_Body} if possible.
24063 As we have seen, there are situations where neither of these
24064 three pragmas can be used.
24065 So we also provide methods for clients to control the
24066 order of elaboration of the servers on which they depend:
24069 @item pragma Elaborate (unit)
24071 @cindex pragma Elaborate
24072 This pragma is placed in the context clause, after a @code{with} clause,
24073 and it requires that the body of the named unit be elaborated before
24074 the unit in which the pragma occurs. The idea is to use this pragma
24075 if the current unit calls at elaboration time, directly or indirectly,
24076 some subprogram in the named unit.
24078 @item pragma Elaborate_All (unit)
24079 @findex Elaborate_All
24080 @cindex pragma Elaborate_All
24081 This is a stronger version of the Elaborate pragma. Consider the
24085 Unit A @code{with}'s unit B and calls B.Func in elab code
24086 Unit B @code{with}'s unit C, and B.Func calls C.Func
24090 Now if we put a pragma @code{Elaborate (B)}
24091 in unit @code{A}, this ensures that the
24092 body of @code{B} is elaborated before the call, but not the
24093 body of @code{C}, so
24094 the call to @code{C.Func} could still cause @code{Program_Error} to
24097 The effect of a pragma @code{Elaborate_All} is stronger, it requires
24098 not only that the body of the named unit be elaborated before the
24099 unit doing the @code{with}, but also the bodies of all units that the
24100 named unit uses, following @code{with} links transitively. For example,
24101 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
24103 not only that the body of @code{B} be elaborated before @code{A},
24105 body of @code{C}, because @code{B} @code{with}'s @code{C}.
24109 We are now in a position to give a usage rule in Ada for avoiding
24110 elaboration problems, at least if dynamic dispatching and access to
24111 subprogram values are not used. We will handle these cases separately
24114 The rule is simple. If a unit has elaboration code that can directly or
24115 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
24116 a generic package in a @code{with}'ed unit,
24117 then if the @code{with}'ed unit does not have
24118 pragma @code{Pure} or @code{Preelaborate}, then the client should have
24119 a pragma @code{Elaborate_All}
24120 for the @code{with}'ed unit. By following this rule a client is
24121 assured that calls can be made without risk of an exception.
24123 For generic subprogram instantiations, the rule can be relaxed to
24124 require only a pragma @code{Elaborate} since elaborating the body
24125 of a subprogram cannot cause any transitive elaboration (we are
24126 not calling the subprogram in this case, just elaborating its
24129 If this rule is not followed, then a program may be in one of four
24133 @item No order exists
24134 No order of elaboration exists which follows the rules, taking into
24135 account any @code{Elaborate}, @code{Elaborate_All},
24136 or @code{Elaborate_Body} pragmas. In
24137 this case, an Ada compiler must diagnose the situation at bind
24138 time, and refuse to build an executable program.
24140 @item One or more orders exist, all incorrect
24141 One or more acceptable elaboration orders exist, and all of them
24142 generate an elaboration order problem. In this case, the binder
24143 can build an executable program, but @code{Program_Error} will be raised
24144 when the program is run.
24146 @item Several orders exist, some right, some incorrect
24147 One or more acceptable elaboration orders exists, and some of them
24148 work, and some do not. The programmer has not controlled
24149 the order of elaboration, so the binder may or may not pick one of
24150 the correct orders, and the program may or may not raise an
24151 exception when it is run. This is the worst case, because it means
24152 that the program may fail when moved to another compiler, or even
24153 another version of the same compiler.
24155 @item One or more orders exists, all correct
24156 One ore more acceptable elaboration orders exist, and all of them
24157 work. In this case the program runs successfully. This state of
24158 affairs can be guaranteed by following the rule we gave above, but
24159 may be true even if the rule is not followed.
24163 Note that one additional advantage of following our rules on the use
24164 of @code{Elaborate} and @code{Elaborate_All}
24165 is that the program continues to stay in the ideal (all orders OK) state
24166 even if maintenance
24167 changes some bodies of some units. Conversely, if a program that does
24168 not follow this rule happens to be safe at some point, this state of affairs
24169 may deteriorate silently as a result of maintenance changes.
24171 You may have noticed that the above discussion did not mention
24172 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
24173 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
24174 code in the body makes calls to some other unit, so it is still necessary
24175 to use @code{Elaborate_All} on such units.
24177 @node Controlling Elaboration in GNAT - Internal Calls
24178 @section Controlling Elaboration in GNAT - Internal Calls
24181 In the case of internal calls, i.e., calls within a single package, the
24182 programmer has full control over the order of elaboration, and it is up
24183 to the programmer to elaborate declarations in an appropriate order. For
24186 @smallexample @c ada
24189 function One return Float;
24193 function One return Float is
24202 will obviously raise @code{Program_Error} at run time, because function
24203 One will be called before its body is elaborated. In this case GNAT will
24204 generate a warning that the call will raise @code{Program_Error}:
24210 2. function One return Float;
24212 4. Q : Float := One;
24214 >>> warning: cannot call "One" before body is elaborated
24215 >>> warning: Program_Error will be raised at run time
24218 6. function One return Float is
24231 Note that in this particular case, it is likely that the call is safe, because
24232 the function @code{One} does not access any global variables.
24233 Nevertheless in Ada, we do not want the validity of the check to depend on
24234 the contents of the body (think about the separate compilation case), so this
24235 is still wrong, as we discussed in the previous sections.
24237 The error is easily corrected by rearranging the declarations so that the
24238 body of @code{One} appears before the declaration containing the call
24239 (note that in Ada 95 and Ada 2005,
24240 declarations can appear in any order, so there is no restriction that
24241 would prevent this reordering, and if we write:
24243 @smallexample @c ada
24246 function One return Float;
24248 function One return Float is
24259 then all is well, no warning is generated, and no
24260 @code{Program_Error} exception
24262 Things are more complicated when a chain of subprograms is executed:
24264 @smallexample @c ada
24267 function A return Integer;
24268 function B return Integer;
24269 function C return Integer;
24271 function B return Integer is begin return A; end;
24272 function C return Integer is begin return B; end;
24276 function A return Integer is begin return 1; end;
24282 Now the call to @code{C}
24283 at elaboration time in the declaration of @code{X} is correct, because
24284 the body of @code{C} is already elaborated,
24285 and the call to @code{B} within the body of
24286 @code{C} is correct, but the call
24287 to @code{A} within the body of @code{B} is incorrect, because the body
24288 of @code{A} has not been elaborated, so @code{Program_Error}
24289 will be raised on the call to @code{A}.
24290 In this case GNAT will generate a
24291 warning that @code{Program_Error} may be
24292 raised at the point of the call. Let's look at the warning:
24298 2. function A return Integer;
24299 3. function B return Integer;
24300 4. function C return Integer;
24302 6. function B return Integer is begin return A; end;
24304 >>> warning: call to "A" before body is elaborated may
24305 raise Program_Error
24306 >>> warning: "B" called at line 7
24307 >>> warning: "C" called at line 9
24309 7. function C return Integer is begin return B; end;
24311 9. X : Integer := C;
24313 11. function A return Integer is begin return 1; end;
24323 Note that the message here says ``may raise'', instead of the direct case,
24324 where the message says ``will be raised''. That's because whether
24326 actually called depends in general on run-time flow of control.
24327 For example, if the body of @code{B} said
24329 @smallexample @c ada
24332 function B return Integer is
24334 if some-condition-depending-on-input-data then
24345 then we could not know until run time whether the incorrect call to A would
24346 actually occur, so @code{Program_Error} might
24347 or might not be raised. It is possible for a compiler to
24348 do a better job of analyzing bodies, to
24349 determine whether or not @code{Program_Error}
24350 might be raised, but it certainly
24351 couldn't do a perfect job (that would require solving the halting problem
24352 and is provably impossible), and because this is a warning anyway, it does
24353 not seem worth the effort to do the analysis. Cases in which it
24354 would be relevant are rare.
24356 In practice, warnings of either of the forms given
24357 above will usually correspond to
24358 real errors, and should be examined carefully and eliminated.
24359 In the rare case where a warning is bogus, it can be suppressed by any of
24360 the following methods:
24364 Compile with the @option{-gnatws} switch set
24367 Suppress @code{Elaboration_Check} for the called subprogram
24370 Use pragma @code{Warnings_Off} to turn warnings off for the call
24374 For the internal elaboration check case,
24375 GNAT by default generates the
24376 necessary run-time checks to ensure
24377 that @code{Program_Error} is raised if any
24378 call fails an elaboration check. Of course this can only happen if a
24379 warning has been issued as described above. The use of pragma
24380 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24381 some of these checks, meaning that it may be possible (but is not
24382 guaranteed) for a program to be able to call a subprogram whose body
24383 is not yet elaborated, without raising a @code{Program_Error} exception.
24385 @node Controlling Elaboration in GNAT - External Calls
24386 @section Controlling Elaboration in GNAT - External Calls
24389 The previous section discussed the case in which the execution of a
24390 particular thread of elaboration code occurred entirely within a
24391 single unit. This is the easy case to handle, because a programmer
24392 has direct and total control over the order of elaboration, and
24393 furthermore, checks need only be generated in cases which are rare
24394 and which the compiler can easily detect.
24395 The situation is more complex when separate compilation is taken into account.
24396 Consider the following:
24398 @smallexample @c ada
24402 function Sqrt (Arg : Float) return Float;
24405 package body Math is
24406 function Sqrt (Arg : Float) return Float is
24415 X : Float := Math.Sqrt (0.5);
24428 where @code{Main} is the main program. When this program is executed, the
24429 elaboration code must first be executed, and one of the jobs of the
24430 binder is to determine the order in which the units of a program are
24431 to be elaborated. In this case we have four units: the spec and body
24433 the spec of @code{Stuff} and the body of @code{Main}).
24434 In what order should the four separate sections of elaboration code
24437 There are some restrictions in the order of elaboration that the binder
24438 can choose. In particular, if unit U has a @code{with}
24439 for a package @code{X}, then you
24440 are assured that the spec of @code{X}
24441 is elaborated before U , but you are
24442 not assured that the body of @code{X}
24443 is elaborated before U.
24444 This means that in the above case, the binder is allowed to choose the
24455 but that's not good, because now the call to @code{Math.Sqrt}
24456 that happens during
24457 the elaboration of the @code{Stuff}
24458 spec happens before the body of @code{Math.Sqrt} is
24459 elaborated, and hence causes @code{Program_Error} exception to be raised.
24460 At first glance, one might say that the binder is misbehaving, because
24461 obviously you want to elaborate the body of something you @code{with}
24463 that is not a general rule that can be followed in all cases. Consider
24465 @smallexample @c ada
24468 package X is @dots{}
24470 package Y is @dots{}
24473 package body Y is @dots{}
24476 package body X is @dots{}
24482 This is a common arrangement, and, apart from the order of elaboration
24483 problems that might arise in connection with elaboration code, this works fine.
24484 A rule that says that you must first elaborate the body of anything you
24485 @code{with} cannot work in this case:
24486 the body of @code{X} @code{with}'s @code{Y},
24487 which means you would have to
24488 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24490 you have to elaborate the body of @code{X} first, but @dots{} and we have a
24491 loop that cannot be broken.
24493 It is true that the binder can in many cases guess an order of elaboration
24494 that is unlikely to cause a @code{Program_Error}
24495 exception to be raised, and it tries to do so (in the
24496 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24498 elaborate the body of @code{Math} right after its spec, so all will be well).
24500 However, a program that blindly relies on the binder to be helpful can
24501 get into trouble, as we discussed in the previous sections, so
24503 provides a number of facilities for assisting the programmer in
24504 developing programs that are robust with respect to elaboration order.
24506 @node Default Behavior in GNAT - Ensuring Safety
24507 @section Default Behavior in GNAT - Ensuring Safety
24510 The default behavior in GNAT ensures elaboration safety. In its
24511 default mode GNAT implements the
24512 rule we previously described as the right approach. Let's restate it:
24516 @emph{If a unit has elaboration code that can directly or indirectly make a
24517 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24518 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24519 does not have pragma @code{Pure} or
24520 @code{Preelaborate}, then the client should have an
24521 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24523 @emph{In the case of instantiating a generic subprogram, it is always
24524 sufficient to have only an @code{Elaborate} pragma for the
24525 @code{with}'ed unit.}
24529 By following this rule a client is assured that calls and instantiations
24530 can be made without risk of an exception.
24532 In this mode GNAT traces all calls that are potentially made from
24533 elaboration code, and puts in any missing implicit @code{Elaborate}
24534 and @code{Elaborate_All} pragmas.
24535 The advantage of this approach is that no elaboration problems
24536 are possible if the binder can find an elaboration order that is
24537 consistent with these implicit @code{Elaborate} and
24538 @code{Elaborate_All} pragmas. The
24539 disadvantage of this approach is that no such order may exist.
24541 If the binder does not generate any diagnostics, then it means that it has
24542 found an elaboration order that is guaranteed to be safe. However, the binder
24543 may still be relying on implicitly generated @code{Elaborate} and
24544 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24547 If it is important to guarantee portability, then the compilations should
24550 (warn on elaboration problems) switch. This will cause warning messages
24551 to be generated indicating the missing @code{Elaborate} and
24552 @code{Elaborate_All} pragmas.
24553 Consider the following source program:
24555 @smallexample @c ada
24560 m : integer := k.r;
24567 where it is clear that there
24568 should be a pragma @code{Elaborate_All}
24569 for unit @code{k}. An implicit pragma will be generated, and it is
24570 likely that the binder will be able to honor it. However, if you want
24571 to port this program to some other Ada compiler than GNAT.
24572 it is safer to include the pragma explicitly in the source. If this
24573 unit is compiled with the
24575 switch, then the compiler outputs a warning:
24582 3. m : integer := k.r;
24584 >>> warning: call to "r" may raise Program_Error
24585 >>> warning: missing pragma Elaborate_All for "k"
24593 and these warnings can be used as a guide for supplying manually
24594 the missing pragmas. It is usually a bad idea to use this warning
24595 option during development. That's because it will warn you when
24596 you need to put in a pragma, but cannot warn you when it is time
24597 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24598 unnecessary dependencies and even false circularities.
24600 This default mode is more restrictive than the Ada Reference
24601 Manual, and it is possible to construct programs which will compile
24602 using the dynamic model described there, but will run into a
24603 circularity using the safer static model we have described.
24605 Of course any Ada compiler must be able to operate in a mode
24606 consistent with the requirements of the Ada Reference Manual,
24607 and in particular must have the capability of implementing the
24608 standard dynamic model of elaboration with run-time checks.
24610 In GNAT, this standard mode can be achieved either by the use of
24611 the @option{-gnatE} switch on the compiler (@command{gcc} or
24612 @command{gnatmake}) command, or by the use of the configuration pragma:
24614 @smallexample @c ada
24615 pragma Elaboration_Checks (DYNAMIC);
24619 Either approach will cause the unit affected to be compiled using the
24620 standard dynamic run-time elaboration checks described in the Ada
24621 Reference Manual. The static model is generally preferable, since it
24622 is clearly safer to rely on compile and link time checks rather than
24623 run-time checks. However, in the case of legacy code, it may be
24624 difficult to meet the requirements of the static model. This
24625 issue is further discussed in
24626 @ref{What to Do If the Default Elaboration Behavior Fails}.
24628 Note that the static model provides a strict subset of the allowed
24629 behavior and programs of the Ada Reference Manual, so if you do
24630 adhere to the static model and no circularities exist,
24631 then you are assured that your program will
24632 work using the dynamic model, providing that you remove any
24633 pragma Elaborate statements from the source.
24635 @node Treatment of Pragma Elaborate
24636 @section Treatment of Pragma Elaborate
24637 @cindex Pragma Elaborate
24640 The use of @code{pragma Elaborate}
24641 should generally be avoided in Ada 95 and Ada 2005 programs,
24642 since there is no guarantee that transitive calls
24643 will be properly handled. Indeed at one point, this pragma was placed
24644 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24646 Now that's a bit restrictive. In practice, the case in which
24647 @code{pragma Elaborate} is useful is when the caller knows that there
24648 are no transitive calls, or that the called unit contains all necessary
24649 transitive @code{pragma Elaborate} statements, and legacy code often
24650 contains such uses.
24652 Strictly speaking the static mode in GNAT should ignore such pragmas,
24653 since there is no assurance at compile time that the necessary safety
24654 conditions are met. In practice, this would cause GNAT to be incompatible
24655 with correctly written Ada 83 code that had all necessary
24656 @code{pragma Elaborate} statements in place. Consequently, we made the
24657 decision that GNAT in its default mode will believe that if it encounters
24658 a @code{pragma Elaborate} then the programmer knows what they are doing,
24659 and it will trust that no elaboration errors can occur.
24661 The result of this decision is two-fold. First to be safe using the
24662 static mode, you should remove all @code{pragma Elaborate} statements.
24663 Second, when fixing circularities in existing code, you can selectively
24664 use @code{pragma Elaborate} statements to convince the static mode of
24665 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24668 When using the static mode with @option{-gnatwl}, any use of
24669 @code{pragma Elaborate} will generate a warning about possible
24672 @node Elaboration Issues for Library Tasks
24673 @section Elaboration Issues for Library Tasks
24674 @cindex Library tasks, elaboration issues
24675 @cindex Elaboration of library tasks
24678 In this section we examine special elaboration issues that arise for
24679 programs that declare library level tasks.
24681 Generally the model of execution of an Ada program is that all units are
24682 elaborated, and then execution of the program starts. However, the
24683 declaration of library tasks definitely does not fit this model. The
24684 reason for this is that library tasks start as soon as they are declared
24685 (more precisely, as soon as the statement part of the enclosing package
24686 body is reached), that is to say before elaboration
24687 of the program is complete. This means that if such a task calls a
24688 subprogram, or an entry in another task, the callee may or may not be
24689 elaborated yet, and in the standard
24690 Reference Manual model of dynamic elaboration checks, you can even
24691 get timing dependent Program_Error exceptions, since there can be
24692 a race between the elaboration code and the task code.
24694 The static model of elaboration in GNAT seeks to avoid all such
24695 dynamic behavior, by being conservative, and the conservative
24696 approach in this particular case is to assume that all the code
24697 in a task body is potentially executed at elaboration time if
24698 a task is declared at the library level.
24700 This can definitely result in unexpected circularities. Consider
24701 the following example
24703 @smallexample @c ada
24709 type My_Int is new Integer;
24711 function Ident (M : My_Int) return My_Int;
24715 package body Decls is
24716 task body Lib_Task is
24722 function Ident (M : My_Int) return My_Int is
24730 procedure Put_Val (Arg : Decls.My_Int);
24734 package body Utils is
24735 procedure Put_Val (Arg : Decls.My_Int) is
24737 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24744 Decls.Lib_Task.Start;
24749 If the above example is compiled in the default static elaboration
24750 mode, then a circularity occurs. The circularity comes from the call
24751 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24752 this call occurs in elaboration code, we need an implicit pragma
24753 @code{Elaborate_All} for @code{Utils}. This means that not only must
24754 the spec and body of @code{Utils} be elaborated before the body
24755 of @code{Decls}, but also the spec and body of any unit that is
24756 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24757 the body of @code{Decls}. This is the transitive implication of
24758 pragma @code{Elaborate_All} and it makes sense, because in general
24759 the body of @code{Put_Val} might have a call to something in a
24760 @code{with'ed} unit.
24762 In this case, the body of Utils (actually its spec) @code{with's}
24763 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24764 must be elaborated before itself, in case there is a call from the
24765 body of @code{Utils}.
24767 Here is the exact chain of events we are worrying about:
24771 In the body of @code{Decls} a call is made from within the body of a library
24772 task to a subprogram in the package @code{Utils}. Since this call may
24773 occur at elaboration time (given that the task is activated at elaboration
24774 time), we have to assume the worst, i.e., that the
24775 call does happen at elaboration time.
24778 This means that the body and spec of @code{Util} must be elaborated before
24779 the body of @code{Decls} so that this call does not cause an access before
24783 Within the body of @code{Util}, specifically within the body of
24784 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24788 One such @code{with}'ed package is package @code{Decls}, so there
24789 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24790 In fact there is such a call in this example, but we would have to
24791 assume that there was such a call even if it were not there, since
24792 we are not supposed to write the body of @code{Decls} knowing what
24793 is in the body of @code{Utils}; certainly in the case of the
24794 static elaboration model, the compiler does not know what is in
24795 other bodies and must assume the worst.
24798 This means that the spec and body of @code{Decls} must also be
24799 elaborated before we elaborate the unit containing the call, but
24800 that unit is @code{Decls}! This means that the body of @code{Decls}
24801 must be elaborated before itself, and that's a circularity.
24805 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24806 the body of @code{Decls} you will get a true Ada Reference Manual
24807 circularity that makes the program illegal.
24809 In practice, we have found that problems with the static model of
24810 elaboration in existing code often arise from library tasks, so
24811 we must address this particular situation.
24813 Note that if we compile and run the program above, using the dynamic model of
24814 elaboration (that is to say use the @option{-gnatE} switch),
24815 then it compiles, binds,
24816 links, and runs, printing the expected result of 2. Therefore in some sense
24817 the circularity here is only apparent, and we need to capture
24818 the properties of this program that distinguish it from other library-level
24819 tasks that have real elaboration problems.
24821 We have four possible answers to this question:
24826 Use the dynamic model of elaboration.
24828 If we use the @option{-gnatE} switch, then as noted above, the program works.
24829 Why is this? If we examine the task body, it is apparent that the task cannot
24831 @code{accept} statement until after elaboration has been completed, because
24832 the corresponding entry call comes from the main program, not earlier.
24833 This is why the dynamic model works here. But that's really giving
24834 up on a precise analysis, and we prefer to take this approach only if we cannot
24836 problem in any other manner. So let us examine two ways to reorganize
24837 the program to avoid the potential elaboration problem.
24840 Split library tasks into separate packages.
24842 Write separate packages, so that library tasks are isolated from
24843 other declarations as much as possible. Let us look at a variation on
24846 @smallexample @c ada
24854 package body Decls1 is
24855 task body Lib_Task is
24863 type My_Int is new Integer;
24864 function Ident (M : My_Int) return My_Int;
24868 package body Decls2 is
24869 function Ident (M : My_Int) return My_Int is
24877 procedure Put_Val (Arg : Decls2.My_Int);
24881 package body Utils is
24882 procedure Put_Val (Arg : Decls2.My_Int) is
24884 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24891 Decls1.Lib_Task.Start;
24896 All we have done is to split @code{Decls} into two packages, one
24897 containing the library task, and one containing everything else. Now
24898 there is no cycle, and the program compiles, binds, links and executes
24899 using the default static model of elaboration.
24902 Declare separate task types.
24904 A significant part of the problem arises because of the use of the
24905 single task declaration form. This means that the elaboration of
24906 the task type, and the elaboration of the task itself (i.e.@: the
24907 creation of the task) happen at the same time. A good rule
24908 of style in Ada is to always create explicit task types. By
24909 following the additional step of placing task objects in separate
24910 packages from the task type declaration, many elaboration problems
24911 are avoided. Here is another modified example of the example program:
24913 @smallexample @c ada
24915 task type Lib_Task_Type is
24919 type My_Int is new Integer;
24921 function Ident (M : My_Int) return My_Int;
24925 package body Decls is
24926 task body Lib_Task_Type is
24932 function Ident (M : My_Int) return My_Int is
24940 procedure Put_Val (Arg : Decls.My_Int);
24944 package body Utils is
24945 procedure Put_Val (Arg : Decls.My_Int) is
24947 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24953 Lib_Task : Decls.Lib_Task_Type;
24959 Declst.Lib_Task.Start;
24964 What we have done here is to replace the @code{task} declaration in
24965 package @code{Decls} with a @code{task type} declaration. Then we
24966 introduce a separate package @code{Declst} to contain the actual
24967 task object. This separates the elaboration issues for
24968 the @code{task type}
24969 declaration, which causes no trouble, from the elaboration issues
24970 of the task object, which is also unproblematic, since it is now independent
24971 of the elaboration of @code{Utils}.
24972 This separation of concerns also corresponds to
24973 a generally sound engineering principle of separating declarations
24974 from instances. This version of the program also compiles, binds, links,
24975 and executes, generating the expected output.
24978 Use No_Entry_Calls_In_Elaboration_Code restriction.
24979 @cindex No_Entry_Calls_In_Elaboration_Code
24981 The previous two approaches described how a program can be restructured
24982 to avoid the special problems caused by library task bodies. in practice,
24983 however, such restructuring may be difficult to apply to existing legacy code,
24984 so we must consider solutions that do not require massive rewriting.
24986 Let us consider more carefully why our original sample program works
24987 under the dynamic model of elaboration. The reason is that the code
24988 in the task body blocks immediately on the @code{accept}
24989 statement. Now of course there is nothing to prohibit elaboration
24990 code from making entry calls (for example from another library level task),
24991 so we cannot tell in isolation that
24992 the task will not execute the accept statement during elaboration.
24994 However, in practice it is very unusual to see elaboration code
24995 make any entry calls, and the pattern of tasks starting
24996 at elaboration time and then immediately blocking on @code{accept} or
24997 @code{select} statements is very common. What this means is that
24998 the compiler is being too pessimistic when it analyzes the
24999 whole package body as though it might be executed at elaboration
25002 If we know that the elaboration code contains no entry calls, (a very safe
25003 assumption most of the time, that could almost be made the default
25004 behavior), then we can compile all units of the program under control
25005 of the following configuration pragma:
25008 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
25012 This pragma can be placed in the @file{gnat.adc} file in the usual
25013 manner. If we take our original unmodified program and compile it
25014 in the presence of a @file{gnat.adc} containing the above pragma,
25015 then once again, we can compile, bind, link, and execute, obtaining
25016 the expected result. In the presence of this pragma, the compiler does
25017 not trace calls in a task body, that appear after the first @code{accept}
25018 or @code{select} statement, and therefore does not report a potential
25019 circularity in the original program.
25021 The compiler will check to the extent it can that the above
25022 restriction is not violated, but it is not always possible to do a
25023 complete check at compile time, so it is important to use this
25024 pragma only if the stated restriction is in fact met, that is to say
25025 no task receives an entry call before elaboration of all units is completed.
25029 @node Mixing Elaboration Models
25030 @section Mixing Elaboration Models
25032 So far, we have assumed that the entire program is either compiled
25033 using the dynamic model or static model, ensuring consistency. It
25034 is possible to mix the two models, but rules have to be followed
25035 if this mixing is done to ensure that elaboration checks are not
25038 The basic rule is that @emph{a unit compiled with the static model cannot
25039 be @code{with'ed} by a unit compiled with the dynamic model}. The
25040 reason for this is that in the static model, a unit assumes that
25041 its clients guarantee to use (the equivalent of) pragma
25042 @code{Elaborate_All} so that no elaboration checks are required
25043 in inner subprograms, and this assumption is violated if the
25044 client is compiled with dynamic checks.
25046 The precise rule is as follows. A unit that is compiled with dynamic
25047 checks can only @code{with} a unit that meets at least one of the
25048 following criteria:
25053 The @code{with'ed} unit is itself compiled with dynamic elaboration
25054 checks (that is with the @option{-gnatE} switch.
25057 The @code{with'ed} unit is an internal GNAT implementation unit from
25058 the System, Interfaces, Ada, or GNAT hierarchies.
25061 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25064 The @code{with'ing} unit (that is the client) has an explicit pragma
25065 @code{Elaborate_All} for the @code{with'ed} unit.
25070 If this rule is violated, that is if a unit with dynamic elaboration
25071 checks @code{with's} a unit that does not meet one of the above four
25072 criteria, then the binder (@code{gnatbind}) will issue a warning
25073 similar to that in the following example:
25076 warning: "x.ads" has dynamic elaboration checks and with's
25077 warning: "y.ads" which has static elaboration checks
25081 These warnings indicate that the rule has been violated, and that as a result
25082 elaboration checks may be missed in the resulting executable file.
25083 This warning may be suppressed using the @option{-ws} binder switch
25084 in the usual manner.
25086 One useful application of this mixing rule is in the case of a subsystem
25087 which does not itself @code{with} units from the remainder of the
25088 application. In this case, the entire subsystem can be compiled with
25089 dynamic checks to resolve a circularity in the subsystem, while
25090 allowing the main application that uses this subsystem to be compiled
25091 using the more reliable default static model.
25093 @node What to Do If the Default Elaboration Behavior Fails
25094 @section What to Do If the Default Elaboration Behavior Fails
25097 If the binder cannot find an acceptable order, it outputs detailed
25098 diagnostics. For example:
25104 error: elaboration circularity detected
25105 info: "proc (body)" must be elaborated before "pack (body)"
25106 info: reason: Elaborate_All probably needed in unit "pack (body)"
25107 info: recompile "pack (body)" with -gnatwl
25108 info: for full details
25109 info: "proc (body)"
25110 info: is needed by its spec:
25111 info: "proc (spec)"
25112 info: which is withed by:
25113 info: "pack (body)"
25114 info: "pack (body)" must be elaborated before "proc (body)"
25115 info: reason: pragma Elaborate in unit "proc (body)"
25121 In this case we have a cycle that the binder cannot break. On the one
25122 hand, there is an explicit pragma Elaborate in @code{proc} for
25123 @code{pack}. This means that the body of @code{pack} must be elaborated
25124 before the body of @code{proc}. On the other hand, there is elaboration
25125 code in @code{pack} that calls a subprogram in @code{proc}. This means
25126 that for maximum safety, there should really be a pragma
25127 Elaborate_All in @code{pack} for @code{proc} which would require that
25128 the body of @code{proc} be elaborated before the body of
25129 @code{pack}. Clearly both requirements cannot be satisfied.
25130 Faced with a circularity of this kind, you have three different options.
25133 @item Fix the program
25134 The most desirable option from the point of view of long-term maintenance
25135 is to rearrange the program so that the elaboration problems are avoided.
25136 One useful technique is to place the elaboration code into separate
25137 child packages. Another is to move some of the initialization code to
25138 explicitly called subprograms, where the program controls the order
25139 of initialization explicitly. Although this is the most desirable option,
25140 it may be impractical and involve too much modification, especially in
25141 the case of complex legacy code.
25143 @item Perform dynamic checks
25144 If the compilations are done using the
25146 (dynamic elaboration check) switch, then GNAT behaves in a quite different
25147 manner. Dynamic checks are generated for all calls that could possibly result
25148 in raising an exception. With this switch, the compiler does not generate
25149 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
25150 exactly as specified in the @cite{Ada Reference Manual}.
25151 The binder will generate
25152 an executable program that may or may not raise @code{Program_Error}, and then
25153 it is the programmer's job to ensure that it does not raise an exception. Note
25154 that it is important to compile all units with the switch, it cannot be used
25157 @item Suppress checks
25158 The drawback of dynamic checks is that they generate a
25159 significant overhead at run time, both in space and time. If you
25160 are absolutely sure that your program cannot raise any elaboration
25161 exceptions, and you still want to use the dynamic elaboration model,
25162 then you can use the configuration pragma
25163 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
25164 example this pragma could be placed in the @file{gnat.adc} file.
25166 @item Suppress checks selectively
25167 When you know that certain calls or instantiations in elaboration code cannot
25168 possibly lead to an elaboration error, and the binder nevertheless complains
25169 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
25170 elaboration circularities, it is possible to remove those warnings locally and
25171 obtain a program that will bind. Clearly this can be unsafe, and it is the
25172 responsibility of the programmer to make sure that the resulting program has no
25173 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
25174 used with different granularity to suppress warnings and break elaboration
25179 Place the pragma that names the called subprogram in the declarative part
25180 that contains the call.
25183 Place the pragma in the declarative part, without naming an entity. This
25184 disables warnings on all calls in the corresponding declarative region.
25187 Place the pragma in the package spec that declares the called subprogram,
25188 and name the subprogram. This disables warnings on all elaboration calls to
25192 Place the pragma in the package spec that declares the called subprogram,
25193 without naming any entity. This disables warnings on all elaboration calls to
25194 all subprograms declared in this spec.
25196 @item Use Pragma Elaborate
25197 As previously described in section @xref{Treatment of Pragma Elaborate},
25198 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
25199 that no elaboration checks are required on calls to the designated unit.
25200 There may be cases in which the caller knows that no transitive calls
25201 can occur, so that a @code{pragma Elaborate} will be sufficient in a
25202 case where @code{pragma Elaborate_All} would cause a circularity.
25206 These five cases are listed in order of decreasing safety, and therefore
25207 require increasing programmer care in their application. Consider the
25210 @smallexample @c adanocomment
25212 function F1 return Integer;
25217 function F2 return Integer;
25218 function Pure (x : integer) return integer;
25219 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
25220 -- pragma Suppress (Elaboration_Check); -- (4)
25224 package body Pack1 is
25225 function F1 return Integer is
25229 Val : integer := Pack2.Pure (11); -- Elab. call (1)
25232 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
25233 -- pragma Suppress(Elaboration_Check); -- (2)
25235 X1 := Pack2.F2 + 1; -- Elab. call (2)
25240 package body Pack2 is
25241 function F2 return Integer is
25245 function Pure (x : integer) return integer is
25247 return x ** 3 - 3 * x;
25251 with Pack1, Ada.Text_IO;
25254 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25257 In the absence of any pragmas, an attempt to bind this program produces
25258 the following diagnostics:
25264 error: elaboration circularity detected
25265 info: "pack1 (body)" must be elaborated before "pack1 (body)"
25266 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
25267 info: recompile "pack1 (body)" with -gnatwl for full details
25268 info: "pack1 (body)"
25269 info: must be elaborated along with its spec:
25270 info: "pack1 (spec)"
25271 info: which is withed by:
25272 info: "pack2 (body)"
25273 info: which must be elaborated along with its spec:
25274 info: "pack2 (spec)"
25275 info: which is withed by:
25276 info: "pack1 (body)"
25279 The sources of the circularity are the two calls to @code{Pack2.Pure} and
25280 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
25281 F2 is safe, even though F2 calls F1, because the call appears after the
25282 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
25283 remove the warning on the call. It is also possible to use pragma (2)
25284 because there are no other potentially unsafe calls in the block.
25287 The call to @code{Pure} is safe because this function does not depend on the
25288 state of @code{Pack2}. Therefore any call to this function is safe, and it
25289 is correct to place pragma (3) in the corresponding package spec.
25292 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
25293 warnings on all calls to functions declared therein. Note that this is not
25294 necessarily safe, and requires more detailed examination of the subprogram
25295 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
25296 be already elaborated.
25300 It is hard to generalize on which of these four approaches should be
25301 taken. Obviously if it is possible to fix the program so that the default
25302 treatment works, this is preferable, but this may not always be practical.
25303 It is certainly simple enough to use
25305 but the danger in this case is that, even if the GNAT binder
25306 finds a correct elaboration order, it may not always do so,
25307 and certainly a binder from another Ada compiler might not. A
25308 combination of testing and analysis (for which the warnings generated
25311 switch can be useful) must be used to ensure that the program is free
25312 of errors. One switch that is useful in this testing is the
25313 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
25316 Normally the binder tries to find an order that has the best chance
25317 of avoiding elaboration problems. However, if this switch is used, the binder
25318 plays a devil's advocate role, and tries to choose the order that
25319 has the best chance of failing. If your program works even with this
25320 switch, then it has a better chance of being error free, but this is still
25323 For an example of this approach in action, consider the C-tests (executable
25324 tests) from the ACVC suite. If these are compiled and run with the default
25325 treatment, then all but one of them succeed without generating any error
25326 diagnostics from the binder. However, there is one test that fails, and
25327 this is not surprising, because the whole point of this test is to ensure
25328 that the compiler can handle cases where it is impossible to determine
25329 a correct order statically, and it checks that an exception is indeed
25330 raised at run time.
25332 This one test must be compiled and run using the
25334 switch, and then it passes. Alternatively, the entire suite can
25335 be run using this switch. It is never wrong to run with the dynamic
25336 elaboration switch if your code is correct, and we assume that the
25337 C-tests are indeed correct (it is less efficient, but efficiency is
25338 not a factor in running the ACVC tests.)
25340 @node Elaboration for Dispatching Calls
25341 @section Elaboration for Dispatching Calls
25342 @cindex Dispatching calls
25345 In rare cases, the static elaboration model fails to prevent
25346 dispatching calls to not-yet-elaborated subprograms. In such cases, we
25347 fall back to run-time checks; premature calls to any primitive
25348 operation of a tagged type before the body of the operation has been
25349 elaborated will raise @code{Program_Error}.
25351 Access-to-subprogram types, however, are handled conservatively, and
25352 do not require run-time checks. This was not true in earlier versions
25353 of the compiler; you can use the @option{-gnatd.U} debug switch to
25354 revert to the old behavior if the new conservative behavior causes
25355 elaboration cycles.
25357 @node Summary of Procedures for Elaboration Control
25358 @section Summary of Procedures for Elaboration Control
25359 @cindex Elaboration control
25362 First, compile your program with the default options, using none of
25363 the special elaboration control switches. If the binder successfully
25364 binds your program, then you can be confident that, apart from issues
25365 raised by the use of access-to-subprogram types and dynamic dispatching,
25366 the program is free of elaboration errors. If it is important that the
25367 program be portable, then use the
25369 switch to generate warnings about missing @code{Elaborate} or
25370 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25372 If the program fails to bind using the default static elaboration
25373 handling, then you can fix the program to eliminate the binder
25374 message, or recompile the entire program with the
25375 @option{-gnatE} switch to generate dynamic elaboration checks,
25376 and, if you are sure there really are no elaboration problems,
25377 use a global pragma @code{Suppress (Elaboration_Check)}.
25379 @node Other Elaboration Order Considerations
25380 @section Other Elaboration Order Considerations
25382 This section has been entirely concerned with the issue of finding a valid
25383 elaboration order, as defined by the Ada Reference Manual. In a case
25384 where several elaboration orders are valid, the task is to find one
25385 of the possible valid elaboration orders (and the static model in GNAT
25386 will ensure that this is achieved).
25388 The purpose of the elaboration rules in the Ada Reference Manual is to
25389 make sure that no entity is accessed before it has been elaborated. For
25390 a subprogram, this means that the spec and body must have been elaborated
25391 before the subprogram is called. For an object, this means that the object
25392 must have been elaborated before its value is read or written. A violation
25393 of either of these two requirements is an access before elaboration order,
25394 and this section has been all about avoiding such errors.
25396 In the case where more than one order of elaboration is possible, in the
25397 sense that access before elaboration errors are avoided, then any one of
25398 the orders is ``correct'' in the sense that it meets the requirements of
25399 the Ada Reference Manual, and no such error occurs.
25401 However, it may be the case for a given program, that there are
25402 constraints on the order of elaboration that come not from consideration
25403 of avoiding elaboration errors, but rather from extra-lingual logic
25404 requirements. Consider this example:
25406 @smallexample @c ada
25407 with Init_Constants;
25408 package Constants is
25413 package Init_Constants is
25414 procedure P; -- require a body
25415 end Init_Constants;
25418 package body Init_Constants is
25419 procedure P is begin null; end;
25423 end Init_Constants;
25427 Z : Integer := Constants.X + Constants.Y;
25431 with Text_IO; use Text_IO;
25434 Put_Line (Calc.Z'Img);
25439 In this example, there is more than one valid order of elaboration. For
25440 example both the following are correct orders:
25443 Init_Constants spec
25446 Init_Constants body
25451 Init_Constants spec
25452 Init_Constants body
25459 There is no language rule to prefer one or the other, both are correct
25460 from an order of elaboration point of view. But the programmatic effects
25461 of the two orders are very different. In the first, the elaboration routine
25462 of @code{Calc} initializes @code{Z} to zero, and then the main program
25463 runs with this value of zero. But in the second order, the elaboration
25464 routine of @code{Calc} runs after the body of Init_Constants has set
25465 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25468 One could perhaps by applying pretty clever non-artificial intelligence
25469 to the situation guess that it is more likely that the second order of
25470 elaboration is the one desired, but there is no formal linguistic reason
25471 to prefer one over the other. In fact in this particular case, GNAT will
25472 prefer the second order, because of the rule that bodies are elaborated
25473 as soon as possible, but it's just luck that this is what was wanted
25474 (if indeed the second order was preferred).
25476 If the program cares about the order of elaboration routines in a case like
25477 this, it is important to specify the order required. In this particular
25478 case, that could have been achieved by adding to the spec of Calc:
25480 @smallexample @c ada
25481 pragma Elaborate_All (Constants);
25485 which requires that the body (if any) and spec of @code{Constants},
25486 as well as the body and spec of any unit @code{with}'ed by
25487 @code{Constants} be elaborated before @code{Calc} is elaborated.
25489 Clearly no automatic method can always guess which alternative you require,
25490 and if you are working with legacy code that had constraints of this kind
25491 which were not properly specified by adding @code{Elaborate} or
25492 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25493 compilers can choose different orders.
25495 However, GNAT does attempt to diagnose the common situation where there
25496 are uninitialized variables in the visible part of a package spec, and the
25497 corresponding package body has an elaboration block that directly or
25498 indirectly initialized one or more of these variables. This is the situation
25499 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25500 a warning that suggests this addition if it detects this situation.
25502 The @code{gnatbind}
25503 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25504 out problems. This switch causes bodies to be elaborated as late as possible
25505 instead of as early as possible. In the example above, it would have forced
25506 the choice of the first elaboration order. If you get different results
25507 when using this switch, and particularly if one set of results is right,
25508 and one is wrong as far as you are concerned, it shows that you have some
25509 missing @code{Elaborate} pragmas. For the example above, we have the
25513 gnatmake -f -q main
25516 gnatmake -f -q main -bargs -p
25522 It is of course quite unlikely that both these results are correct, so
25523 it is up to you in a case like this to investigate the source of the
25524 difference, by looking at the two elaboration orders that are chosen,
25525 and figuring out which is correct, and then adding the necessary
25526 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25529 @c **********************************
25530 @node Overflow Check Handling in GNAT
25531 @appendix Overflow Check Handling in GNAT
25532 @cindex Overflow checks
25533 @cindex Checks (overflow)
25534 @c **********************************
25538 * Overflow Checking Modes in GNAT::
25539 * Specifying the Desired Mode::
25540 * Default Settings::
25541 * Implementation Notes::
25546 @section Background
25549 Overflow checks are checks that the compiler may make to ensure
25550 that intermediate results are not out of range. For example:
25552 @smallexample @c ada
25559 if @code{A} has the value @code{Integer'Last}, then the addition may cause
25560 overflow since the result is out of range of the type @code{Integer}.
25561 In this case @code{Constraint_Error} will be raised if checks are
25564 A trickier situation arises in examples like the following:
25566 @smallexample @c ada
25573 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
25574 Now the final result of the expression on the right hand side is
25575 @code{Integer'Last} which is in range, but the question arises whether the
25576 intermediate addition of @code{(A + 1)} raises an overflow error.
25578 The (perhaps surprising) answer is that the Ada language
25579 definition does not answer this question. Instead it leaves
25580 it up to the implementation to do one of two things:
25584 raise an exception (@code{Constraint_Error}), or
25587 yield the correct mathematical result which is then used in
25588 subsequent operations.
25592 If the compiler chooses the first approach, then the assignment of this
25593 example will indeed raise @code{Constraint_Error}. But if the compiler
25594 chooses the second approach, then it can perform both additions yielding
25595 the correct mathematical result, which is in range, so no exception
25598 Note that in the first example an
25599 exception will be raised in either case, since if the compiler
25600 gives the correct mathematical result for the addition, it will
25601 be out of range of the target type of the assignment, and thus
25602 fails the range check.
25604 This lack of specified behavior in the handling of overflow for
25605 intermediate results is a source of non-portability, and can thus
25606 be problematic when programs are ported. Most typically this arises
25607 in a situation where the original compiler did not raise an exception,
25608 and then the application is moved to a compiler where the check is
25609 performed on the intermediate result and an unexpected exception is
25612 Furthermore, when using Ada 2012's preconditions and other
25613 assertion forms, another issue arises. Consider:
25615 @smallexample @c ada
25616 procedure P (A, B : Integer) with
25617 Pre => A + B <= Integer'Last;
25621 One often wants to regard arithmetic in a context like this from
25622 a mathematical point of view. So for example, if the two actual parameters
25623 for a call to @code{P} are both @code{Integer'Last}, then
25624 the precondition should be regarded as False. If we are executing
25625 in a mode with run-time checks enabled for preconditions, then we would
25626 like this precondition to fail, rather than raising an exception
25627 because of the intermediate overflow.
25629 However, the language definition leaves the specification of
25630 whether the above condition fails (raising @code{Assert_Error}) or
25631 causes an intermediate overflow (raising @code{Constraint_Error})
25632 up to the implementation.
25634 The situation is worse in a case such as the following:
25636 @smallexample @c ada
25637 procedure Q (A, B, C : Integer) with
25638 Pre => A + B + C <= Integer'Last;
25644 @smallexample @c ada
25645 Q (A => Integer'Last, B => 1, C => -1);
25649 From a mathematical point of view the precondition
25650 is True, but at run time we may (but are not guaranteed to) get an
25651 exception raised because of the intermediate overflow (and we really
25652 would prefer this precondition to be considered True at run time).
25654 @node Overflow Checking Modes in GNAT
25655 @section Overflow Checking Modes in GNAT
25658 To deal with the portability issue, and with the problem of
25659 mathematical versus run-time intepretation of the expressions in
25660 assertions, GNAT provides comprehensive control over the handling
25661 of intermediate overflow. GNAT can operate in four modes, and
25662 furthemore, permits separate selection of operating modes for
25663 the expressions within assertions (here the term ``assertions''
25664 is used in the technical sense, which includes preconditions and so forth)
25665 and for expressions appearing outside assertions.
25667 The four modes are:
25670 @item @i{Checks suppressed} (@code{SUPPRESSED})
25672 This is the normal defined language mode, as specified by a pragma
25673 @code{Suppress (Overflow_Check)}. If any intermediate overflow occurs,
25674 then the program execution is erroneous, which means that anything
25675 could happen. Note in particular, that the result of evaluating
25676 a precondition may be plain wrong if there is an intermediate
25677 overflow, as in our examples above.
25679 @item @i{All intermediate overflows checked} (@code{CHECKED})
25681 In this mode, all intermediate results for predefined arithmetic
25682 operators must be in range of the base type. If this is not the
25683 case a constraint error is raised. This is the normal default mode
25684 specified by use of the pragma @code{Unsuppress (Overflow_Check)}.
25686 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
25688 In this mode, the compiler attempts to avoid intermediate overflows by
25689 using @code{Long_Long_Integer} as the type in which arithmetic is
25690 performed for predefined arithmetic operators. This is slightly more
25692 run time (compared to suppressing intermediate overflow checks), though
25693 the cost is minimal on modern 64-bit machines. For the examples given
25694 earlier, no intermediate overflows would have resulted in exceptions,
25695 since the intermediate results are all in the range of
25696 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
25699 However, there are cases where @code{Long_Long_Integer} is not large
25700 enough, consider the following example:
25702 @smallexample @c ada
25703 procedure R (A, B, C, D : Integer) with
25704 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
25707 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25708 Now the intermediate results are
25709 out of the range of @code{Long_Long_Integer} even though the final result
25710 is in range and the precondition is True (from a mathematical point
25711 of view). In such a case, operating in this mode, an exception will
25712 be raised for the intermediate overflow (which is why this mode
25713 says @i{most} intermediate overflows are avoided).
25715 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
25717 In this mode, the compiler avoids all intermediate overflows
25718 by using arbitrary precision arithmetic as required. In this
25719 mode, the above example with @code{A**2 * B**2} would
25720 not cause intermediate overflow, because the intermediate result
25721 would be evaluated using sufficient precision, and the result
25722 of evaluating the precondition would be True.
25724 This mode has the advantage of avoiding any intermediate
25725 overflows, but at the expense of significant run-time overhead,
25726 including the use of a library (included automatically in this
25727 mode) for multiple-precision arithmetic.
25729 This mode provides cleaner semantics for assertions, since now
25730 the run-time behavior emulates true arithmetic behavior for the
25731 predefined arithmetic operators, meaning that there is never a
25732 conflict between the mathematical view of the assertion, and its
25737 Note that these modes apply only to the evaluation of predefined
25738 arithmetic, membership, and comparison operators for signed integer
25741 For fixed-point arithmetic, checks can be suppressed. But if checks
25742 are enabled (any of the three non-suppress modes will enable checks),
25743 then fixed-point values are always checked for overflow against the
25744 base type for intermediate expressions.
25746 For floating-point, on nearly all architectures, @code{Machine_Overflows}
25747 is False, and IEEE infinities are generated, so overflow exceptions
25748 are never raised. If you want to avoid infinities, and check that
25749 final results of expressions are in range, then you can declare a
25750 constrained floating-point type, and range checks will be carried
25751 out in the normal manner (with infinite values always failing all
25755 @c -------------------------
25756 @node Specifying the Desired Mode
25757 @section Specifying the Desired Mode
25760 The desired mode of overflow checking can be specified using
25761 either the @code{Overflow_Checks} pragma or an equivalent compiler switch.
25762 The pragma has the form
25763 @cindex pragma @code{Overflow_Checks}
25765 @smallexample @c ada
25766 pragma Overflow_Checks ([General =>] MODE [, [Assertions =>] MODE]);
25770 where @code{MODE} is one of
25773 @item @code{SUPPRESSED}: suppress overflow checks
25774 @item @code{CHECKED}: all intermediate overflows checked
25775 @item @code{MINIMIZED}: minimize intermediate overflows
25776 @item @code{ELIMINATED}: eliminate intermediate overflows
25780 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25781 @code{minimized} all have the same effect.
25783 If only the @code{General} parameter is present, then the given @code{MODE}
25785 to expressions both within and outside assertions. If both arguments
25786 are present, then @code{General} applies to expressions outside assertions,
25787 and @code{Assertions} applies to expressions within assertions. For example:
25789 @smallexample @c ada
25790 pragma Overflow_Checks
25791 (General => Minimized, Assertions => Eliminated);
25795 specifies that general expressions outside assertions be evaluated
25796 in ``minimize intermediate overflows'' mode, and expressions within
25797 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25798 This is often a reasonable choice, avoiding excessive overhead
25799 outside assertions, but assuring a high degree of portability
25800 when importing code from another compiler, while incurring
25801 the extra overhead for assertion expressions to ensure that
25802 the behavior at run time matches the expected mathematical
25805 The @code{Overflow_Checks} pragma has the same scoping and placement
25806 rules as pragma @code{Suppress}, so it can occur either as a
25807 configuration pragma, specifying a default for the whole
25808 program, or in a declarative scope, where it applies to the
25809 remaining declarations and statements in that scope.
25811 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25812 can be used to control the checking mode default (which can be subsequently
25813 overridden using the pragma form).
25814 @cindex @option{-gnato?} (gcc)
25815 @cindex @option{-gnato??} (gcc)
25817 Here `@code{?}' is one of the digits `@code{0}' through `@code{3}':
25821 suppress overflow checks (@code{SUPPRESSED})
25823 all intermediate overflows checked (@code{CHECKED})
25825 minimize intermediate overflows (@code{MINIMIZED})
25827 eliminate intermediate overflows (@code{ELIMINATED})
25831 As with the pragma, if only one digit appears then it applies to all
25832 cases; if two digits are given, then the first applies outside
25833 assertions, and the second within assertions. Thus the equivalent
25834 of the example pragma above would be @option{-gnato23}.
25836 If no digits follow the @option{-gnato}, then it is equivalent to
25838 causing all intermediate overflows to be checked.
25841 @c -------------------------
25842 @node Default Settings
25843 @section Default Settings
25845 The default mode for overflow checks is
25848 General => Suppressed
25852 which suppresses checks inside and outside assertions,
25853 This retains compatibility with previous versions of
25854 GNAT which suppressed overflow checks by default.
25856 The switch @option{-gnato} (with no digits following) is equivalent to
25857 @cindex @option{-gnato} (gcc)
25864 which causes overflow checking of all intermediate overflows
25865 both inside and outside assertions. This provides compatibility
25866 with this switch as implemented in previous versions of GNAT.
25868 The pragma @code{Suppress (Overflow_Check)} sets mode
25871 General => Suppressed
25875 suppressing all overflow checking within and outside
25877 @cindex @code{Overflow_Check} (argument to pragma Suppress)
25879 The pragam @code{Unsuppress (Overflow_Check)} sets mode
25886 which causes overflow checking of all intermediate overflows.
25887 This applies both inside and outside assertions.
25888 @cindex @code{Overflow_Check} (argument to pragma Unsuppress)
25891 @c -------------------------
25892 @node Implementation Notes
25893 @section Implementation Notes
25895 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
25896 reasonably efficient, and can be generally used. It also helps
25897 to ensure compatibility with code imported from some other
25900 Setting all intermediate overflows checking (@code{CHECKED} mode)
25901 makes sense if you want to
25902 make sure that your code is compatible with any other possible
25903 Ada implementation. This may be useful in ensuring portability
25904 for code that is to be exported to some other compiler than GNAT.
25905 It is also appropriate if you intend to turn off checks for
25906 the final delivered software, since in @code{SUPPRESSED} mode, the
25907 assumption is that all intermediate results are in range. In
25908 this situation, it is likely that you are also suppressing
25909 assertions in the final executable, so in that case it does not
25910 matter which mode is selected for assertions during development.
25912 The Ada standard allows the reassociation of expressions at
25913 the same precedence level if no parentheses are present. For
25914 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
25915 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
25916 introducing or eliminating an overflow exception. The GNAT
25917 compiler never takes advantage of this freedom, and the
25918 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
25919 If you need the other order, you can write the parentheses
25920 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
25922 The use of @code{ELIMINATED} mode will cause the compiler to
25923 automatically include an appropriate arbitrary precision
25924 integer arithmetic package. The compiler will make calls
25925 to this package, though only in cases where it cannot be
25926 sure that @code{Long_Long_Integer} is sufficient to guard against
25927 intermediate overflows. This package does not use dynamic
25928 alllocation, but it does use the secondary stack, so an
25929 appropriate secondary stack package must be present (this
25930 is always true for standard full Ada, but may require
25931 specific steps for restricted run times such as ZFP).
25933 Although @code{ELIMINATED} mode causes expressions to use arbitrary
25934 precision arithmetic, avoiding overflow, the final result
25935 must be in an appropriate range. This is true even if the
25936 final result is of type @code{[Long_[Long_]]Integer'Base}, which
25937 still has the same bounds as its associated constrained
25940 Currently, the @code{ELIMINATED} mode is only available on target
25941 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
25944 @c *******************************
25945 @node Conditional Compilation
25946 @appendix Conditional Compilation
25947 @c *******************************
25948 @cindex Conditional compilation
25951 It is often necessary to arrange for a single source program
25952 to serve multiple purposes, where it is compiled in different
25953 ways to achieve these different goals. Some examples of the
25954 need for this feature are
25957 @item Adapting a program to a different hardware environment
25958 @item Adapting a program to a different target architecture
25959 @item Turning debugging features on and off
25960 @item Arranging for a program to compile with different compilers
25964 In C, or C++, the typical approach would be to use the preprocessor
25965 that is defined as part of the language. The Ada language does not
25966 contain such a feature. This is not an oversight, but rather a very
25967 deliberate design decision, based on the experience that overuse of
25968 the preprocessing features in C and C++ can result in programs that
25969 are extremely difficult to maintain. For example, if we have ten
25970 switches that can be on or off, this means that there are a thousand
25971 separate programs, any one of which might not even be syntactically
25972 correct, and even if syntactically correct, the resulting program
25973 might not work correctly. Testing all combinations can quickly become
25976 Nevertheless, the need to tailor programs certainly exists, and in
25977 this Appendix we will discuss how this can
25978 be achieved using Ada in general, and GNAT in particular.
25981 * Use of Boolean Constants::
25982 * Debugging - A Special Case::
25983 * Conditionalizing Declarations::
25984 * Use of Alternative Implementations::
25988 @node Use of Boolean Constants
25989 @section Use of Boolean Constants
25992 In the case where the difference is simply which code
25993 sequence is executed, the cleanest solution is to use Boolean
25994 constants to control which code is executed.
25996 @smallexample @c ada
25998 FP_Initialize_Required : constant Boolean := True;
26000 if FP_Initialize_Required then
26007 Not only will the code inside the @code{if} statement not be executed if
26008 the constant Boolean is @code{False}, but it will also be completely
26009 deleted from the program.
26010 However, the code is only deleted after the @code{if} statement
26011 has been checked for syntactic and semantic correctness.
26012 (In contrast, with preprocessors the code is deleted before the
26013 compiler ever gets to see it, so it is not checked until the switch
26015 @cindex Preprocessors (contrasted with conditional compilation)
26017 Typically the Boolean constants will be in a separate package,
26020 @smallexample @c ada
26023 FP_Initialize_Required : constant Boolean := True;
26024 Reset_Available : constant Boolean := False;
26031 The @code{Config} package exists in multiple forms for the various targets,
26032 with an appropriate script selecting the version of @code{Config} needed.
26033 Then any other unit requiring conditional compilation can do a @code{with}
26034 of @code{Config} to make the constants visible.
26037 @node Debugging - A Special Case
26038 @section Debugging - A Special Case
26041 A common use of conditional code is to execute statements (for example
26042 dynamic checks, or output of intermediate results) under control of a
26043 debug switch, so that the debugging behavior can be turned on and off.
26044 This can be done using a Boolean constant to control whether the code
26047 @smallexample @c ada
26050 Put_Line ("got to the first stage!");
26058 @smallexample @c ada
26060 if Debugging and then Temperature > 999.0 then
26061 raise Temperature_Crazy;
26067 Since this is a common case, there are special features to deal with
26068 this in a convenient manner. For the case of tests, Ada 2005 has added
26069 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
26070 @cindex pragma @code{Assert}
26071 on the @code{Assert} pragma that has always been available in GNAT, so this
26072 feature may be used with GNAT even if you are not using Ada 2005 features.
26073 The use of pragma @code{Assert} is described in
26074 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
26075 example, the last test could be written:
26077 @smallexample @c ada
26078 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
26084 @smallexample @c ada
26085 pragma Assert (Temperature <= 999.0);
26089 In both cases, if assertions are active and the temperature is excessive,
26090 the exception @code{Assert_Failure} will be raised, with the given string in
26091 the first case or a string indicating the location of the pragma in the second
26092 case used as the exception message.
26094 You can turn assertions on and off by using the @code{Assertion_Policy}
26096 @cindex pragma @code{Assertion_Policy}
26097 This is an Ada 2005 pragma which is implemented in all modes by
26098 GNAT, but only in the latest versions of GNAT which include Ada 2005
26099 capability. Alternatively, you can use the @option{-gnata} switch
26100 @cindex @option{-gnata} switch
26101 to enable assertions from the command line (this is recognized by all versions
26104 For the example above with the @code{Put_Line}, the GNAT-specific pragma
26105 @code{Debug} can be used:
26106 @cindex pragma @code{Debug}
26108 @smallexample @c ada
26109 pragma Debug (Put_Line ("got to the first stage!"));
26113 If debug pragmas are enabled, the argument, which must be of the form of
26114 a procedure call, is executed (in this case, @code{Put_Line} will be called).
26115 Only one call can be present, but of course a special debugging procedure
26116 containing any code you like can be included in the program and then
26117 called in a pragma @code{Debug} argument as needed.
26119 One advantage of pragma @code{Debug} over the @code{if Debugging then}
26120 construct is that pragma @code{Debug} can appear in declarative contexts,
26121 such as at the very beginning of a procedure, before local declarations have
26124 Debug pragmas are enabled using either the @option{-gnata} switch that also
26125 controls assertions, or with a separate Debug_Policy pragma.
26126 @cindex pragma @code{Debug_Policy}
26127 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
26128 in Ada 95 and Ada 83 programs as well), and is analogous to
26129 pragma @code{Assertion_Policy} to control assertions.
26131 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
26132 and thus they can appear in @file{gnat.adc} if you are not using a
26133 project file, or in the file designated to contain configuration pragmas
26135 They then apply to all subsequent compilations. In practice the use of
26136 the @option{-gnata} switch is often the most convenient method of controlling
26137 the status of these pragmas.
26139 Note that a pragma is not a statement, so in contexts where a statement
26140 sequence is required, you can't just write a pragma on its own. You have
26141 to add a @code{null} statement.
26143 @smallexample @c ada
26146 @dots{} -- some statements
26148 pragma Assert (Num_Cases < 10);
26155 @node Conditionalizing Declarations
26156 @section Conditionalizing Declarations
26159 In some cases, it may be necessary to conditionalize declarations to meet
26160 different requirements. For example we might want a bit string whose length
26161 is set to meet some hardware message requirement.
26163 In some cases, it may be possible to do this using declare blocks controlled
26164 by conditional constants:
26166 @smallexample @c ada
26168 if Small_Machine then
26170 X : Bit_String (1 .. 10);
26176 X : Large_Bit_String (1 .. 1000);
26185 Note that in this approach, both declarations are analyzed by the
26186 compiler so this can only be used where both declarations are legal,
26187 even though one of them will not be used.
26189 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
26190 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
26191 that are parameterized by these constants. For example
26193 @smallexample @c ada
26196 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
26202 If @code{Bits_Per_Word} is set to 32, this generates either
26204 @smallexample @c ada
26207 Field1 at 0 range 0 .. 32;
26213 for the big endian case, or
26215 @smallexample @c ada
26218 Field1 at 0 range 10 .. 32;
26224 for the little endian case. Since a powerful subset of Ada expression
26225 notation is usable for creating static constants, clever use of this
26226 feature can often solve quite difficult problems in conditionalizing
26227 compilation (note incidentally that in Ada 95, the little endian
26228 constant was introduced as @code{System.Default_Bit_Order}, so you do not
26229 need to define this one yourself).
26232 @node Use of Alternative Implementations
26233 @section Use of Alternative Implementations
26236 In some cases, none of the approaches described above are adequate. This
26237 can occur for example if the set of declarations required is radically
26238 different for two different configurations.
26240 In this situation, the official Ada way of dealing with conditionalizing
26241 such code is to write separate units for the different cases. As long as
26242 this does not result in excessive duplication of code, this can be done
26243 without creating maintenance problems. The approach is to share common
26244 code as far as possible, and then isolate the code and declarations
26245 that are different. Subunits are often a convenient method for breaking
26246 out a piece of a unit that is to be conditionalized, with separate files
26247 for different versions of the subunit for different targets, where the
26248 build script selects the right one to give to the compiler.
26249 @cindex Subunits (and conditional compilation)
26251 As an example, consider a situation where a new feature in Ada 2005
26252 allows something to be done in a really nice way. But your code must be able
26253 to compile with an Ada 95 compiler. Conceptually you want to say:
26255 @smallexample @c ada
26258 @dots{} neat Ada 2005 code
26260 @dots{} not quite as neat Ada 95 code
26266 where @code{Ada_2005} is a Boolean constant.
26268 But this won't work when @code{Ada_2005} is set to @code{False},
26269 since the @code{then} clause will be illegal for an Ada 95 compiler.
26270 (Recall that although such unreachable code would eventually be deleted
26271 by the compiler, it still needs to be legal. If it uses features
26272 introduced in Ada 2005, it will be illegal in Ada 95.)
26274 So instead we write
26276 @smallexample @c ada
26277 procedure Insert is separate;
26281 Then we have two files for the subunit @code{Insert}, with the two sets of
26283 If the package containing this is called @code{File_Queries}, then we might
26287 @item @file{file_queries-insert-2005.adb}
26288 @item @file{file_queries-insert-95.adb}
26292 and the build script renames the appropriate file to
26295 file_queries-insert.adb
26299 and then carries out the compilation.
26301 This can also be done with project files' naming schemes. For example:
26303 @smallexample @c project
26304 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
26308 Note also that with project files it is desirable to use a different extension
26309 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
26310 conflict may arise through another commonly used feature: to declare as part
26311 of the project a set of directories containing all the sources obeying the
26312 default naming scheme.
26314 The use of alternative units is certainly feasible in all situations,
26315 and for example the Ada part of the GNAT run-time is conditionalized
26316 based on the target architecture using this approach. As a specific example,
26317 consider the implementation of the AST feature in VMS. There is one
26325 which is the same for all architectures, and three bodies:
26329 used for all non-VMS operating systems
26330 @item s-asthan-vms-alpha.adb
26331 used for VMS on the Alpha
26332 @item s-asthan-vms-ia64.adb
26333 used for VMS on the ia64
26337 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
26338 this operating system feature is not available, and the two remaining
26339 versions interface with the corresponding versions of VMS to provide
26340 VMS-compatible AST handling. The GNAT build script knows the architecture
26341 and operating system, and automatically selects the right version,
26342 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
26344 Another style for arranging alternative implementations is through Ada's
26345 access-to-subprogram facility.
26346 In case some functionality is to be conditionally included,
26347 you can declare an access-to-procedure variable @code{Ref} that is initialized
26348 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
26350 In some library package, set @code{Ref} to @code{Proc'Access} for some
26351 procedure @code{Proc} that performs the relevant processing.
26352 The initialization only occurs if the library package is included in the
26354 The same idea can also be implemented using tagged types and dispatching
26358 @node Preprocessing
26359 @section Preprocessing
26360 @cindex Preprocessing
26363 Although it is quite possible to conditionalize code without the use of
26364 C-style preprocessing, as described earlier in this section, it is
26365 nevertheless convenient in some cases to use the C approach. Moreover,
26366 older Ada compilers have often provided some preprocessing capability,
26367 so legacy code may depend on this approach, even though it is not
26370 To accommodate such use, GNAT provides a preprocessor (modeled to a large
26371 extent on the various preprocessors that have been used
26372 with legacy code on other compilers, to enable easier transition).
26374 The preprocessor may be used in two separate modes. It can be used quite
26375 separately from the compiler, to generate a separate output source file
26376 that is then fed to the compiler as a separate step. This is the
26377 @code{gnatprep} utility, whose use is fully described in
26378 @ref{Preprocessing Using gnatprep}.
26379 @cindex @code{gnatprep}
26381 The preprocessing language allows such constructs as
26385 #if DEBUG or PRIORITY > 4 then
26386 bunch of declarations
26388 completely different bunch of declarations
26394 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
26395 defined either on the command line or in a separate file.
26397 The other way of running the preprocessor is even closer to the C style and
26398 often more convenient. In this approach the preprocessing is integrated into
26399 the compilation process. The compiler is fed the preprocessor input which
26400 includes @code{#if} lines etc, and then the compiler carries out the
26401 preprocessing internally and processes the resulting output.
26402 For more details on this approach, see @ref{Integrated Preprocessing}.
26405 @c *******************************
26406 @node Inline Assembler
26407 @appendix Inline Assembler
26408 @c *******************************
26411 If you need to write low-level software that interacts directly
26412 with the hardware, Ada provides two ways to incorporate assembly
26413 language code into your program. First, you can import and invoke
26414 external routines written in assembly language, an Ada feature fully
26415 supported by GNAT@. However, for small sections of code it may be simpler
26416 or more efficient to include assembly language statements directly
26417 in your Ada source program, using the facilities of the implementation-defined
26418 package @code{System.Machine_Code}, which incorporates the gcc
26419 Inline Assembler. The Inline Assembler approach offers a number of advantages,
26420 including the following:
26423 @item No need to use non-Ada tools
26424 @item Consistent interface over different targets
26425 @item Automatic usage of the proper calling conventions
26426 @item Access to Ada constants and variables
26427 @item Definition of intrinsic routines
26428 @item Possibility of inlining a subprogram comprising assembler code
26429 @item Code optimizer can take Inline Assembler code into account
26432 This chapter presents a series of examples to show you how to use
26433 the Inline Assembler. Although it focuses on the Intel x86,
26434 the general approach applies also to other processors.
26435 It is assumed that you are familiar with Ada
26436 and with assembly language programming.
26439 * Basic Assembler Syntax::
26440 * A Simple Example of Inline Assembler::
26441 * Output Variables in Inline Assembler::
26442 * Input Variables in Inline Assembler::
26443 * Inlining Inline Assembler Code::
26444 * Other Asm Functionality::
26447 @c ---------------------------------------------------------------------------
26448 @node Basic Assembler Syntax
26449 @section Basic Assembler Syntax
26452 The assembler used by GNAT and gcc is based not on the Intel assembly
26453 language, but rather on a language that descends from the AT&T Unix
26454 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
26455 The following table summarizes the main features of @emph{as} syntax
26456 and points out the differences from the Intel conventions.
26457 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
26458 pre-processor) documentation for further information.
26461 @item Register names
26462 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
26464 Intel: No extra punctuation; for example @code{eax}
26466 @item Immediate operand
26467 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
26469 Intel: No extra punctuation; for example @code{4}
26472 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
26474 Intel: No extra punctuation; for example @code{loc}
26476 @item Memory contents
26477 gcc / @emph{as}: No extra punctuation; for example @code{loc}
26479 Intel: Square brackets; for example @code{[loc]}
26481 @item Register contents
26482 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
26484 Intel: Square brackets; for example @code{[eax]}
26486 @item Hexadecimal numbers
26487 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
26489 Intel: Trailing ``h''; for example @code{A0h}
26492 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
26495 Intel: Implicit, deduced by assembler; for example @code{mov}
26497 @item Instruction repetition
26498 gcc / @emph{as}: Split into two lines; for example
26504 Intel: Keep on one line; for example @code{rep stosl}
26506 @item Order of operands
26507 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
26509 Intel: Destination first; for example @code{mov eax, 4}
26512 @c ---------------------------------------------------------------------------
26513 @node A Simple Example of Inline Assembler
26514 @section A Simple Example of Inline Assembler
26517 The following example will generate a single assembly language statement,
26518 @code{nop}, which does nothing. Despite its lack of run-time effect,
26519 the example will be useful in illustrating the basics of
26520 the Inline Assembler facility.
26522 @smallexample @c ada
26524 with System.Machine_Code; use System.Machine_Code;
26525 procedure Nothing is
26532 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
26533 here it takes one parameter, a @emph{template string} that must be a static
26534 expression and that will form the generated instruction.
26535 @code{Asm} may be regarded as a compile-time procedure that parses
26536 the template string and additional parameters (none here),
26537 from which it generates a sequence of assembly language instructions.
26539 The examples in this chapter will illustrate several of the forms
26540 for invoking @code{Asm}; a complete specification of the syntax
26541 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
26544 Under the standard GNAT conventions, the @code{Nothing} procedure
26545 should be in a file named @file{nothing.adb}.
26546 You can build the executable in the usual way:
26550 However, the interesting aspect of this example is not its run-time behavior
26551 but rather the generated assembly code.
26552 To see this output, invoke the compiler as follows:
26554 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
26556 where the options are:
26560 compile only (no bind or link)
26562 generate assembler listing
26563 @item -fomit-frame-pointer
26564 do not set up separate stack frames
26566 do not add runtime checks
26569 This gives a human-readable assembler version of the code. The resulting
26570 file will have the same name as the Ada source file, but with a @code{.s}
26571 extension. In our example, the file @file{nothing.s} has the following
26576 .file "nothing.adb"
26578 ___gnu_compiled_ada:
26581 .globl __ada_nothing
26593 The assembly code you included is clearly indicated by
26594 the compiler, between the @code{#APP} and @code{#NO_APP}
26595 delimiters. The character before the 'APP' and 'NOAPP'
26596 can differ on different targets. For example, GNU/Linux uses '#APP' while
26597 on NT you will see '/APP'.
26599 If you make a mistake in your assembler code (such as using the
26600 wrong size modifier, or using a wrong operand for the instruction) GNAT
26601 will report this error in a temporary file, which will be deleted when
26602 the compilation is finished. Generating an assembler file will help
26603 in such cases, since you can assemble this file separately using the
26604 @emph{as} assembler that comes with gcc.
26606 Assembling the file using the command
26609 as @file{nothing.s}
26612 will give you error messages whose lines correspond to the assembler
26613 input file, so you can easily find and correct any mistakes you made.
26614 If there are no errors, @emph{as} will generate an object file
26615 @file{nothing.out}.
26617 @c ---------------------------------------------------------------------------
26618 @node Output Variables in Inline Assembler
26619 @section Output Variables in Inline Assembler
26622 The examples in this section, showing how to access the processor flags,
26623 illustrate how to specify the destination operands for assembly language
26626 @smallexample @c ada
26628 with Interfaces; use Interfaces;
26629 with Ada.Text_IO; use Ada.Text_IO;
26630 with System.Machine_Code; use System.Machine_Code;
26631 procedure Get_Flags is
26632 Flags : Unsigned_32;
26635 Asm ("pushfl" & LF & HT & -- push flags on stack
26636 "popl %%eax" & LF & HT & -- load eax with flags
26637 "movl %%eax, %0", -- store flags in variable
26638 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26639 Put_Line ("Flags register:" & Flags'Img);
26644 In order to have a nicely aligned assembly listing, we have separated
26645 multiple assembler statements in the Asm template string with linefeed
26646 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
26647 The resulting section of the assembly output file is:
26654 movl %eax, -40(%ebp)
26659 It would have been legal to write the Asm invocation as:
26662 Asm ("pushfl popl %%eax movl %%eax, %0")
26665 but in the generated assembler file, this would come out as:
26669 pushfl popl %eax movl %eax, -40(%ebp)
26673 which is not so convenient for the human reader.
26675 We use Ada comments
26676 at the end of each line to explain what the assembler instructions
26677 actually do. This is a useful convention.
26679 When writing Inline Assembler instructions, you need to precede each register
26680 and variable name with a percent sign. Since the assembler already requires
26681 a percent sign at the beginning of a register name, you need two consecutive
26682 percent signs for such names in the Asm template string, thus @code{%%eax}.
26683 In the generated assembly code, one of the percent signs will be stripped off.
26685 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
26686 variables: operands you later define using @code{Input} or @code{Output}
26687 parameters to @code{Asm}.
26688 An output variable is illustrated in
26689 the third statement in the Asm template string:
26693 The intent is to store the contents of the eax register in a variable that can
26694 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
26695 necessarily work, since the compiler might optimize by using a register
26696 to hold Flags, and the expansion of the @code{movl} instruction would not be
26697 aware of this optimization. The solution is not to store the result directly
26698 but rather to advise the compiler to choose the correct operand form;
26699 that is the purpose of the @code{%0} output variable.
26701 Information about the output variable is supplied in the @code{Outputs}
26702 parameter to @code{Asm}:
26704 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26707 The output is defined by the @code{Asm_Output} attribute of the target type;
26708 the general format is
26710 Type'Asm_Output (constraint_string, variable_name)
26713 The constraint string directs the compiler how
26714 to store/access the associated variable. In the example
26716 Unsigned_32'Asm_Output ("=m", Flags);
26718 the @code{"m"} (memory) constraint tells the compiler that the variable
26719 @code{Flags} should be stored in a memory variable, thus preventing
26720 the optimizer from keeping it in a register. In contrast,
26722 Unsigned_32'Asm_Output ("=r", Flags);
26724 uses the @code{"r"} (register) constraint, telling the compiler to
26725 store the variable in a register.
26727 If the constraint is preceded by the equal character (@strong{=}), it tells
26728 the compiler that the variable will be used to store data into it.
26730 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26731 allowing the optimizer to choose whatever it deems best.
26733 There are a fairly large number of constraints, but the ones that are
26734 most useful (for the Intel x86 processor) are the following:
26740 global (i.e.@: can be stored anywhere)
26758 use one of eax, ebx, ecx or edx
26760 use one of eax, ebx, ecx, edx, esi or edi
26763 The full set of constraints is described in the gcc and @emph{as}
26764 documentation; note that it is possible to combine certain constraints
26765 in one constraint string.
26767 You specify the association of an output variable with an assembler operand
26768 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26770 @smallexample @c ada
26772 Asm ("pushfl" & LF & HT & -- push flags on stack
26773 "popl %%eax" & LF & HT & -- load eax with flags
26774 "movl %%eax, %0", -- store flags in variable
26775 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26779 @code{%0} will be replaced in the expanded code by the appropriate operand,
26781 the compiler decided for the @code{Flags} variable.
26783 In general, you may have any number of output variables:
26786 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26788 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26789 of @code{Asm_Output} attributes
26793 @smallexample @c ada
26795 Asm ("movl %%eax, %0" & LF & HT &
26796 "movl %%ebx, %1" & LF & HT &
26798 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
26799 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
26800 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
26804 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26805 in the Ada program.
26807 As a variation on the @code{Get_Flags} example, we can use the constraints
26808 string to direct the compiler to store the eax register into the @code{Flags}
26809 variable, instead of including the store instruction explicitly in the
26810 @code{Asm} template string:
26812 @smallexample @c ada
26814 with Interfaces; use Interfaces;
26815 with Ada.Text_IO; use Ada.Text_IO;
26816 with System.Machine_Code; use System.Machine_Code;
26817 procedure Get_Flags_2 is
26818 Flags : Unsigned_32;
26821 Asm ("pushfl" & LF & HT & -- push flags on stack
26822 "popl %%eax", -- save flags in eax
26823 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26824 Put_Line ("Flags register:" & Flags'Img);
26830 The @code{"a"} constraint tells the compiler that the @code{Flags}
26831 variable will come from the eax register. Here is the resulting code:
26839 movl %eax,-40(%ebp)
26844 The compiler generated the store of eax into Flags after
26845 expanding the assembler code.
26847 Actually, there was no need to pop the flags into the eax register;
26848 more simply, we could just pop the flags directly into the program variable:
26850 @smallexample @c ada
26852 with Interfaces; use Interfaces;
26853 with Ada.Text_IO; use Ada.Text_IO;
26854 with System.Machine_Code; use System.Machine_Code;
26855 procedure Get_Flags_3 is
26856 Flags : Unsigned_32;
26859 Asm ("pushfl" & LF & HT & -- push flags on stack
26860 "pop %0", -- save flags in Flags
26861 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26862 Put_Line ("Flags register:" & Flags'Img);
26867 @c ---------------------------------------------------------------------------
26868 @node Input Variables in Inline Assembler
26869 @section Input Variables in Inline Assembler
26872 The example in this section illustrates how to specify the source operands
26873 for assembly language statements.
26874 The program simply increments its input value by 1:
26876 @smallexample @c ada
26878 with Interfaces; use Interfaces;
26879 with Ada.Text_IO; use Ada.Text_IO;
26880 with System.Machine_Code; use System.Machine_Code;
26881 procedure Increment is
26883 function Incr (Value : Unsigned_32) return Unsigned_32 is
26884 Result : Unsigned_32;
26887 Outputs => Unsigned_32'Asm_Output ("=a", Result),
26888 Inputs => Unsigned_32'Asm_Input ("a", Value));
26892 Value : Unsigned_32;
26896 Put_Line ("Value before is" & Value'Img);
26897 Value := Incr (Value);
26898 Put_Line ("Value after is" & Value'Img);
26903 The @code{Outputs} parameter to @code{Asm} specifies
26904 that the result will be in the eax register and that it is to be stored
26905 in the @code{Result} variable.
26907 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26908 but with an @code{Asm_Input} attribute.
26909 The @code{"="} constraint, indicating an output value, is not present.
26911 You can have multiple input variables, in the same way that you can have more
26912 than one output variable.
26914 The parameter count (%0, %1) etc, still starts at the first output statement,
26915 and continues with the input statements.
26917 Just as the @code{Outputs} parameter causes the register to be stored into the
26918 target variable after execution of the assembler statements, so does the
26919 @code{Inputs} parameter cause its variable to be loaded into the register
26920 before execution of the assembler statements.
26922 Thus the effect of the @code{Asm} invocation is:
26924 @item load the 32-bit value of @code{Value} into eax
26925 @item execute the @code{incl %eax} instruction
26926 @item store the contents of eax into the @code{Result} variable
26929 The resulting assembler file (with @option{-O2} optimization) contains:
26932 _increment__incr.1:
26945 @c ---------------------------------------------------------------------------
26946 @node Inlining Inline Assembler Code
26947 @section Inlining Inline Assembler Code
26950 For a short subprogram such as the @code{Incr} function in the previous
26951 section, the overhead of the call and return (creating / deleting the stack
26952 frame) can be significant, compared to the amount of code in the subprogram
26953 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26954 which directs the compiler to expand invocations of the subprogram at the
26955 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26956 Here is the resulting program:
26958 @smallexample @c ada
26960 with Interfaces; use Interfaces;
26961 with Ada.Text_IO; use Ada.Text_IO;
26962 with System.Machine_Code; use System.Machine_Code;
26963 procedure Increment_2 is
26965 function Incr (Value : Unsigned_32) return Unsigned_32 is
26966 Result : Unsigned_32;
26969 Outputs => Unsigned_32'Asm_Output ("=a", Result),
26970 Inputs => Unsigned_32'Asm_Input ("a", Value));
26973 pragma Inline (Increment);
26975 Value : Unsigned_32;
26979 Put_Line ("Value before is" & Value'Img);
26980 Value := Increment (Value);
26981 Put_Line ("Value after is" & Value'Img);
26986 Compile the program with both optimization (@option{-O2}) and inlining
26987 (@option{-gnatn}) enabled.
26989 The @code{Incr} function is still compiled as usual, but at the
26990 point in @code{Increment} where our function used to be called:
26995 call _increment__incr.1
27000 the code for the function body directly appears:
27013 thus saving the overhead of stack frame setup and an out-of-line call.
27015 @c ---------------------------------------------------------------------------
27016 @node Other Asm Functionality
27017 @section Other @code{Asm} Functionality
27020 This section describes two important parameters to the @code{Asm}
27021 procedure: @code{Clobber}, which identifies register usage;
27022 and @code{Volatile}, which inhibits unwanted optimizations.
27025 * The Clobber Parameter::
27026 * The Volatile Parameter::
27029 @c ---------------------------------------------------------------------------
27030 @node The Clobber Parameter
27031 @subsection The @code{Clobber} Parameter
27034 One of the dangers of intermixing assembly language and a compiled language
27035 such as Ada is that the compiler needs to be aware of which registers are
27036 being used by the assembly code. In some cases, such as the earlier examples,
27037 the constraint string is sufficient to indicate register usage (e.g.,
27039 the eax register). But more generally, the compiler needs an explicit
27040 identification of the registers that are used by the Inline Assembly
27043 Using a register that the compiler doesn't know about
27044 could be a side effect of an instruction (like @code{mull}
27045 storing its result in both eax and edx).
27046 It can also arise from explicit register usage in your
27047 assembly code; for example:
27050 Asm ("movl %0, %%ebx" & LF & HT &
27052 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27053 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
27057 where the compiler (since it does not analyze the @code{Asm} template string)
27058 does not know you are using the ebx register.
27060 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
27061 to identify the registers that will be used by your assembly code:
27065 Asm ("movl %0, %%ebx" & LF & HT &
27067 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27068 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
27073 The Clobber parameter is a static string expression specifying the
27074 register(s) you are using. Note that register names are @emph{not} prefixed
27075 by a percent sign. Also, if more than one register is used then their names
27076 are separated by commas; e.g., @code{"eax, ebx"}
27078 The @code{Clobber} parameter has several additional uses:
27080 @item Use ``register'' name @code{cc} to indicate that flags might have changed
27081 @item Use ``register'' name @code{memory} if you changed a memory location
27084 @c ---------------------------------------------------------------------------
27085 @node The Volatile Parameter
27086 @subsection The @code{Volatile} Parameter
27087 @cindex Volatile parameter
27090 Compiler optimizations in the presence of Inline Assembler may sometimes have
27091 unwanted effects. For example, when an @code{Asm} invocation with an input
27092 variable is inside a loop, the compiler might move the loading of the input
27093 variable outside the loop, regarding it as a one-time initialization.
27095 If this effect is not desired, you can disable such optimizations by setting
27096 the @code{Volatile} parameter to @code{True}; for example:
27098 @smallexample @c ada
27100 Asm ("movl %0, %%ebx" & LF & HT &
27102 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27103 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
27109 By default, @code{Volatile} is set to @code{False} unless there is no
27110 @code{Outputs} parameter.
27112 Although setting @code{Volatile} to @code{True} prevents unwanted
27113 optimizations, it will also disable other optimizations that might be
27114 important for efficiency. In general, you should set @code{Volatile}
27115 to @code{True} only if the compiler's optimizations have created
27117 @c END OF INLINE ASSEMBLER CHAPTER
27118 @c ===============================
27120 @c ***********************************
27121 @c * Compatibility and Porting Guide *
27122 @c ***********************************
27123 @node Compatibility and Porting Guide
27124 @appendix Compatibility and Porting Guide
27127 This chapter describes the compatibility issues that may arise between
27128 GNAT and other Ada compilation systems (including those for Ada 83),
27129 and shows how GNAT can expedite porting
27130 applications developed in other Ada environments.
27133 * Compatibility with Ada 83::
27134 * Compatibility between Ada 95 and Ada 2005::
27135 * Implementation-dependent characteristics::
27136 * Compatibility with Other Ada Systems::
27137 * Representation Clauses::
27139 @c Brief section is only in non-VMS version
27140 @c Full chapter is in VMS version
27141 * Compatibility with HP Ada 83::
27144 * Transitioning to 64-Bit GNAT for OpenVMS::
27148 @node Compatibility with Ada 83
27149 @section Compatibility with Ada 83
27150 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
27153 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
27154 particular, the design intention was that the difficulties associated
27155 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
27156 that occur when moving from one Ada 83 system to another.
27158 However, there are a number of points at which there are minor
27159 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
27160 full details of these issues,
27161 and should be consulted for a complete treatment.
27163 following subsections treat the most likely issues to be encountered.
27166 * Legal Ada 83 programs that are illegal in Ada 95::
27167 * More deterministic semantics::
27168 * Changed semantics::
27169 * Other language compatibility issues::
27172 @node Legal Ada 83 programs that are illegal in Ada 95
27173 @subsection Legal Ada 83 programs that are illegal in Ada 95
27175 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
27176 Ada 95 and thus also in Ada 2005:
27179 @item Character literals
27180 Some uses of character literals are ambiguous. Since Ada 95 has introduced
27181 @code{Wide_Character} as a new predefined character type, some uses of
27182 character literals that were legal in Ada 83 are illegal in Ada 95.
27184 @smallexample @c ada
27185 for Char in 'A' .. 'Z' loop @dots{} end loop;
27189 The problem is that @code{'A'} and @code{'Z'} could be from either
27190 @code{Character} or @code{Wide_Character}. The simplest correction
27191 is to make the type explicit; e.g.:
27192 @smallexample @c ada
27193 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
27196 @item New reserved words
27197 The identifiers @code{abstract}, @code{aliased}, @code{protected},
27198 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
27199 Existing Ada 83 code using any of these identifiers must be edited to
27200 use some alternative name.
27202 @item Freezing rules
27203 The rules in Ada 95 are slightly different with regard to the point at
27204 which entities are frozen, and representation pragmas and clauses are
27205 not permitted past the freeze point. This shows up most typically in
27206 the form of an error message complaining that a representation item
27207 appears too late, and the appropriate corrective action is to move
27208 the item nearer to the declaration of the entity to which it refers.
27210 A particular case is that representation pragmas
27213 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
27215 cannot be applied to a subprogram body. If necessary, a separate subprogram
27216 declaration must be introduced to which the pragma can be applied.
27218 @item Optional bodies for library packages
27219 In Ada 83, a package that did not require a package body was nevertheless
27220 allowed to have one. This lead to certain surprises in compiling large
27221 systems (situations in which the body could be unexpectedly ignored by the
27222 binder). In Ada 95, if a package does not require a body then it is not
27223 permitted to have a body. To fix this problem, simply remove a redundant
27224 body if it is empty, or, if it is non-empty, introduce a dummy declaration
27225 into the spec that makes the body required. One approach is to add a private
27226 part to the package declaration (if necessary), and define a parameterless
27227 procedure called @code{Requires_Body}, which must then be given a dummy
27228 procedure body in the package body, which then becomes required.
27229 Another approach (assuming that this does not introduce elaboration
27230 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
27231 since one effect of this pragma is to require the presence of a package body.
27233 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
27234 In Ada 95, the exception @code{Numeric_Error} is a renaming of
27235 @code{Constraint_Error}.
27236 This means that it is illegal to have separate exception handlers for
27237 the two exceptions. The fix is simply to remove the handler for the
27238 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
27239 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
27241 @item Indefinite subtypes in generics
27242 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
27243 as the actual for a generic formal private type, but then the instantiation
27244 would be illegal if there were any instances of declarations of variables
27245 of this type in the generic body. In Ada 95, to avoid this clear violation
27246 of the methodological principle known as the ``contract model'',
27247 the generic declaration explicitly indicates whether
27248 or not such instantiations are permitted. If a generic formal parameter
27249 has explicit unknown discriminants, indicated by using @code{(<>)} after the
27250 subtype name, then it can be instantiated with indefinite types, but no
27251 stand-alone variables can be declared of this type. Any attempt to declare
27252 such a variable will result in an illegality at the time the generic is
27253 declared. If the @code{(<>)} notation is not used, then it is illegal
27254 to instantiate the generic with an indefinite type.
27255 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
27256 It will show up as a compile time error, and
27257 the fix is usually simply to add the @code{(<>)} to the generic declaration.
27260 @node More deterministic semantics
27261 @subsection More deterministic semantics
27265 Conversions from real types to integer types round away from 0. In Ada 83
27266 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
27267 implementation freedom was intended to support unbiased rounding in
27268 statistical applications, but in practice it interfered with portability.
27269 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
27270 is required. Numeric code may be affected by this change in semantics.
27271 Note, though, that this issue is no worse than already existed in Ada 83
27272 when porting code from one vendor to another.
27275 The Real-Time Annex introduces a set of policies that define the behavior of
27276 features that were implementation dependent in Ada 83, such as the order in
27277 which open select branches are executed.
27280 @node Changed semantics
27281 @subsection Changed semantics
27284 The worst kind of incompatibility is one where a program that is legal in
27285 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
27286 possible in Ada 83. Fortunately this is extremely rare, but the one
27287 situation that you should be alert to is the change in the predefined type
27288 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
27291 @item Range of type @code{Character}
27292 The range of @code{Standard.Character} is now the full 256 characters
27293 of Latin-1, whereas in most Ada 83 implementations it was restricted
27294 to 128 characters. Although some of the effects of
27295 this change will be manifest in compile-time rejection of legal
27296 Ada 83 programs it is possible for a working Ada 83 program to have
27297 a different effect in Ada 95, one that was not permitted in Ada 83.
27298 As an example, the expression
27299 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
27300 delivers @code{255} as its value.
27301 In general, you should look at the logic of any
27302 character-processing Ada 83 program and see whether it needs to be adapted
27303 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
27304 character handling package that may be relevant if code needs to be adapted
27305 to account for the additional Latin-1 elements.
27306 The desirable fix is to
27307 modify the program to accommodate the full character set, but in some cases
27308 it may be convenient to define a subtype or derived type of Character that
27309 covers only the restricted range.
27313 @node Other language compatibility issues
27314 @subsection Other language compatibility issues
27317 @item @option{-gnat83} switch
27318 All implementations of GNAT provide a switch that causes GNAT to operate
27319 in Ada 83 mode. In this mode, some but not all compatibility problems
27320 of the type described above are handled automatically. For example, the
27321 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
27322 as identifiers as in Ada 83.
27324 in practice, it is usually advisable to make the necessary modifications
27325 to the program to remove the need for using this switch.
27326 See @ref{Compiling Different Versions of Ada}.
27328 @item Support for removed Ada 83 pragmas and attributes
27329 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
27330 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
27331 compilers are allowed, but not required, to implement these missing
27332 elements. In contrast with some other compilers, GNAT implements all
27333 such pragmas and attributes, eliminating this compatibility concern. These
27334 include @code{pragma Interface} and the floating point type attributes
27335 (@code{Emax}, @code{Mantissa}, etc.), among other items.
27339 @node Compatibility between Ada 95 and Ada 2005
27340 @section Compatibility between Ada 95 and Ada 2005
27341 @cindex Compatibility between Ada 95 and Ada 2005
27344 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
27345 a number of incompatibilities. Several are enumerated below;
27346 for a complete description please see the
27347 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
27348 @cite{Rationale for Ada 2005}.
27351 @item New reserved words.
27352 The words @code{interface}, @code{overriding} and @code{synchronized} are
27353 reserved in Ada 2005.
27354 A pre-Ada 2005 program that uses any of these as an identifier will be
27357 @item New declarations in predefined packages.
27358 A number of packages in the predefined environment contain new declarations:
27359 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
27360 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
27361 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
27362 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
27363 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
27364 If an Ada 95 program does a @code{with} and @code{use} of any of these
27365 packages, the new declarations may cause name clashes.
27367 @item Access parameters.
27368 A nondispatching subprogram with an access parameter cannot be renamed
27369 as a dispatching operation. This was permitted in Ada 95.
27371 @item Access types, discriminants, and constraints.
27372 Rule changes in this area have led to some incompatibilities; for example,
27373 constrained subtypes of some access types are not permitted in Ada 2005.
27375 @item Aggregates for limited types.
27376 The allowance of aggregates for limited types in Ada 2005 raises the
27377 possibility of ambiguities in legal Ada 95 programs, since additional types
27378 now need to be considered in expression resolution.
27380 @item Fixed-point multiplication and division.
27381 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
27382 were legal in Ada 95 and invoked the predefined versions of these operations,
27384 The ambiguity may be resolved either by applying a type conversion to the
27385 expression, or by explicitly invoking the operation from package
27388 @item Return-by-reference types.
27389 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
27390 can declare a function returning a value from an anonymous access type.
27394 @node Implementation-dependent characteristics
27395 @section Implementation-dependent characteristics
27397 Although the Ada language defines the semantics of each construct as
27398 precisely as practical, in some situations (for example for reasons of
27399 efficiency, or where the effect is heavily dependent on the host or target
27400 platform) the implementation is allowed some freedom. In porting Ada 83
27401 code to GNAT, you need to be aware of whether / how the existing code
27402 exercised such implementation dependencies. Such characteristics fall into
27403 several categories, and GNAT offers specific support in assisting the
27404 transition from certain Ada 83 compilers.
27407 * Implementation-defined pragmas::
27408 * Implementation-defined attributes::
27410 * Elaboration order::
27411 * Target-specific aspects::
27414 @node Implementation-defined pragmas
27415 @subsection Implementation-defined pragmas
27418 Ada compilers are allowed to supplement the language-defined pragmas, and
27419 these are a potential source of non-portability. All GNAT-defined pragmas
27420 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
27421 Reference Manual}, and these include several that are specifically
27422 intended to correspond to other vendors' Ada 83 pragmas.
27423 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
27424 For compatibility with HP Ada 83, GNAT supplies the pragmas
27425 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
27426 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
27427 and @code{Volatile}.
27428 Other relevant pragmas include @code{External} and @code{Link_With}.
27429 Some vendor-specific
27430 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
27432 avoiding compiler rejection of units that contain such pragmas; they are not
27433 relevant in a GNAT context and hence are not otherwise implemented.
27435 @node Implementation-defined attributes
27436 @subsection Implementation-defined attributes
27438 Analogous to pragmas, the set of attributes may be extended by an
27439 implementation. All GNAT-defined attributes are described in
27440 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
27441 Manual}, and these include several that are specifically intended
27442 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
27443 the attribute @code{VADS_Size} may be useful. For compatibility with HP
27444 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
27448 @subsection Libraries
27450 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
27451 code uses vendor-specific libraries then there are several ways to manage
27452 this in Ada 95 or Ada 2005:
27455 If the source code for the libraries (specs and bodies) are
27456 available, then the libraries can be migrated in the same way as the
27459 If the source code for the specs but not the bodies are
27460 available, then you can reimplement the bodies.
27462 Some features introduced by Ada 95 obviate the need for library support. For
27463 example most Ada 83 vendors supplied a package for unsigned integers. The
27464 Ada 95 modular type feature is the preferred way to handle this need, so
27465 instead of migrating or reimplementing the unsigned integer package it may
27466 be preferable to retrofit the application using modular types.
27469 @node Elaboration order
27470 @subsection Elaboration order
27472 The implementation can choose any elaboration order consistent with the unit
27473 dependency relationship. This freedom means that some orders can result in
27474 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
27475 to invoke a subprogram its body has been elaborated, or to instantiate a
27476 generic before the generic body has been elaborated. By default GNAT
27477 attempts to choose a safe order (one that will not encounter access before
27478 elaboration problems) by implicitly inserting @code{Elaborate} or
27479 @code{Elaborate_All} pragmas where
27480 needed. However, this can lead to the creation of elaboration circularities
27481 and a resulting rejection of the program by gnatbind. This issue is
27482 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
27483 In brief, there are several
27484 ways to deal with this situation:
27488 Modify the program to eliminate the circularities, e.g.@: by moving
27489 elaboration-time code into explicitly-invoked procedures
27491 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
27492 @code{Elaborate} pragmas, and then inhibit the generation of implicit
27493 @code{Elaborate_All}
27494 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
27495 (by selectively suppressing elaboration checks via pragma
27496 @code{Suppress(Elaboration_Check)} when it is safe to do so).
27499 @node Target-specific aspects
27500 @subsection Target-specific aspects
27502 Low-level applications need to deal with machine addresses, data
27503 representations, interfacing with assembler code, and similar issues. If
27504 such an Ada 83 application is being ported to different target hardware (for
27505 example where the byte endianness has changed) then you will need to
27506 carefully examine the program logic; the porting effort will heavily depend
27507 on the robustness of the original design. Moreover, Ada 95 (and thus
27508 Ada 2005) are sometimes
27509 incompatible with typical Ada 83 compiler practices regarding implicit
27510 packing, the meaning of the Size attribute, and the size of access values.
27511 GNAT's approach to these issues is described in @ref{Representation Clauses}.
27513 @node Compatibility with Other Ada Systems
27514 @section Compatibility with Other Ada Systems
27517 If programs avoid the use of implementation dependent and
27518 implementation defined features, as documented in the @cite{Ada
27519 Reference Manual}, there should be a high degree of portability between
27520 GNAT and other Ada systems. The following are specific items which
27521 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
27522 compilers, but do not affect porting code to GNAT@.
27523 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
27524 the following issues may or may not arise for Ada 2005 programs
27525 when other compilers appear.)
27528 @item Ada 83 Pragmas and Attributes
27529 Ada 95 compilers are allowed, but not required, to implement the missing
27530 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
27531 GNAT implements all such pragmas and attributes, eliminating this as
27532 a compatibility concern, but some other Ada 95 compilers reject these
27533 pragmas and attributes.
27535 @item Specialized Needs Annexes
27536 GNAT implements the full set of special needs annexes. At the
27537 current time, it is the only Ada 95 compiler to do so. This means that
27538 programs making use of these features may not be portable to other Ada
27539 95 compilation systems.
27541 @item Representation Clauses
27542 Some other Ada 95 compilers implement only the minimal set of
27543 representation clauses required by the Ada 95 reference manual. GNAT goes
27544 far beyond this minimal set, as described in the next section.
27547 @node Representation Clauses
27548 @section Representation Clauses
27551 The Ada 83 reference manual was quite vague in describing both the minimal
27552 required implementation of representation clauses, and also their precise
27553 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
27554 minimal set of capabilities required is still quite limited.
27556 GNAT implements the full required set of capabilities in
27557 Ada 95 and Ada 2005, but also goes much further, and in particular
27558 an effort has been made to be compatible with existing Ada 83 usage to the
27559 greatest extent possible.
27561 A few cases exist in which Ada 83 compiler behavior is incompatible with
27562 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
27563 intentional or accidental dependence on specific implementation dependent
27564 characteristics of these Ada 83 compilers. The following is a list of
27565 the cases most likely to arise in existing Ada 83 code.
27568 @item Implicit Packing
27569 Some Ada 83 compilers allowed a Size specification to cause implicit
27570 packing of an array or record. This could cause expensive implicit
27571 conversions for change of representation in the presence of derived
27572 types, and the Ada design intends to avoid this possibility.
27573 Subsequent AI's were issued to make it clear that such implicit
27574 change of representation in response to a Size clause is inadvisable,
27575 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27576 Reference Manuals as implementation advice that is followed by GNAT@.
27577 The problem will show up as an error
27578 message rejecting the size clause. The fix is simply to provide
27579 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27580 a Component_Size clause.
27582 @item Meaning of Size Attribute
27583 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27584 the minimal number of bits required to hold values of the type. For example,
27585 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27586 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
27587 some 32 in this situation. This problem will usually show up as a compile
27588 time error, but not always. It is a good idea to check all uses of the
27589 'Size attribute when porting Ada 83 code. The GNAT specific attribute
27590 Object_Size can provide a useful way of duplicating the behavior of
27591 some Ada 83 compiler systems.
27593 @item Size of Access Types
27594 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27595 and that therefore it will be the same size as a System.Address value. This
27596 assumption is true for GNAT in most cases with one exception. For the case of
27597 a pointer to an unconstrained array type (where the bounds may vary from one
27598 value of the access type to another), the default is to use a ``fat pointer'',
27599 which is represented as two separate pointers, one to the bounds, and one to
27600 the array. This representation has a number of advantages, including improved
27601 efficiency. However, it may cause some difficulties in porting existing Ada 83
27602 code which makes the assumption that, for example, pointers fit in 32 bits on
27603 a machine with 32-bit addressing.
27605 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27606 access types in this case (where the designated type is an unconstrained array
27607 type). These thin pointers are indeed the same size as a System.Address value.
27608 To specify a thin pointer, use a size clause for the type, for example:
27610 @smallexample @c ada
27611 type X is access all String;
27612 for X'Size use Standard'Address_Size;
27616 which will cause the type X to be represented using a single pointer.
27617 When using this representation, the bounds are right behind the array.
27618 This representation is slightly less efficient, and does not allow quite
27619 such flexibility in the use of foreign pointers or in using the
27620 Unrestricted_Access attribute to create pointers to non-aliased objects.
27621 But for any standard portable use of the access type it will work in
27622 a functionally correct manner and allow porting of existing code.
27623 Note that another way of forcing a thin pointer representation
27624 is to use a component size clause for the element size in an array,
27625 or a record representation clause for an access field in a record.
27629 @c This brief section is only in the non-VMS version
27630 @c The complete chapter on HP Ada is in the VMS version
27631 @node Compatibility with HP Ada 83
27632 @section Compatibility with HP Ada 83
27635 The VMS version of GNAT fully implements all the pragmas and attributes
27636 provided by HP Ada 83, as well as providing the standard HP Ada 83
27637 libraries, including Starlet. In addition, data layouts and parameter
27638 passing conventions are highly compatible. This means that porting
27639 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27640 most other porting efforts. The following are some of the most
27641 significant differences between GNAT and HP Ada 83.
27644 @item Default floating-point representation
27645 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27646 it is VMS format. GNAT does implement the necessary pragmas
27647 (Long_Float, Float_Representation) for changing this default.
27650 The package System in GNAT exactly corresponds to the definition in the
27651 Ada 95 reference manual, which means that it excludes many of the
27652 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
27653 that contains the additional definitions, and a special pragma,
27654 Extend_System allows this package to be treated transparently as an
27655 extension of package System.
27658 The definitions provided by Aux_DEC are exactly compatible with those
27659 in the HP Ada 83 version of System, with one exception.
27660 HP Ada provides the following declarations:
27662 @smallexample @c ada
27663 TO_ADDRESS (INTEGER)
27664 TO_ADDRESS (UNSIGNED_LONGWORD)
27665 TO_ADDRESS (@i{universal_integer})
27669 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27670 an extension to Ada 83 not strictly compatible with the reference manual.
27671 In GNAT, we are constrained to be exactly compatible with the standard,
27672 and this means we cannot provide this capability. In HP Ada 83, the
27673 point of this definition is to deal with a call like:
27675 @smallexample @c ada
27676 TO_ADDRESS (16#12777#);
27680 Normally, according to the Ada 83 standard, one would expect this to be
27681 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27682 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
27683 definition using @i{universal_integer} takes precedence.
27685 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27686 is not possible to be 100% compatible. Since there are many programs using
27687 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27688 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27689 declarations provided in the GNAT version of AUX_Dec are:
27691 @smallexample @c ada
27692 function To_Address (X : Integer) return Address;
27693 pragma Pure_Function (To_Address);
27695 function To_Address_Long (X : Unsigned_Longword)
27697 pragma Pure_Function (To_Address_Long);
27701 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27702 change the name to TO_ADDRESS_LONG@.
27704 @item Task_Id values
27705 The Task_Id values assigned will be different in the two systems, and GNAT
27706 does not provide a specified value for the Task_Id of the environment task,
27707 which in GNAT is treated like any other declared task.
27711 For full details on these and other less significant compatibility issues,
27712 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27713 Overview and Comparison on HP Platforms}.
27715 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27716 attributes are recognized, although only a subset of them can sensibly
27717 be implemented. The description of pragmas in @ref{Implementation
27718 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27719 indicates whether or not they are applicable to non-VMS systems.
27723 @node Transitioning to 64-Bit GNAT for OpenVMS
27724 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
27727 This section is meant to assist users of pre-2006 @value{EDITION}
27728 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
27729 the version of the GNAT technology supplied in 2006 and later for
27730 OpenVMS on both Alpha and I64.
27733 * Introduction to transitioning::
27734 * Migration of 32 bit code::
27735 * Taking advantage of 64 bit addressing::
27736 * Technical details::
27739 @node Introduction to transitioning
27740 @subsection Introduction
27743 64-bit @value{EDITION} for Open VMS has been designed to meet
27748 Providing a full conforming implementation of Ada 95 and Ada 2005
27751 Allowing maximum backward compatibility, thus easing migration of existing
27755 Supplying a path for exploiting the full 64-bit address range
27759 Ada's strong typing semantics has made it
27760 impractical to have different 32-bit and 64-bit modes. As soon as
27761 one object could possibly be outside the 32-bit address space, this
27762 would make it necessary for the @code{System.Address} type to be 64 bits.
27763 In particular, this would cause inconsistencies if 32-bit code is
27764 called from 64-bit code that raises an exception.
27766 This issue has been resolved by always using 64-bit addressing
27767 at the system level, but allowing for automatic conversions between
27768 32-bit and 64-bit addresses where required. Thus users who
27769 do not currently require 64-bit addressing capabilities, can
27770 recompile their code with only minimal changes (and indeed
27771 if the code is written in portable Ada, with no assumptions about
27772 the size of the @code{Address} type, then no changes at all are necessary).
27774 this approach provides a simple, gradual upgrade path to future
27775 use of larger memories than available for 32-bit systems.
27776 Also, newly written applications or libraries will by default
27777 be fully compatible with future systems exploiting 64-bit
27778 addressing capabilities.
27780 @ref{Migration of 32 bit code}, will focus on porting applications
27781 that do not require more than 2 GB of
27782 addressable memory. This code will be referred to as
27783 @emph{32-bit code}.
27784 For applications intending to exploit the full 64-bit address space,
27785 @ref{Taking advantage of 64 bit addressing},
27786 will consider further changes that may be required.
27787 Such code will be referred to below as @emph{64-bit code}.
27789 @node Migration of 32 bit code
27790 @subsection Migration of 32-bit code
27794 * Access types and 32/64-bit allocation::
27795 * Unchecked conversions::
27796 * Predefined constants::
27797 * Interfacing with C::
27798 * 32/64-bit descriptors::
27799 * Experience with source compatibility::
27802 @node Address types
27803 @subsubsection Address types
27806 To solve the problem of mixing 64-bit and 32-bit addressing,
27807 while maintaining maximum backward compatibility, the following
27808 approach has been taken:
27812 @code{System.Address} always has a size of 64 bits
27813 @cindex @code{System.Address} size
27814 @cindex @code{Address} size
27817 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
27818 @cindex @code{System.Short_Address} size
27819 @cindex @code{Short_Address} size
27823 Since @code{System.Short_Address} is a subtype of @code{System.Address},
27824 a @code{Short_Address}
27825 may be used where an @code{Address} is required, and vice versa, without
27826 needing explicit type conversions.
27827 By virtue of the Open VMS parameter passing conventions,
27829 and exported subprograms that have 32-bit address parameters are
27830 compatible with those that have 64-bit address parameters.
27831 (See @ref{Making code 64 bit clean} for details.)
27833 The areas that may need attention are those where record types have
27834 been defined that contain components of the type @code{System.Address}, and
27835 where objects of this type are passed to code expecting a record layout with
27838 Different compilers on different platforms cannot be
27839 expected to represent the same type in the same way,
27840 since alignment constraints
27841 and other system-dependent properties affect the compiler's decision.
27842 For that reason, Ada code
27843 generally uses representation clauses to specify the expected
27844 layout where required.
27846 If such a representation clause uses 32 bits for a component having
27847 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
27848 will detect that error and produce a specific diagnostic message.
27849 The developer should then determine whether the representation
27850 should be 64 bits or not and make either of two changes:
27851 change the size to 64 bits and leave the type as @code{System.Address}, or
27852 leave the size as 32 bits and change the type to @code{System.Short_Address}.
27853 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
27854 required in any code setting or accessing the field; the compiler will
27855 automatically perform any needed conversions between address
27858 @node Access types and 32/64-bit allocation
27859 @subsubsection Access types and 32/64-bit allocation
27860 @cindex 32-bit allocation
27861 @cindex 64-bit allocation
27864 By default, objects designated by access values are always allocated in
27865 the 64-bit address space, and access values themselves are represented
27866 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
27867 is required (for example if the address of an allocated object is assigned
27868 to a @code{Short_Address} variable), then several alternatives are available:
27872 A pool-specific access type (ie, an @w{Ada 83} access type, whose
27873 definition is @code{access T} versus @code{access all T} or
27874 @code{access constant T}), may be declared with a @code{'Size} representation
27875 clause that establishes the size as 32 bits.
27876 In such circumstances allocations for that type will
27877 be from the 32-bit heap. Such a clause is not permitted
27878 for a general access type (declared with @code{access all} or
27879 @code{access constant}) as values of such types must be able to refer
27880 to any object of the designated type, including objects residing outside
27881 the 32-bit address range. Existing @w{Ada 83} code will not contain such
27882 type definitions, however, since general access types were introduced
27886 Switches for @command{GNAT BIND} control whether the internal GNAT
27887 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
27888 @cindex @code{__gnat_malloc}
27889 The switches are respectively @option{-H64} (the default) and
27891 @cindex @option{-H32} (@command{gnatbind})
27892 @cindex @option{-H64} (@command{gnatbind})
27895 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
27896 @cindex @code{GNAT$NO_MALLOC_64} environment variable
27897 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
27898 If this variable is left
27899 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
27900 then the default (64-bit) allocation is used.
27901 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
27902 then 32-bit allocation is used. The gnatbind qualifiers described above
27903 override this logical name.
27906 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
27907 @cindex @option{-mno-malloc64} (^gcc^gcc^)
27908 at a low level to convert explicit calls to @code{malloc} and related
27909 functions from the C run-time library so that they perform allocations
27910 in the 32-bit heap.
27911 Since all internal allocations from GNAT use @code{__gnat_malloc},
27912 this switch is not required unless the program makes explicit calls on
27913 @code{malloc} (or related functions) from interfaced C code.
27917 @node Unchecked conversions
27918 @subsubsection Unchecked conversions
27921 In the case of an @code{Unchecked_Conversion} where the source type is a
27922 64-bit access type or the type @code{System.Address}, and the target
27923 type is a 32-bit type, the compiler will generate a warning.
27924 Even though the generated code will still perform the required
27925 conversions, it is highly recommended in these cases to use
27926 respectively a 32-bit access type or @code{System.Short_Address}
27927 as the source type.
27929 @node Predefined constants
27930 @subsubsection Predefined constants
27933 The following table shows the correspondence between pre-2006 versions of
27934 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
27937 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
27938 @item @b{Constant} @tab @b{Old} @tab @b{New}
27939 @item @code{System.Word_Size} @tab 32 @tab 64
27940 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
27941 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
27942 @item @code{System.Address_Size} @tab 32 @tab 64
27946 If you need to refer to the specific
27947 memory size of a 32-bit implementation, instead of the
27948 actual memory size, use @code{System.Short_Memory_Size}
27949 rather than @code{System.Memory_Size}.
27950 Similarly, references to @code{System.Address_Size} may need
27951 to be replaced by @code{System.Short_Address'Size}.
27952 The program @command{gnatfind} may be useful for locating
27953 references to the above constants, so that you can verify that they
27956 @node Interfacing with C
27957 @subsubsection Interfacing with C
27960 In order to minimize the impact of the transition to 64-bit addresses on
27961 legacy programs, some fundamental types in the @code{Interfaces.C}
27962 package hierarchy continue to be represented in 32 bits.
27963 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
27964 This eases integration with the default HP C layout choices, for example
27965 as found in the system routines in @code{DECC$SHR.EXE}.
27966 Because of this implementation choice, the type fully compatible with
27967 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
27968 Depending on the context the compiler will issue a
27969 warning or an error when type @code{Address} is used, alerting the user to a
27970 potential problem. Otherwise 32-bit programs that use
27971 @code{Interfaces.C} should normally not require code modifications
27973 The other issue arising with C interfacing concerns pragma @code{Convention}.
27974 For VMS 64-bit systems, there is an issue of the appropriate default size
27975 of C convention pointers in the absence of an explicit size clause. The HP
27976 C compiler can choose either 32 or 64 bits depending on compiler options.
27977 GNAT chooses 32-bits rather than 64-bits in the default case where no size
27978 clause is given. This proves a better choice for porting 32-bit legacy
27979 applications. In order to have a 64-bit representation, it is necessary to
27980 specify a size representation clause. For example:
27982 @smallexample @c ada
27983 type int_star is access Interfaces.C.int;
27984 pragma Convention(C, int_star);
27985 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
27988 @node 32/64-bit descriptors
27989 @subsubsection 32/64-bit descriptors
27992 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
27993 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
27994 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
27995 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
27996 @cindex @code{Short_Descriptor} mechanism for imported subprograms
27998 If the configuration pragma @code{Short_Descriptors} is supplied, then
27999 all descriptors will be 32 bits.
28000 @cindex pragma @code{Short_Descriptors}
28002 @node Experience with source compatibility
28003 @subsubsection Experience with source compatibility
28006 The Security Server and STARLET on I64 provide an interesting ``test case''
28007 for source compatibility issues, since it is in such system code
28008 where assumptions about @code{Address} size might be expected to occur.
28009 Indeed, there were a small number of occasions in the Security Server
28010 file @file{jibdef.ads}
28011 where a representation clause for a record type specified
28012 32 bits for a component of type @code{Address}.
28013 All of these errors were detected by the compiler.
28014 The repair was obvious and immediate; to simply replace @code{Address} by
28015 @code{Short_Address}.
28017 In the case of STARLET, there were several record types that should
28018 have had representation clauses but did not. In these record types
28019 there was an implicit assumption that an @code{Address} value occupied
28021 These compiled without error, but their usage resulted in run-time error
28022 returns from STARLET system calls.
28023 Future GNAT technology enhancements may include a tool that detects and flags
28024 these sorts of potential source code porting problems.
28026 @c ****************************************
28027 @node Taking advantage of 64 bit addressing
28028 @subsection Taking advantage of 64-bit addressing
28031 * Making code 64 bit clean::
28032 * Allocating memory from the 64 bit storage pool::
28033 * Restrictions on use of 64 bit objects::
28034 * STARLET and other predefined libraries::
28037 @node Making code 64 bit clean
28038 @subsubsection Making code 64-bit clean
28041 In order to prevent problems that may occur when (parts of) a
28042 system start using memory outside the 32-bit address range,
28043 we recommend some additional guidelines:
28047 For imported subprograms that take parameters of the
28048 type @code{System.Address}, ensure that these subprograms can
28049 indeed handle 64-bit addresses. If not, or when in doubt,
28050 change the subprogram declaration to specify
28051 @code{System.Short_Address} instead.
28054 Resolve all warnings related to size mismatches in
28055 unchecked conversions. Failing to do so causes
28056 erroneous execution if the source object is outside
28057 the 32-bit address space.
28060 (optional) Explicitly use the 32-bit storage pool
28061 for access types used in a 32-bit context, or use
28062 generic access types where possible
28063 (@pxref{Restrictions on use of 64 bit objects}).
28067 If these rules are followed, the compiler will automatically insert
28068 any necessary checks to ensure that no addresses or access values
28069 passed to 32-bit code ever refer to objects outside the 32-bit
28071 Any attempt to do this will raise @code{Constraint_Error}.
28073 @node Allocating memory from the 64 bit storage pool
28074 @subsubsection Allocating memory from the 64-bit storage pool
28077 By default, all allocations -- for both pool-specific and general
28078 access types -- use the 64-bit storage pool. To override
28079 this default, for an individual access type or globally, see
28080 @ref{Access types and 32/64-bit allocation}.
28082 @node Restrictions on use of 64 bit objects
28083 @subsubsection Restrictions on use of 64-bit objects
28086 Taking the address of an object allocated from a 64-bit storage pool,
28087 and then passing this address to a subprogram expecting
28088 @code{System.Short_Address},
28089 or assigning it to a variable of type @code{Short_Address}, will cause
28090 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
28091 (@pxref{Making code 64 bit clean}), or checks are suppressed,
28092 no exception is raised and execution
28093 will become erroneous.
28095 @node STARLET and other predefined libraries
28096 @subsubsection STARLET and other predefined libraries
28099 All code that comes as part of GNAT is 64-bit clean, but the
28100 restrictions given in @ref{Restrictions on use of 64 bit objects},
28101 still apply. Look at the package
28102 specs to see in which contexts objects allocated
28103 in 64-bit address space are acceptable.
28105 @node Technical details
28106 @subsection Technical details
28109 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
28110 Ada standard with respect to the type of @code{System.Address}. Previous
28111 versions of @value{EDITION} have defined this type as private and implemented it as a
28114 In order to allow defining @code{System.Short_Address} as a proper subtype,
28115 and to match the implicit sign extension in parameter passing,
28116 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
28117 visible (i.e., non-private) integer type.
28118 Standard operations on the type, such as the binary operators ``+'', ``-'',
28119 etc., that take @code{Address} operands and return an @code{Address} result,
28120 have been hidden by declaring these
28121 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
28122 ambiguities that would otherwise result from overloading.
28123 (Note that, although @code{Address} is a visible integer type,
28124 good programming practice dictates against exploiting the type's
28125 integer properties such as literals, since this will compromise
28128 Defining @code{Address} as a visible integer type helps achieve
28129 maximum compatibility for existing Ada code,
28130 without sacrificing the capabilities of the 64-bit architecture.
28133 @c ************************************************
28135 @node Microsoft Windows Topics
28136 @appendix Microsoft Windows Topics
28142 This chapter describes topics that are specific to the Microsoft Windows
28143 platforms (NT, 2000, and XP Professional).
28146 * Using GNAT on Windows::
28147 * Using a network installation of GNAT::
28148 * CONSOLE and WINDOWS subsystems::
28149 * Temporary Files::
28150 * Mixed-Language Programming on Windows::
28151 * Windows Calling Conventions::
28152 * Introduction to Dynamic Link Libraries (DLLs)::
28153 * Using DLLs with GNAT::
28154 * Building DLLs with GNAT Project files::
28155 * Building DLLs with GNAT::
28156 * Building DLLs with gnatdll::
28157 * GNAT and Windows Resources::
28158 * Debugging a DLL::
28159 * Setting Stack Size from gnatlink::
28160 * Setting Heap Size from gnatlink::
28163 @node Using GNAT on Windows
28164 @section Using GNAT on Windows
28167 One of the strengths of the GNAT technology is that its tool set
28168 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
28169 @code{gdb} debugger, etc.) is used in the same way regardless of the
28172 On Windows this tool set is complemented by a number of Microsoft-specific
28173 tools that have been provided to facilitate interoperability with Windows
28174 when this is required. With these tools:
28179 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
28183 You can use any Dynamically Linked Library (DLL) in your Ada code (both
28184 relocatable and non-relocatable DLLs are supported).
28187 You can build Ada DLLs for use in other applications. These applications
28188 can be written in a language other than Ada (e.g., C, C++, etc). Again both
28189 relocatable and non-relocatable Ada DLLs are supported.
28192 You can include Windows resources in your Ada application.
28195 You can use or create COM/DCOM objects.
28199 Immediately below are listed all known general GNAT-for-Windows restrictions.
28200 Other restrictions about specific features like Windows Resources and DLLs
28201 are listed in separate sections below.
28206 It is not possible to use @code{GetLastError} and @code{SetLastError}
28207 when tasking, protected records, or exceptions are used. In these
28208 cases, in order to implement Ada semantics, the GNAT run-time system
28209 calls certain Win32 routines that set the last error variable to 0 upon
28210 success. It should be possible to use @code{GetLastError} and
28211 @code{SetLastError} when tasking, protected record, and exception
28212 features are not used, but it is not guaranteed to work.
28215 It is not possible to link against Microsoft C++ libraries except for
28216 import libraries. Interfacing must be done by the mean of DLLs.
28219 It is possible to link against Microsoft C libraries. Yet the preferred
28220 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
28221 doesn't require having two different development environments and makes the
28222 inter-language debugging experience smoother.
28225 When the compilation environment is located on FAT32 drives, users may
28226 experience recompilations of the source files that have not changed if
28227 Daylight Saving Time (DST) state has changed since the last time files
28228 were compiled. NTFS drives do not have this problem.
28231 No components of the GNAT toolset use any entries in the Windows
28232 registry. The only entries that can be created are file associations and
28233 PATH settings, provided the user has chosen to create them at installation
28234 time, as well as some minimal book-keeping information needed to correctly
28235 uninstall or integrate different GNAT products.
28238 @node Using a network installation of GNAT
28239 @section Using a network installation of GNAT
28242 Make sure the system on which GNAT is installed is accessible from the
28243 current machine, i.e., the install location is shared over the network.
28244 Shared resources are accessed on Windows by means of UNC paths, which
28245 have the format @code{\\server\sharename\path}
28247 In order to use such a network installation, simply add the UNC path of the
28248 @file{bin} directory of your GNAT installation in front of your PATH. For
28249 example, if GNAT is installed in @file{\GNAT} directory of a share location
28250 called @file{c-drive} on a machine @file{LOKI}, the following command will
28253 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
28255 Be aware that every compilation using the network installation results in the
28256 transfer of large amounts of data across the network and will likely cause
28257 serious performance penalty.
28259 @node CONSOLE and WINDOWS subsystems
28260 @section CONSOLE and WINDOWS subsystems
28261 @cindex CONSOLE Subsystem
28262 @cindex WINDOWS Subsystem
28266 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
28267 (which is the default subsystem) will always create a console when
28268 launching the application. This is not something desirable when the
28269 application has a Windows GUI. To get rid of this console the
28270 application must be using the @code{WINDOWS} subsystem. To do so
28271 the @option{-mwindows} linker option must be specified.
28274 $ gnatmake winprog -largs -mwindows
28277 @node Temporary Files
28278 @section Temporary Files
28279 @cindex Temporary files
28282 It is possible to control where temporary files gets created by setting
28283 the @env{TMP} environment variable. The file will be created:
28286 @item Under the directory pointed to by the @env{TMP} environment variable if
28287 this directory exists.
28289 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
28290 set (or not pointing to a directory) and if this directory exists.
28292 @item Under the current working directory otherwise.
28296 This allows you to determine exactly where the temporary
28297 file will be created. This is particularly useful in networked
28298 environments where you may not have write access to some
28301 @node Mixed-Language Programming on Windows
28302 @section Mixed-Language Programming on Windows
28305 Developing pure Ada applications on Windows is no different than on
28306 other GNAT-supported platforms. However, when developing or porting an
28307 application that contains a mix of Ada and C/C++, the choice of your
28308 Windows C/C++ development environment conditions your overall
28309 interoperability strategy.
28311 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
28312 your application, there are no Windows-specific restrictions that
28313 affect the overall interoperability with your Ada code. If you do want
28314 to use the Microsoft tools for your C++ code, you have two choices:
28318 Encapsulate your C++ code in a DLL to be linked with your Ada
28319 application. In this case, use the Microsoft or whatever environment to
28320 build the DLL and use GNAT to build your executable
28321 (@pxref{Using DLLs with GNAT}).
28324 Or you can encapsulate your Ada code in a DLL to be linked with the
28325 other part of your application. In this case, use GNAT to build the DLL
28326 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
28327 or whatever environment to build your executable.
28330 @node Windows Calling Conventions
28331 @section Windows Calling Conventions
28335 This section pertain only to Win32. On Win64 there is a single native
28336 calling convention. All convention specifiers are ignored on this
28340 * C Calling Convention::
28341 * Stdcall Calling Convention::
28342 * Win32 Calling Convention::
28343 * DLL Calling Convention::
28347 When a subprogram @code{F} (caller) calls a subprogram @code{G}
28348 (callee), there are several ways to push @code{G}'s parameters on the
28349 stack and there are several possible scenarios to clean up the stack
28350 upon @code{G}'s return. A calling convention is an agreed upon software
28351 protocol whereby the responsibilities between the caller (@code{F}) and
28352 the callee (@code{G}) are clearly defined. Several calling conventions
28353 are available for Windows:
28357 @code{C} (Microsoft defined)
28360 @code{Stdcall} (Microsoft defined)
28363 @code{Win32} (GNAT specific)
28366 @code{DLL} (GNAT specific)
28369 @node C Calling Convention
28370 @subsection @code{C} Calling Convention
28373 This is the default calling convention used when interfacing to C/C++
28374 routines compiled with either @command{gcc} or Microsoft Visual C++.
28376 In the @code{C} calling convention subprogram parameters are pushed on the
28377 stack by the caller from right to left. The caller itself is in charge of
28378 cleaning up the stack after the call. In addition, the name of a routine
28379 with @code{C} calling convention is mangled by adding a leading underscore.
28381 The name to use on the Ada side when importing (or exporting) a routine
28382 with @code{C} calling convention is the name of the routine. For
28383 instance the C function:
28386 int get_val (long);
28390 should be imported from Ada as follows:
28392 @smallexample @c ada
28394 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28395 pragma Import (C, Get_Val, External_Name => "get_val");
28400 Note that in this particular case the @code{External_Name} parameter could
28401 have been omitted since, when missing, this parameter is taken to be the
28402 name of the Ada entity in lower case. When the @code{Link_Name} parameter
28403 is missing, as in the above example, this parameter is set to be the
28404 @code{External_Name} with a leading underscore.
28406 When importing a variable defined in C, you should always use the @code{C}
28407 calling convention unless the object containing the variable is part of a
28408 DLL (in which case you should use the @code{Stdcall} calling
28409 convention, @pxref{Stdcall Calling Convention}).
28411 @node Stdcall Calling Convention
28412 @subsection @code{Stdcall} Calling Convention
28415 This convention, which was the calling convention used for Pascal
28416 programs, is used by Microsoft for all the routines in the Win32 API for
28417 efficiency reasons. It must be used to import any routine for which this
28418 convention was specified.
28420 In the @code{Stdcall} calling convention subprogram parameters are pushed
28421 on the stack by the caller from right to left. The callee (and not the
28422 caller) is in charge of cleaning the stack on routine exit. In addition,
28423 the name of a routine with @code{Stdcall} calling convention is mangled by
28424 adding a leading underscore (as for the @code{C} calling convention) and a
28425 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
28426 bytes) of the parameters passed to the routine.
28428 The name to use on the Ada side when importing a C routine with a
28429 @code{Stdcall} calling convention is the name of the C routine. The leading
28430 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
28431 the compiler. For instance the Win32 function:
28434 @b{APIENTRY} int get_val (long);
28438 should be imported from Ada as follows:
28440 @smallexample @c ada
28442 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28443 pragma Import (Stdcall, Get_Val);
28444 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
28449 As for the @code{C} calling convention, when the @code{External_Name}
28450 parameter is missing, it is taken to be the name of the Ada entity in lower
28451 case. If instead of writing the above import pragma you write:
28453 @smallexample @c ada
28455 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28456 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
28461 then the imported routine is @code{_retrieve_val@@4}. However, if instead
28462 of specifying the @code{External_Name} parameter you specify the
28463 @code{Link_Name} as in the following example:
28465 @smallexample @c ada
28467 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
28468 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
28473 then the imported routine is @code{retrieve_val}, that is, there is no
28474 decoration at all. No leading underscore and no Stdcall suffix
28475 @code{@@}@code{@var{nn}}.
28478 This is especially important as in some special cases a DLL's entry
28479 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
28480 name generated for a call has it.
28483 It is also possible to import variables defined in a DLL by using an
28484 import pragma for a variable. As an example, if a DLL contains a
28485 variable defined as:
28492 then, to access this variable from Ada you should write:
28494 @smallexample @c ada
28496 My_Var : Interfaces.C.int;
28497 pragma Import (Stdcall, My_Var);
28502 Note that to ease building cross-platform bindings this convention
28503 will be handled as a @code{C} calling convention on non-Windows platforms.
28505 @node Win32 Calling Convention
28506 @subsection @code{Win32} Calling Convention
28509 This convention, which is GNAT-specific is fully equivalent to the
28510 @code{Stdcall} calling convention described above.
28512 @node DLL Calling Convention
28513 @subsection @code{DLL} Calling Convention
28516 This convention, which is GNAT-specific is fully equivalent to the
28517 @code{Stdcall} calling convention described above.
28519 @node Introduction to Dynamic Link Libraries (DLLs)
28520 @section Introduction to Dynamic Link Libraries (DLLs)
28524 A Dynamically Linked Library (DLL) is a library that can be shared by
28525 several applications running under Windows. A DLL can contain any number of
28526 routines and variables.
28528 One advantage of DLLs is that you can change and enhance them without
28529 forcing all the applications that depend on them to be relinked or
28530 recompiled. However, you should be aware than all calls to DLL routines are
28531 slower since, as you will understand below, such calls are indirect.
28533 To illustrate the remainder of this section, suppose that an application
28534 wants to use the services of a DLL @file{API.dll}. To use the services
28535 provided by @file{API.dll} you must statically link against the DLL or
28536 an import library which contains a jump table with an entry for each
28537 routine and variable exported by the DLL. In the Microsoft world this
28538 import library is called @file{API.lib}. When using GNAT this import
28539 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
28540 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
28542 After you have linked your application with the DLL or the import library
28543 and you run your application, here is what happens:
28547 Your application is loaded into memory.
28550 The DLL @file{API.dll} is mapped into the address space of your
28551 application. This means that:
28555 The DLL will use the stack of the calling thread.
28558 The DLL will use the virtual address space of the calling process.
28561 The DLL will allocate memory from the virtual address space of the calling
28565 Handles (pointers) can be safely exchanged between routines in the DLL
28566 routines and routines in the application using the DLL.
28570 The entries in the jump table (from the import library @file{libAPI.dll.a}
28571 or @file{API.lib} or automatically created when linking against a DLL)
28572 which is part of your application are initialized with the addresses
28573 of the routines and variables in @file{API.dll}.
28576 If present in @file{API.dll}, routines @code{DllMain} or
28577 @code{DllMainCRTStartup} are invoked. These routines typically contain
28578 the initialization code needed for the well-being of the routines and
28579 variables exported by the DLL.
28583 There is an additional point which is worth mentioning. In the Windows
28584 world there are two kind of DLLs: relocatable and non-relocatable
28585 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
28586 in the target application address space. If the addresses of two
28587 non-relocatable DLLs overlap and these happen to be used by the same
28588 application, a conflict will occur and the application will run
28589 incorrectly. Hence, when possible, it is always preferable to use and
28590 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
28591 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
28592 User's Guide) removes the debugging symbols from the DLL but the DLL can
28593 still be relocated.
28595 As a side note, an interesting difference between Microsoft DLLs and
28596 Unix shared libraries, is the fact that on most Unix systems all public
28597 routines are exported by default in a Unix shared library, while under
28598 Windows it is possible (but not required) to list exported routines in
28599 a definition file (@pxref{The Definition File}).
28601 @node Using DLLs with GNAT
28602 @section Using DLLs with GNAT
28605 * Creating an Ada Spec for the DLL Services::
28606 * Creating an Import Library::
28610 To use the services of a DLL, say @file{API.dll}, in your Ada application
28615 The Ada spec for the routines and/or variables you want to access in
28616 @file{API.dll}. If not available this Ada spec must be built from the C/C++
28617 header files provided with the DLL.
28620 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
28621 mentioned an import library is a statically linked library containing the
28622 import table which will be filled at load time to point to the actual
28623 @file{API.dll} routines. Sometimes you don't have an import library for the
28624 DLL you want to use. The following sections will explain how to build
28625 one. Note that this is optional.
28628 The actual DLL, @file{API.dll}.
28632 Once you have all the above, to compile an Ada application that uses the
28633 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
28634 you simply issue the command
28637 $ gnatmake my_ada_app -largs -lAPI
28641 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
28642 tells the GNAT linker to look for an import library. The linker will
28643 look for a library name in this specific order:
28646 @item @file{libAPI.dll.a}
28647 @item @file{API.dll.a}
28648 @item @file{libAPI.a}
28649 @item @file{API.lib}
28650 @item @file{libAPI.dll}
28651 @item @file{API.dll}
28654 The first three are the GNU style import libraries. The third is the
28655 Microsoft style import libraries. The last two are the actual DLL names.
28657 Note that if the Ada package spec for @file{API.dll} contains the
28660 @smallexample @c ada
28661 pragma Linker_Options ("-lAPI");
28665 you do not have to add @option{-largs -lAPI} at the end of the
28666 @command{gnatmake} command.
28668 If any one of the items above is missing you will have to create it
28669 yourself. The following sections explain how to do so using as an
28670 example a fictitious DLL called @file{API.dll}.
28672 @node Creating an Ada Spec for the DLL Services
28673 @subsection Creating an Ada Spec for the DLL Services
28676 A DLL typically comes with a C/C++ header file which provides the
28677 definitions of the routines and variables exported by the DLL. The Ada
28678 equivalent of this header file is a package spec that contains definitions
28679 for the imported entities. If the DLL you intend to use does not come with
28680 an Ada spec you have to generate one such spec yourself. For example if
28681 the header file of @file{API.dll} is a file @file{api.h} containing the
28682 following two definitions:
28694 then the equivalent Ada spec could be:
28696 @smallexample @c ada
28699 with Interfaces.C.Strings;
28704 function Get (Str : C.Strings.Chars_Ptr) return C.int;
28707 pragma Import (C, Get);
28708 pragma Import (DLL, Some_Var);
28715 Note that a variable is
28716 @strong{always imported with a DLL convention}. A function
28717 can have @code{C} or @code{Stdcall} convention.
28718 (@pxref{Windows Calling Conventions}).
28720 @node Creating an Import Library
28721 @subsection Creating an Import Library
28722 @cindex Import library
28725 * The Definition File::
28726 * GNAT-Style Import Library::
28727 * Microsoft-Style Import Library::
28731 If a Microsoft-style import library @file{API.lib} or a GNAT-style
28732 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
28733 with @file{API.dll} you can skip this section. You can also skip this
28734 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
28735 as in this case it is possible to link directly against the
28736 DLL. Otherwise read on.
28738 @node The Definition File
28739 @subsubsection The Definition File
28740 @cindex Definition file
28744 As previously mentioned, and unlike Unix systems, the list of symbols
28745 that are exported from a DLL must be provided explicitly in Windows.
28746 The main goal of a definition file is precisely that: list the symbols
28747 exported by a DLL. A definition file (usually a file with a @code{.def}
28748 suffix) has the following structure:
28753 @r{[}LIBRARY @var{name}@r{]}
28754 @r{[}DESCRIPTION @var{string}@r{]}
28764 @item LIBRARY @var{name}
28765 This section, which is optional, gives the name of the DLL.
28767 @item DESCRIPTION @var{string}
28768 This section, which is optional, gives a description string that will be
28769 embedded in the import library.
28772 This section gives the list of exported symbols (procedures, functions or
28773 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
28774 section of @file{API.def} looks like:
28788 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28789 (@pxref{Windows Calling Conventions}) for a Stdcall
28790 calling convention function in the exported symbols list.
28793 There can actually be other sections in a definition file, but these
28794 sections are not relevant to the discussion at hand.
28796 @node GNAT-Style Import Library
28797 @subsubsection GNAT-Style Import Library
28800 To create a static import library from @file{API.dll} with the GNAT tools
28801 you should proceed as follows:
28805 Create the definition file @file{API.def} (@pxref{The Definition File}).
28806 For that use the @code{dll2def} tool as follows:
28809 $ dll2def API.dll > API.def
28813 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28814 to standard output the list of entry points in the DLL. Note that if
28815 some routines in the DLL have the @code{Stdcall} convention
28816 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28817 suffix then you'll have to edit @file{api.def} to add it, and specify
28818 @option{-k} to @command{gnatdll} when creating the import library.
28821 Here are some hints to find the right @code{@@}@var{nn} suffix.
28825 If you have the Microsoft import library (.lib), it is possible to get
28826 the right symbols by using Microsoft @code{dumpbin} tool (see the
28827 corresponding Microsoft documentation for further details).
28830 $ dumpbin /exports api.lib
28834 If you have a message about a missing symbol at link time the compiler
28835 tells you what symbol is expected. You just have to go back to the
28836 definition file and add the right suffix.
28840 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28841 (@pxref{Using gnatdll}) as follows:
28844 $ gnatdll -e API.def -d API.dll
28848 @code{gnatdll} takes as input a definition file @file{API.def} and the
28849 name of the DLL containing the services listed in the definition file
28850 @file{API.dll}. The name of the static import library generated is
28851 computed from the name of the definition file as follows: if the
28852 definition file name is @var{xyz}@code{.def}, the import library name will
28853 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
28854 @option{-e} could have been removed because the name of the definition
28855 file (before the ``@code{.def}'' suffix) is the same as the name of the
28856 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
28859 @node Microsoft-Style Import Library
28860 @subsubsection Microsoft-Style Import Library
28863 With GNAT you can either use a GNAT-style or Microsoft-style import
28864 library. A Microsoft import library is needed only if you plan to make an
28865 Ada DLL available to applications developed with Microsoft
28866 tools (@pxref{Mixed-Language Programming on Windows}).
28868 To create a Microsoft-style import library for @file{API.dll} you
28869 should proceed as follows:
28873 Create the definition file @file{API.def} from the DLL. For this use either
28874 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28875 tool (see the corresponding Microsoft documentation for further details).
28878 Build the actual import library using Microsoft's @code{lib} utility:
28881 $ lib -machine:IX86 -def:API.def -out:API.lib
28885 If you use the above command the definition file @file{API.def} must
28886 contain a line giving the name of the DLL:
28893 See the Microsoft documentation for further details about the usage of
28897 @node Building DLLs with GNAT Project files
28898 @section Building DLLs with GNAT Project files
28899 @cindex DLLs, building
28902 There is nothing specific to Windows in the build process.
28903 @pxref{Library Projects}.
28906 Due to a system limitation, it is not possible under Windows to create threads
28907 when inside the @code{DllMain} routine which is used for auto-initialization
28908 of shared libraries, so it is not possible to have library level tasks in SALs.
28910 @node Building DLLs with GNAT
28911 @section Building DLLs with GNAT
28912 @cindex DLLs, building
28915 This section explain how to build DLLs using the GNAT built-in DLL
28916 support. With the following procedure it is straight forward to build
28917 and use DLLs with GNAT.
28921 @item building object files
28923 The first step is to build all objects files that are to be included
28924 into the DLL. This is done by using the standard @command{gnatmake} tool.
28926 @item building the DLL
28928 To build the DLL you must use @command{gcc}'s @option{-shared} and
28929 @option{-shared-libgcc} options. It is quite simple to use this method:
28932 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28935 It is important to note that in this case all symbols found in the
28936 object files are automatically exported. It is possible to restrict
28937 the set of symbols to export by passing to @command{gcc} a definition
28938 file, @pxref{The Definition File}. For example:
28941 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28944 If you use a definition file you must export the elaboration procedures
28945 for every package that required one. Elaboration procedures are named
28946 using the package name followed by "_E".
28948 @item preparing DLL to be used
28950 For the DLL to be used by client programs the bodies must be hidden
28951 from it and the .ali set with read-only attribute. This is very important
28952 otherwise GNAT will recompile all packages and will not actually use
28953 the code in the DLL. For example:
28957 $ copy *.ads *.ali api.dll apilib
28958 $ attrib +R apilib\*.ali
28963 At this point it is possible to use the DLL by directly linking
28964 against it. Note that you must use the GNAT shared runtime when using
28965 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28969 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28972 @node Building DLLs with gnatdll
28973 @section Building DLLs with gnatdll
28974 @cindex DLLs, building
28977 * Limitations When Using Ada DLLs from Ada::
28978 * Exporting Ada Entities::
28979 * Ada DLLs and Elaboration::
28980 * Ada DLLs and Finalization::
28981 * Creating a Spec for Ada DLLs::
28982 * Creating the Definition File::
28987 Note that it is preferred to use GNAT Project files
28988 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28989 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28991 This section explains how to build DLLs containing Ada code using
28992 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28993 remainder of this section.
28995 The steps required to build an Ada DLL that is to be used by Ada as well as
28996 non-Ada applications are as follows:
29000 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
29001 @code{Stdcall} calling convention to avoid any Ada name mangling for the
29002 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
29003 skip this step if you plan to use the Ada DLL only from Ada applications.
29006 Your Ada code must export an initialization routine which calls the routine
29007 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
29008 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
29009 routine exported by the Ada DLL must be invoked by the clients of the DLL
29010 to initialize the DLL.
29013 When useful, the DLL should also export a finalization routine which calls
29014 routine @code{adafinal} generated by @command{gnatbind} to perform the
29015 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
29016 The finalization routine exported by the Ada DLL must be invoked by the
29017 clients of the DLL when the DLL services are no further needed.
29020 You must provide a spec for the services exported by the Ada DLL in each
29021 of the programming languages to which you plan to make the DLL available.
29024 You must provide a definition file listing the exported entities
29025 (@pxref{The Definition File}).
29028 Finally you must use @code{gnatdll} to produce the DLL and the import
29029 library (@pxref{Using gnatdll}).
29033 Note that a relocatable DLL stripped using the @code{strip}
29034 binutils tool will not be relocatable anymore. To build a DLL without
29035 debug information pass @code{-largs -s} to @code{gnatdll}. This
29036 restriction does not apply to a DLL built using a Library Project.
29037 @pxref{Library Projects}.
29039 @node Limitations When Using Ada DLLs from Ada
29040 @subsection Limitations When Using Ada DLLs from Ada
29043 When using Ada DLLs from Ada applications there is a limitation users
29044 should be aware of. Because on Windows the GNAT run time is not in a DLL of
29045 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
29046 each Ada DLL includes the services of the GNAT run time that are necessary
29047 to the Ada code inside the DLL. As a result, when an Ada program uses an
29048 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
29049 one in the main program.
29051 It is therefore not possible to exchange GNAT run-time objects between the
29052 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
29053 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
29056 It is completely safe to exchange plain elementary, array or record types,
29057 Windows object handles, etc.
29059 @node Exporting Ada Entities
29060 @subsection Exporting Ada Entities
29061 @cindex Export table
29064 Building a DLL is a way to encapsulate a set of services usable from any
29065 application. As a result, the Ada entities exported by a DLL should be
29066 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
29067 any Ada name mangling. As an example here is an Ada package
29068 @code{API}, spec and body, exporting two procedures, a function, and a
29071 @smallexample @c ada
29074 with Interfaces.C; use Interfaces;
29076 Count : C.int := 0;
29077 function Factorial (Val : C.int) return C.int;
29079 procedure Initialize_API;
29080 procedure Finalize_API;
29081 -- Initialization & Finalization routines. More in the next section.
29083 pragma Export (C, Initialize_API);
29084 pragma Export (C, Finalize_API);
29085 pragma Export (C, Count);
29086 pragma Export (C, Factorial);
29092 @smallexample @c ada
29095 package body API is
29096 function Factorial (Val : C.int) return C.int is
29099 Count := Count + 1;
29100 for K in 1 .. Val loop
29106 procedure Initialize_API is
29108 pragma Import (C, Adainit);
29111 end Initialize_API;
29113 procedure Finalize_API is
29114 procedure Adafinal;
29115 pragma Import (C, Adafinal);
29125 If the Ada DLL you are building will only be used by Ada applications
29126 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
29127 convention. As an example, the previous package could be written as
29130 @smallexample @c ada
29134 Count : Integer := 0;
29135 function Factorial (Val : Integer) return Integer;
29137 procedure Initialize_API;
29138 procedure Finalize_API;
29139 -- Initialization and Finalization routines.
29145 @smallexample @c ada
29148 package body API is
29149 function Factorial (Val : Integer) return Integer is
29150 Fact : Integer := 1;
29152 Count := Count + 1;
29153 for K in 1 .. Val loop
29160 -- The remainder of this package body is unchanged.
29167 Note that if you do not export the Ada entities with a @code{C} or
29168 @code{Stdcall} convention you will have to provide the mangled Ada names
29169 in the definition file of the Ada DLL
29170 (@pxref{Creating the Definition File}).
29172 @node Ada DLLs and Elaboration
29173 @subsection Ada DLLs and Elaboration
29174 @cindex DLLs and elaboration
29177 The DLL that you are building contains your Ada code as well as all the
29178 routines in the Ada library that are needed by it. The first thing a
29179 user of your DLL must do is elaborate the Ada code
29180 (@pxref{Elaboration Order Handling in GNAT}).
29182 To achieve this you must export an initialization routine
29183 (@code{Initialize_API} in the previous example), which must be invoked
29184 before using any of the DLL services. This elaboration routine must call
29185 the Ada elaboration routine @code{adainit} generated by the GNAT binder
29186 (@pxref{Binding with Non-Ada Main Programs}). See the body of
29187 @code{Initialize_Api} for an example. Note that the GNAT binder is
29188 automatically invoked during the DLL build process by the @code{gnatdll}
29189 tool (@pxref{Using gnatdll}).
29191 When a DLL is loaded, Windows systematically invokes a routine called
29192 @code{DllMain}. It would therefore be possible to call @code{adainit}
29193 directly from @code{DllMain} without having to provide an explicit
29194 initialization routine. Unfortunately, it is not possible to call
29195 @code{adainit} from the @code{DllMain} if your program has library level
29196 tasks because access to the @code{DllMain} entry point is serialized by
29197 the system (that is, only a single thread can execute ``through'' it at a
29198 time), which means that the GNAT run time will deadlock waiting for the
29199 newly created task to complete its initialization.
29201 @node Ada DLLs and Finalization
29202 @subsection Ada DLLs and Finalization
29203 @cindex DLLs and finalization
29206 When the services of an Ada DLL are no longer needed, the client code should
29207 invoke the DLL finalization routine, if available. The DLL finalization
29208 routine is in charge of releasing all resources acquired by the DLL. In the
29209 case of the Ada code contained in the DLL, this is achieved by calling
29210 routine @code{adafinal} generated by the GNAT binder
29211 (@pxref{Binding with Non-Ada Main Programs}).
29212 See the body of @code{Finalize_Api} for an
29213 example. As already pointed out the GNAT binder is automatically invoked
29214 during the DLL build process by the @code{gnatdll} tool
29215 (@pxref{Using gnatdll}).
29217 @node Creating a Spec for Ada DLLs
29218 @subsection Creating a Spec for Ada DLLs
29221 To use the services exported by the Ada DLL from another programming
29222 language (e.g.@: C), you have to translate the specs of the exported Ada
29223 entities in that language. For instance in the case of @code{API.dll},
29224 the corresponding C header file could look like:
29229 extern int *_imp__count;
29230 #define count (*_imp__count)
29231 int factorial (int);
29237 It is important to understand that when building an Ada DLL to be used by
29238 other Ada applications, you need two different specs for the packages
29239 contained in the DLL: one for building the DLL and the other for using
29240 the DLL. This is because the @code{DLL} calling convention is needed to
29241 use a variable defined in a DLL, but when building the DLL, the variable
29242 must have either the @code{Ada} or @code{C} calling convention. As an
29243 example consider a DLL comprising the following package @code{API}:
29245 @smallexample @c ada
29249 Count : Integer := 0;
29251 -- Remainder of the package omitted.
29258 After producing a DLL containing package @code{API}, the spec that
29259 must be used to import @code{API.Count} from Ada code outside of the
29262 @smallexample @c ada
29267 pragma Import (DLL, Count);
29273 @node Creating the Definition File
29274 @subsection Creating the Definition File
29277 The definition file is the last file needed to build the DLL. It lists
29278 the exported symbols. As an example, the definition file for a DLL
29279 containing only package @code{API} (where all the entities are exported
29280 with a @code{C} calling convention) is:
29295 If the @code{C} calling convention is missing from package @code{API},
29296 then the definition file contains the mangled Ada names of the above
29297 entities, which in this case are:
29306 api__initialize_api
29311 @node Using gnatdll
29312 @subsection Using @code{gnatdll}
29316 * gnatdll Example::
29317 * gnatdll behind the Scenes::
29322 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
29323 and non-Ada sources that make up your DLL have been compiled.
29324 @code{gnatdll} is actually in charge of two distinct tasks: build the
29325 static import library for the DLL and the actual DLL. The form of the
29326 @code{gnatdll} command is
29330 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29331 @c Expanding @ovar macro inline (explanation in macro def comments)
29332 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
29337 where @var{list-of-files} is a list of ALI and object files. The object
29338 file list must be the exact list of objects corresponding to the non-Ada
29339 sources whose services are to be included in the DLL. The ALI file list
29340 must be the exact list of ALI files for the corresponding Ada sources
29341 whose services are to be included in the DLL. If @var{list-of-files} is
29342 missing, only the static import library is generated.
29345 You may specify any of the following switches to @code{gnatdll}:
29348 @c @item -a@ovar{address}
29349 @c Expanding @ovar macro inline (explanation in macro def comments)
29350 @item -a@r{[}@var{address}@r{]}
29351 @cindex @option{-a} (@code{gnatdll})
29352 Build a non-relocatable DLL at @var{address}. If @var{address} is not
29353 specified the default address @var{0x11000000} will be used. By default,
29354 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
29355 advise the reader to build relocatable DLL.
29357 @item -b @var{address}
29358 @cindex @option{-b} (@code{gnatdll})
29359 Set the relocatable DLL base address. By default the address is
29362 @item -bargs @var{opts}
29363 @cindex @option{-bargs} (@code{gnatdll})
29364 Binder options. Pass @var{opts} to the binder.
29366 @item -d @var{dllfile}
29367 @cindex @option{-d} (@code{gnatdll})
29368 @var{dllfile} is the name of the DLL. This switch must be present for
29369 @code{gnatdll} to do anything. The name of the generated import library is
29370 obtained algorithmically from @var{dllfile} as shown in the following
29371 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
29372 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
29373 by option @option{-e}) is obtained algorithmically from @var{dllfile}
29374 as shown in the following example:
29375 if @var{dllfile} is @code{xyz.dll}, the definition
29376 file used is @code{xyz.def}.
29378 @item -e @var{deffile}
29379 @cindex @option{-e} (@code{gnatdll})
29380 @var{deffile} is the name of the definition file.
29383 @cindex @option{-g} (@code{gnatdll})
29384 Generate debugging information. This information is stored in the object
29385 file and copied from there to the final DLL file by the linker,
29386 where it can be read by the debugger. You must use the
29387 @option{-g} switch if you plan on using the debugger or the symbolic
29391 @cindex @option{-h} (@code{gnatdll})
29392 Help mode. Displays @code{gnatdll} switch usage information.
29395 @cindex @option{-I} (@code{gnatdll})
29396 Direct @code{gnatdll} to search the @var{dir} directory for source and
29397 object files needed to build the DLL.
29398 (@pxref{Search Paths and the Run-Time Library (RTL)}).
29401 @cindex @option{-k} (@code{gnatdll})
29402 Removes the @code{@@}@var{nn} suffix from the import library's exported
29403 names, but keeps them for the link names. You must specify this
29404 option if you want to use a @code{Stdcall} function in a DLL for which
29405 the @code{@@}@var{nn} suffix has been removed. This is the case for most
29406 of the Windows NT DLL for example. This option has no effect when
29407 @option{-n} option is specified.
29409 @item -l @var{file}
29410 @cindex @option{-l} (@code{gnatdll})
29411 The list of ALI and object files used to build the DLL are listed in
29412 @var{file}, instead of being given in the command line. Each line in
29413 @var{file} contains the name of an ALI or object file.
29416 @cindex @option{-n} (@code{gnatdll})
29417 No Import. Do not create the import library.
29420 @cindex @option{-q} (@code{gnatdll})
29421 Quiet mode. Do not display unnecessary messages.
29424 @cindex @option{-v} (@code{gnatdll})
29425 Verbose mode. Display extra information.
29427 @item -largs @var{opts}
29428 @cindex @option{-largs} (@code{gnatdll})
29429 Linker options. Pass @var{opts} to the linker.
29432 @node gnatdll Example
29433 @subsubsection @code{gnatdll} Example
29436 As an example the command to build a relocatable DLL from @file{api.adb}
29437 once @file{api.adb} has been compiled and @file{api.def} created is
29440 $ gnatdll -d api.dll api.ali
29444 The above command creates two files: @file{libapi.dll.a} (the import
29445 library) and @file{api.dll} (the actual DLL). If you want to create
29446 only the DLL, just type:
29449 $ gnatdll -d api.dll -n api.ali
29453 Alternatively if you want to create just the import library, type:
29456 $ gnatdll -d api.dll
29459 @node gnatdll behind the Scenes
29460 @subsubsection @code{gnatdll} behind the Scenes
29463 This section details the steps involved in creating a DLL. @code{gnatdll}
29464 does these steps for you. Unless you are interested in understanding what
29465 goes on behind the scenes, you should skip this section.
29467 We use the previous example of a DLL containing the Ada package @code{API},
29468 to illustrate the steps necessary to build a DLL. The starting point is a
29469 set of objects that will make up the DLL and the corresponding ALI
29470 files. In the case of this example this means that @file{api.o} and
29471 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
29476 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
29477 the information necessary to generate relocation information for the
29483 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
29488 In addition to the base file, the @command{gnatlink} command generates an
29489 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
29490 asks @command{gnatlink} to generate the routines @code{DllMain} and
29491 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
29492 is loaded into memory.
29495 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
29496 export table (@file{api.exp}). The export table contains the relocation
29497 information in a form which can be used during the final link to ensure
29498 that the Windows loader is able to place the DLL anywhere in memory.
29502 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29503 --output-exp api.exp
29508 @code{gnatdll} builds the base file using the new export table. Note that
29509 @command{gnatbind} must be called once again since the binder generated file
29510 has been deleted during the previous call to @command{gnatlink}.
29515 $ gnatlink api -o api.jnk api.exp -mdll
29516 -Wl,--base-file,api.base
29521 @code{gnatdll} builds the new export table using the new base file and
29522 generates the DLL import library @file{libAPI.dll.a}.
29526 $ dlltool --dllname api.dll --def api.def --base-file api.base \
29527 --output-exp api.exp --output-lib libAPI.a
29532 Finally @code{gnatdll} builds the relocatable DLL using the final export
29538 $ gnatlink api api.exp -o api.dll -mdll
29543 @node Using dlltool
29544 @subsubsection Using @code{dlltool}
29547 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
29548 DLLs and static import libraries. This section summarizes the most
29549 common @code{dlltool} switches. The form of the @code{dlltool} command
29553 @c $ dlltool @ovar{switches}
29554 @c Expanding @ovar macro inline (explanation in macro def comments)
29555 $ dlltool @r{[}@var{switches}@r{]}
29559 @code{dlltool} switches include:
29562 @item --base-file @var{basefile}
29563 @cindex @option{--base-file} (@command{dlltool})
29564 Read the base file @var{basefile} generated by the linker. This switch
29565 is used to create a relocatable DLL.
29567 @item --def @var{deffile}
29568 @cindex @option{--def} (@command{dlltool})
29569 Read the definition file.
29571 @item --dllname @var{name}
29572 @cindex @option{--dllname} (@command{dlltool})
29573 Gives the name of the DLL. This switch is used to embed the name of the
29574 DLL in the static import library generated by @code{dlltool} with switch
29575 @option{--output-lib}.
29578 @cindex @option{-k} (@command{dlltool})
29579 Kill @code{@@}@var{nn} from exported names
29580 (@pxref{Windows Calling Conventions}
29581 for a discussion about @code{Stdcall}-style symbols.
29584 @cindex @option{--help} (@command{dlltool})
29585 Prints the @code{dlltool} switches with a concise description.
29587 @item --output-exp @var{exportfile}
29588 @cindex @option{--output-exp} (@command{dlltool})
29589 Generate an export file @var{exportfile}. The export file contains the
29590 export table (list of symbols in the DLL) and is used to create the DLL.
29592 @item --output-lib @var{libfile}
29593 @cindex @option{--output-lib} (@command{dlltool})
29594 Generate a static import library @var{libfile}.
29597 @cindex @option{-v} (@command{dlltool})
29600 @item --as @var{assembler-name}
29601 @cindex @option{--as} (@command{dlltool})
29602 Use @var{assembler-name} as the assembler. The default is @code{as}.
29605 @node GNAT and Windows Resources
29606 @section GNAT and Windows Resources
29607 @cindex Resources, windows
29610 * Building Resources::
29611 * Compiling Resources::
29612 * Using Resources::
29616 Resources are an easy way to add Windows specific objects to your
29617 application. The objects that can be added as resources include:
29626 @item string tables
29636 @item version information
29639 For example, a version information resource can be defined as follow and
29640 embedded into an executable or DLL:
29642 A version information resource can be used to embed information into an
29643 executable or a DLL. These information can be viewed using the file properties
29644 from the Windows Explorer. Here is an example of a version information
29650 FILEVERSION 1,0,0,0
29651 PRODUCTVERSION 1,0,0,0
29653 BLOCK "StringFileInfo"
29657 VALUE "CompanyName", "My Company Name"
29658 VALUE "FileDescription", "My application"
29659 VALUE "FileVersion", "1.0"
29660 VALUE "InternalName", "my_app"
29661 VALUE "LegalCopyright", "My Name"
29662 VALUE "OriginalFilename", "my_app.exe"
29663 VALUE "ProductName", "My App"
29664 VALUE "ProductVersion", "1.0"
29668 BLOCK "VarFileInfo"
29670 VALUE "Translation", 0x809, 1252
29676 The value @code{0809} (langID) is for the U.K English language and
29677 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
29681 This section explains how to build, compile and use resources. Note that this
29682 section does not cover all resource objects, for a complete description see
29683 the corresponding Microsoft documentation.
29685 @node Building Resources
29686 @subsection Building Resources
29687 @cindex Resources, building
29690 A resource file is an ASCII file. By convention resource files have an
29691 @file{.rc} extension.
29692 The easiest way to build a resource file is to use Microsoft tools
29693 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
29694 @code{dlgedit.exe} to build dialogs.
29695 It is always possible to build an @file{.rc} file yourself by writing a
29698 It is not our objective to explain how to write a resource file. A
29699 complete description of the resource script language can be found in the
29700 Microsoft documentation.
29702 @node Compiling Resources
29703 @subsection Compiling Resources
29706 @cindex Resources, compiling
29709 This section describes how to build a GNAT-compatible (COFF) object file
29710 containing the resources. This is done using the Resource Compiler
29711 @code{windres} as follows:
29714 $ windres -i myres.rc -o myres.o
29718 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
29719 file. You can specify an alternate preprocessor (usually named
29720 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
29721 parameter. A list of all possible options may be obtained by entering
29722 the command @code{windres} @option{--help}.
29724 It is also possible to use the Microsoft resource compiler @code{rc.exe}
29725 to produce a @file{.res} file (binary resource file). See the
29726 corresponding Microsoft documentation for further details. In this case
29727 you need to use @code{windres} to translate the @file{.res} file to a
29728 GNAT-compatible object file as follows:
29731 $ windres -i myres.res -o myres.o
29734 @node Using Resources
29735 @subsection Using Resources
29736 @cindex Resources, using
29739 To include the resource file in your program just add the
29740 GNAT-compatible object file for the resource(s) to the linker
29741 arguments. With @command{gnatmake} this is done by using the @option{-largs}
29745 $ gnatmake myprog -largs myres.o
29748 @node Debugging a DLL
29749 @section Debugging a DLL
29750 @cindex DLL debugging
29753 * Program and DLL Both Built with GCC/GNAT::
29754 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
29758 Debugging a DLL is similar to debugging a standard program. But
29759 we have to deal with two different executable parts: the DLL and the
29760 program that uses it. We have the following four possibilities:
29764 The program and the DLL are built with @code{GCC/GNAT}.
29766 The program is built with foreign tools and the DLL is built with
29769 The program is built with @code{GCC/GNAT} and the DLL is built with
29774 In this section we address only cases one and two above.
29775 There is no point in trying to debug
29776 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
29777 information in it. To do so you must use a debugger compatible with the
29778 tools suite used to build the DLL.
29780 @node Program and DLL Both Built with GCC/GNAT
29781 @subsection Program and DLL Both Built with GCC/GNAT
29784 This is the simplest case. Both the DLL and the program have @code{GDB}
29785 compatible debugging information. It is then possible to break anywhere in
29786 the process. Let's suppose here that the main procedure is named
29787 @code{ada_main} and that in the DLL there is an entry point named
29791 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29792 program must have been built with the debugging information (see GNAT -g
29793 switch). Here are the step-by-step instructions for debugging it:
29796 @item Launch @code{GDB} on the main program.
29802 @item Start the program and stop at the beginning of the main procedure
29809 This step is required to be able to set a breakpoint inside the DLL. As long
29810 as the program is not run, the DLL is not loaded. This has the
29811 consequence that the DLL debugging information is also not loaded, so it is not
29812 possible to set a breakpoint in the DLL.
29814 @item Set a breakpoint inside the DLL
29817 (gdb) break ada_dll
29824 At this stage a breakpoint is set inside the DLL. From there on
29825 you can use the standard approach to debug the whole program
29826 (@pxref{Running and Debugging Ada Programs}).
29829 @c This used to work, probably because the DLLs were non-relocatable
29830 @c keep this section around until the problem is sorted out.
29832 To break on the @code{DllMain} routine it is not possible to follow
29833 the procedure above. At the time the program stop on @code{ada_main}
29834 the @code{DllMain} routine as already been called. Either you can use
29835 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29838 @item Launch @code{GDB} on the main program.
29844 @item Load DLL symbols
29847 (gdb) add-sym api.dll
29850 @item Set a breakpoint inside the DLL
29853 (gdb) break ada_dll.adb:45
29856 Note that at this point it is not possible to break using the routine symbol
29857 directly as the program is not yet running. The solution is to break
29858 on the proper line (break in @file{ada_dll.adb} line 45).
29860 @item Start the program
29869 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
29870 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
29873 * Debugging the DLL Directly::
29874 * Attaching to a Running Process::
29878 In this case things are slightly more complex because it is not possible to
29879 start the main program and then break at the beginning to load the DLL and the
29880 associated DLL debugging information. It is not possible to break at the
29881 beginning of the program because there is no @code{GDB} debugging information,
29882 and therefore there is no direct way of getting initial control. This
29883 section addresses this issue by describing some methods that can be used
29884 to break somewhere in the DLL to debug it.
29887 First suppose that the main procedure is named @code{main} (this is for
29888 example some C code built with Microsoft Visual C) and that there is a
29889 DLL named @code{test.dll} containing an Ada entry point named
29893 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29894 been built with debugging information (see GNAT -g option).
29896 @node Debugging the DLL Directly
29897 @subsubsection Debugging the DLL Directly
29901 Find out the executable starting address
29904 $ objdump --file-header main.exe
29907 The starting address is reported on the last line. For example:
29910 main.exe: file format pei-i386
29911 architecture: i386, flags 0x0000010a:
29912 EXEC_P, HAS_DEBUG, D_PAGED
29913 start address 0x00401010
29917 Launch the debugger on the executable.
29924 Set a breakpoint at the starting address, and launch the program.
29927 $ (gdb) break *0x00401010
29931 The program will stop at the given address.
29934 Set a breakpoint on a DLL subroutine.
29937 (gdb) break ada_dll.adb:45
29940 Or if you want to break using a symbol on the DLL, you need first to
29941 select the Ada language (language used by the DLL).
29944 (gdb) set language ada
29945 (gdb) break ada_dll
29949 Continue the program.
29956 This will run the program until it reaches the breakpoint that has been
29957 set. From that point you can use the standard way to debug a program
29958 as described in (@pxref{Running and Debugging Ada Programs}).
29963 It is also possible to debug the DLL by attaching to a running process.
29965 @node Attaching to a Running Process
29966 @subsubsection Attaching to a Running Process
29967 @cindex DLL debugging, attach to process
29970 With @code{GDB} it is always possible to debug a running process by
29971 attaching to it. It is possible to debug a DLL this way. The limitation
29972 of this approach is that the DLL must run long enough to perform the
29973 attach operation. It may be useful for instance to insert a time wasting
29974 loop in the code of the DLL to meet this criterion.
29978 @item Launch the main program @file{main.exe}.
29984 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29985 that the process PID for @file{main.exe} is 208.
29993 @item Attach to the running process to be debugged.
29999 @item Load the process debugging information.
30002 (gdb) symbol-file main.exe
30005 @item Break somewhere in the DLL.
30008 (gdb) break ada_dll
30011 @item Continue process execution.
30020 This last step will resume the process execution, and stop at
30021 the breakpoint we have set. From there you can use the standard
30022 approach to debug a program as described in
30023 (@pxref{Running and Debugging Ada Programs}).
30025 @node Setting Stack Size from gnatlink
30026 @section Setting Stack Size from @command{gnatlink}
30029 It is possible to specify the program stack size at link time. On modern
30030 versions of Windows, starting with XP, this is mostly useful to set the size of
30031 the main stack (environment task). The other task stacks are set with pragma
30032 Storage_Size or with the @command{gnatbind -d} command.
30034 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
30035 reserve size of individual tasks, the link-time stack size applies to all
30036 tasks, and pragma Storage_Size has no effect.
30037 In particular, Stack Overflow checks are made against this
30038 link-time specified size.
30040 This setting can be done with
30041 @command{gnatlink} using either:
30045 @item using @option{-Xlinker} linker option
30048 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
30051 This sets the stack reserve size to 0x10000 bytes and the stack commit
30052 size to 0x1000 bytes.
30054 @item using @option{-Wl} linker option
30057 $ gnatlink hello -Wl,--stack=0x1000000
30060 This sets the stack reserve size to 0x1000000 bytes. Note that with
30061 @option{-Wl} option it is not possible to set the stack commit size
30062 because the coma is a separator for this option.
30066 @node Setting Heap Size from gnatlink
30067 @section Setting Heap Size from @command{gnatlink}
30070 Under Windows systems, it is possible to specify the program heap size from
30071 @command{gnatlink} using either:
30075 @item using @option{-Xlinker} linker option
30078 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
30081 This sets the heap reserve size to 0x10000 bytes and the heap commit
30082 size to 0x1000 bytes.
30084 @item using @option{-Wl} linker option
30087 $ gnatlink hello -Wl,--heap=0x1000000
30090 This sets the heap reserve size to 0x1000000 bytes. Note that with
30091 @option{-Wl} option it is not possible to set the heap commit size
30092 because the coma is a separator for this option.
30098 @c **********************************
30099 @c * GNU Free Documentation License *
30100 @c **********************************
30102 @c GNU Free Documentation License
30104 @node Index,,GNU Free Documentation License, Top
30110 @c Put table of contents at end, otherwise it precedes the "title page" in
30111 @c the .txt version
30112 @c Edit the pdf file to move the contents to the beginning, after the title